Esempio n. 1
0
 /// <summary>
 /// Creates a delegate which can get the value of an indexer matching <paramref name="bindingFlags"/>.
 /// </summary>
 /// <param name="type">The type which the indexer belongs to.</param>
 /// <param name="bindingFlags">The binding flags used to lookup the indexer.</param>
 /// <param name="parameterTypes">The types of the indexer parameters (must be in the right order).</param>
 /// <returns>The delegate which can get the value of an indexer.</returns>
 public static MethodInvoker DelegateForGetIndexer( this Type type, Flags bindingFlags,
                                                    params Type[] parameterTypes )
 {
     return (MethodInvoker)
         new MethodInvocationEmitter( type, bindingFlags, Constants.IndexerGetterName, parameterTypes ).
             GetDelegate();
 }
Esempio n. 2
0
        /// <summary>
        /// 選択データのタイトルをファイルに出力する。
        /// </summary>
        /// <param name="data">項目データ</param>
        public void AllDataTitle( Datas data )
        {
            SaveFileDialog sfd = new SaveFileDialog();

            flags = uXml.read();

            sfd.FileName = "全データタイトル一覧.txt";
            if( sfd.ShowDialog() == DialogResult.OK ){

                StreamWriter ofs = new StreamWriter( sfd.FileName );
                for( int i=0; i<data.data.Count; i++){

                    //フィルターに引っかかる物は表示しない
                    if (uXml.check(data.data[i].now_status, flags) != true)
                    {
                        continue;
                    }

                    //ofs.WriteLine("{0}\t:{1}", data.data[i].getStatus().ToString(), data.data[i].name.ToString());
                    ofs.WriteLine("{1}(期限:{0})", data.data[i].getStatusTextForDisp().ToString(), data.data[i].name.ToString());
                }
                ofs.Close();

                //MessageBox.Show(sfd.FileName.ToString()+"に保存しました。");
                SaveFile(sfd.FileName.ToString());

            }
        }
Esempio n. 3
0
 void Awake()
 {
     GameObject c = GameObject.FindGameObjectWithTag ("GameController");
     flags = c.GetComponent<Flags>();
     transition = GameObject.FindGameObjectWithTag("Fader").GetComponent<SceneTransition>();
     flags.AddCutsceneFlag(cutsceneDialogue.name);
 }
Esempio n. 4
0
 public MapCallInfo(Type targetType, Type[] genericTypes, Flags bindingFlags, MemberTypes memberTypes, string name, Type[] parameterTypes, MemberInfo memberInfo, bool isReadOperation, Type sourceType, MemberTypes sourceMemberTypes, MemberTypes targetMemberTypes, string[] names) : base(targetType, genericTypes, bindingFlags, memberTypes, name, parameterTypes, memberInfo, isReadOperation)
 {
     SourceType = sourceType;
     SourceMemberTypes = sourceMemberTypes;
     TargetMemberTypes = targetMemberTypes;
     Names = names;
 }
Esempio n. 5
0
 public void SetFlag(Flags flag, bool b)
 {
     if (b)
         StatusRegister |= (byte)flag;
     else
         StatusRegister &= (byte)~flag;
 }
        private JObject getRequestJSONObject(List<Placement> placements, Flags flags = null, string medium = null, string frame = null, string title = null, bool useIframe = false)
        {
            JObject jsonObject = new JObject();

            if (placements != null && placements.Count > 0) {
                JArray placementsJSONArray = new JArray();
                foreach (var placement in placements) {
                    placementsJSONArray.Add(JObject.Parse(base.jsonSerializer.Serialize(placement)));
                }
                jsonObject.Add("placements", placementsJSONArray);
            }

            if (flags != null) {
                jsonObject.Add("flags", JObject.Parse(base.jsonSerializer.Serialize(flags)));
            }

            if (medium != null) {
                jsonObject.Add("medium", new JValue(medium));
            }

            if (frame != null) {
                jsonObject.Add("frame", new JValue(frame));
            }

            if (title != null) {
                jsonObject.Add("title", new JValue(title));
            }

            jsonObject.Add("useiframe", new JValue(useIframe));

            return jsonObject;
        }
Esempio n. 7
0
        public static void SendMail(Flags flag)
        {
            Flags result = 0x00;
            // Define action-lookup
            int intero = 1;
            //string stringa = "email";

            var actionsByFlag = new Dictionary<Flags, Func<int, Flags>>
            {
                { Flags.Notify, Notify },
                { Flags.Email, Email }
            };

            // Find applicable actions
            var actions = actionsByFlag.Where(kvp => (flag & kvp.Key) == kvp.Key)
                                       .Select(kvp => kvp.Value);

            //Execute applicable actions
            foreach (var action in actions)
                result = result | action(intero);

            Console.WriteLine("Risultato");
            Console.WriteLine(result);
            Console.ReadLine();
        }
Esempio n. 8
0
        public void Resolve_Nosynonyms_ArgumentNotFound_ReturnsNull()
        {
            var flags = new Flags();

            var result = flags.Resolve("argument");

            Assert.IsNull(result);
        }
Esempio n. 9
0
        public void Resolve_Twosynonyms_ResolveSecondsynonym_ReturnsArgument()
        {
            var flags = new Flags();
            flags.Add("argument", "-a", "--a");

            var result = flags.Resolve("--a");

            Assert.That(result, Is.EqualTo("argument"));
        }
Esempio n. 10
0
        public void Resolve_Nosynonyms_ArgumentFound_ReturnsArgument()
        {
            var flags = new Flags();
            flags.Add("argument");

            var result = flags.Resolve("argument");

            Assert.That(result, Is.EqualTo("argument"));
        }
Esempio n. 11
0
 public Line(float x, float y, float x2, float y2, float a, float a2, Flags flags, int priority)
     : base(flags, priority << 16)
 {
     X = x;
     Y = y;
     X2 = x2;
     Y2 = y2;
     _a = a;
     _a2 = a2;
 }
Esempio n. 12
0
		internal VisualStudioHelper()
		{
			ScratchFiles = new List<ScratchFile>();
			Projects = new List<ProjectFacade>();
			Solution = null;
			Log = new List<LogEntry>();
			HasConfig = false;
			Flags = new Flags();
			
	}
Esempio n. 13
0
 public static void InitializeResolver(Flags f)
 {
     UrlResolver.HrefResolver =
         new Lazy<IPathResolver>(
             () =>
             new ContentResolver
             {
                 ContentDir = f.WebAppRoot
             });
 }
 public void SetFlag(Flags mask, bool value)
 {
     if (value)
     {
         this.flags |= mask;
     }
     else
     {
         this.flags &= ~mask;
     }
 }
Esempio n. 15
0
 public Form3()
 {
     InitializeComponent();
     f = uXml.read();
     this.checkBox1.Checked = f.finish;
     this.checkBox2.Checked = f.date;
     this.checkBox3.Checked = f.unLimited;
     this.checkBox4.Checked = f.memo1;
     this.checkBox5.Checked = f.memo2;
     this.checkBox6.Checked = f.memo3;
     this.checkBox7.Checked = f.emergency;
     this.checkBox8.Checked = f.check;
 }
Esempio n. 16
0
 private static byte[] Read_CWav(Stream stream, Flags flags)
 {
     if (flags.SoundEffect)
     {
         using (var br = new BinaryReader(stream, Encoding.ASCII, true))
         {
             stream.Position = 0xBC;
             var len = br.ReadUInt32();
             var offset = br.ReadUInt32();
             stream.Position = offset;
             return br.ReadBytes((int) len);
         }
     }
     return new byte[0];
 }
Esempio n. 17
0
        public static void Test()
        {
            int result;
            //3
            result = new Flags().solution(new int[] { 1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2 });

            //2
            result = new Flags().solution(new int[] { 0, 1, 0, 1, 0, 1, 0 });

            //2
            result = new Flags().solution(new int[] { 0, 1, 0, 0, 1, 0, 1, 0 });

            //3
            result = new Flags().solution(new int[] { 0, 1, 0, 0, 1, 0, 1, 0, 1, 0 });
        }
Esempio n. 18
0
        public static int Main(string[] args)
        {
            var flags = new Flags(args);

            if (flags.HelpRequested)
            {
                flags.ShowUsage(Console.Out);
                return 0;
            }

            ConfigureLogging(flags.Verbose);

            using (var program = new Program(flags.WorkingDirectory, flags.ErrorWriter))
            {
                return program.Run() == 0 ? 0 : -1;
            }
        }
Esempio n. 19
0
        public void MessageReceived(LCM.LCM.LCM lcm, string channel, LCM.LCM.LCMDataInputStream dins)
        {
            Console.WriteLine("RECV: " + channel);

            if (channel == "MaestroDriver/Flags")
            {
                Flags msg = new Flags(dins);
                Console.WriteLine("length1=" + msg.goals.Length);
                Console.WriteLine("length2=" + msg.goals.LongLength);
                for(int goal = 0; goal< 4; goal++)
                {
                    for(int box = 0; box < 5; box++)
                    {
                        Console.WriteLine ("element goal=" + goal + ",\t box=" + box + ", value=" + msg.goals[goal,box]);
                        this.field.Goals[goal].setFlagPosition(box, msg.goals[goal, box]);
                    }
                }
            }
        }
Esempio n. 20
0
 public MapEmitter(Type sourceType, Type targetType, MemberTypes sourceMemberTypes, MemberTypes targetMemberTypes,
                    Flags bindingFlags, params string[] names)
     : base(new MapCallInfo(targetType, null,
         // Auto-apply IgnoreCase if we're mapping from one membertype to another
         Flags.SetIf(bindingFlags, Flags.IgnoreCase, (sourceMemberTypes & targetMemberTypes) != sourceMemberTypes),
         MemberTypes.Custom,
         "Mammatus.Library.Reflection_Map",
         Type.EmptyTypes,
         null,
         false,
         sourceType,
         sourceMemberTypes,
         targetMemberTypes,
         names))
 {
     this.sourceType = sourceType;
     this.sourceMemberTypes = sourceMemberTypes;
     this.targetMemberTypes = targetMemberTypes;
     this.names = names;
 }
Esempio n. 21
0
        /// <summary>
        /// Gets the member identified by <paramref name="name"/> on the given <paramref name="type"/>. Use
        /// the <paramref name="bindingFlags"/> parameter to define the scope of the search.
        /// </summary>
        /// <returns>A single MemberInfo instance of the first found match or null if no match was found.</returns>
        public static MemberInfo Member(this Type type, string name, Flags bindingFlags)
        {
            // we need to check all members to do partial name matches
            if (bindingFlags.IsAnySet(Flags.PartialNameMatch | Flags.TrimExplicitlyImplemented))
            {
                return type.Members(MemberTypes.All, bindingFlags, name).FirstOrDefault();
            }

            IList<MemberInfo> result = type.GetMember(name, bindingFlags);
            bool hasSpecialFlags = bindingFlags.IsAnySet(Flags.ExcludeBackingMembers | Flags.ExcludeExplicitlyImplemented | Flags.ExcludeHiddenMembers);
            result = hasSpecialFlags && result.Count > 0 ? result.Filter(bindingFlags) : result;
            bool found = result.Count > 0;

            if (!found && bindingFlags.IsNotSet(Flags.DeclaredOnly))
            {
                if (type.BaseType != typeof(object) && type.BaseType != null)
                {
                    return type.BaseType.Member(name, bindingFlags);
                }
            }
            return found ? result[0] : null;
        }
Esempio n. 22
0
        /// <summary>
        /// 選択データのタイトル及び内容を出力する。
        /// タイトルのみは AllDataTitle を利用する。
        /// </summary>
        /// <param name="data">項目データ</param>
        public void AllDatas( Datas data )
        {
            SaveFileDialog sfd = new SaveFileDialog();

            flags = uXml.read();

            sfd.FileName = "全データ一覧.txt";
            if (sfd.ShowDialog() == DialogResult.OK)
            {

                StreamWriter ofs = new StreamWriter(sfd.FileName);
                for (int i = 0; i < data.data.Count; i++)
                {
                    //フィルターに引っかかる物は表示しない
                    if (uXml.check(data.data[i].now_status, flags) != true)
                    {
                        continue;
                    }

                    //ofs.WriteLine("{0}\t:{1}", data.data[i].getStatus().ToString(), data.data[i].name.ToString());
                    ofs.Write("【{0}】【{1}】", data.data[i].getStatusTextForDisp().ToString(), data.data[i].name.ToString());
                    ofs.Write(Environment.NewLine);
                    ofs.Write("(作成日:{0})", data.data[i].createDate.ToString());
                    ofs.Write("(期限:{0})", data.data[i].limitDate.ToString());
                    ofs.Write("(終了日:{0})", data.data[i].exitDate.ToString());
                    ofs.Write(Environment.NewLine);
                    ofs.Write("【メモ】" + Environment.NewLine);

                    ofs.Write("\t{0}", data.data[i].memo.Replace(Environment.NewLine, Environment.NewLine + "\t").ToString());
                    ofs.Write(Environment.NewLine);
                    ofs.Write(Environment.NewLine);
                }
                ofs.Close();
                //MessageBox.Show(sfd.FileName.ToString() + "に保存しました。");
                SaveFile(sfd.FileName.ToString());

            }
        }
Esempio n. 23
0
 private void ClearFlag(Flags flags)
 {
     af.Low &= (byte)~flags;
 }
Esempio n. 24
0
        private PEPropertySymbol(
            PEModuleSymbol moduleSymbol,
            PENamedTypeSymbol containingType,
            PropertyDefinitionHandle handle,
            PEMethodSymbol getMethod,
            PEMethodSymbol setMethod,
            int countOfCustomModifiers,
            ParamInfo <TypeSymbol>[] propertyParams,
            MetadataDecoder metadataDecoder)
        {
            _containingType = containingType;
            var module = moduleSymbol.Module;
            PropertyAttributes      mdFlags = 0;
            BadImageFormatException mrEx    = null;

            try
            {
                module.GetPropertyDefPropsOrThrow(handle, out _name, out mdFlags);
            }
            catch (BadImageFormatException e)
            {
                mrEx = e;

                if ((object)_name == null)
                {
                    _name = string.Empty;
                }
            }

            _getMethod = getMethod;
            _setMethod = setMethod;
            _handle    = handle;

            SignatureHeader         unusedCallingConvention;
            BadImageFormatException getEx = null;
            var getMethodParams           = (object)getMethod == null ? null : metadataDecoder.GetSignatureForMethod(getMethod.Handle, out unusedCallingConvention, out getEx);
            BadImageFormatException setEx = null;
            var setMethodParams           = (object)setMethod == null ? null : metadataDecoder.GetSignatureForMethod(setMethod.Handle, out unusedCallingConvention, out setEx);

            // NOTE: property parameter names are not recorded in metadata, so we have to
            // use the parameter names from one of the indexers
            // NB: prefer setter names to getter names if both are present.
            bool isBad;

            _parameters = GetParameters(moduleSymbol, this, propertyParams, setMethodParams ?? getMethodParams, out isBad);

            if (getEx != null || setEx != null || mrEx != null || isBad)
            {
                _lazyUseSiteDiagnostic = new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this);
            }

            var returnInfo = propertyParams[0];

            _refKind = returnInfo.IsByRef ? RefKind.Ref : RefKind.None;

            // CONSIDER: Can we make parameter type computation lazy?
            TypeSymbol originalPropertyType = returnInfo.Type;

            _propertyType = DynamicTypeDecoder.TransformType(originalPropertyType, countOfCustomModifiers, handle, moduleSymbol, _refKind);

            // Dynamify object type if necessary
            _propertyType = _propertyType.AsDynamicIfNoPia(_containingType);

            _propertyType = TupleTypeDecoder.DecodeTupleTypesIfApplicable(_propertyType, handle, moduleSymbol);

            // A property is bogus and must be accessed by calling its accessors directly if the
            // accessor signatures do not agree, both with each other and with the property,
            // or if it has parameters and is not an indexer or indexed property.
            bool callMethodsDirectly = !DoSignaturesMatch(module, metadataDecoder, propertyParams, _getMethod, getMethodParams, _setMethod, setMethodParams) ||
                                       MustCallMethodsDirectlyCore();

            if (!callMethodsDirectly)
            {
                if ((object)_getMethod != null)
                {
                    _getMethod.SetAssociatedProperty(this, MethodKind.PropertyGet);
                }

                if ((object)_setMethod != null)
                {
                    _setMethod.SetAssociatedProperty(this, MethodKind.PropertySet);
                }
            }

            if (callMethodsDirectly)
            {
                _flags |= Flags.CallMethodsDirectly;
            }

            if ((mdFlags & PropertyAttributes.SpecialName) != 0)
            {
                _flags |= Flags.IsSpecialName;
            }

            if ((mdFlags & PropertyAttributes.RTSpecialName) != 0)
            {
                _flags |= Flags.IsRuntimeSpecialName;
            }
        }
Esempio n. 25
0
        public bool PublicKeySerialize(ReadOnlySpan <byte> publicKey, Span <byte> serializedPublicKeyOutput, Flags flags = Flags.SECP256K1_EC_UNCOMPRESSED)
        {
            bool compressed             = flags.HasFlag(Flags.SECP256K1_EC_COMPRESSED);
            int  serializedPubKeyLength = compressed ? SERIALIZED_COMPRESSED_PUBKEY_LENGTH : SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH;

            if (serializedPublicKeyOutput.Length != serializedPubKeyLength)
            {
                string compressedStr = compressed ? "compressed" : "uncompressed";
                throw new ArgumentException($"{nameof(serializedPublicKeyOutput)} ({compressedStr}) must be {serializedPubKeyLength} bytes");
            }
            if (publicKey.Length != PUBKEY_LENGTH)
            {
                throw new ArgumentException($"{nameof(publicKey)} must be {PUBKEY_LENGTH} bytes");
            }

            UIntPtr newLength = (UIntPtr)serializedPubKeyLength;

            fixed(byte *serializedPtr = serializedPublicKeyOutput)
            fixed(byte *pubKeyPtr = publicKey)
            {
                var result = secp256k1_ec_pubkey_serialize.Value(_ctx, serializedPtr, ref newLength, pubKeyPtr, (uint)flags);

                return(result == 1 && (uint)newLength == serializedPubKeyLength);
            }
        }
Esempio n. 26
0
        public void DumpXml(XmlWriter writer)
        {
            if (AbcDumpService.FilterClass(this))
            {
                return;
            }
            IsDumped = true;

            writer.WriteStartElement("instance");
            writer.WriteAttributeString("index", Index.ToString());

            if (Name != null)
            {
                writer.WriteAttributeString("name", Name.FullName);
            }

            //if (_superName != null)
            //    writer.WriteAttributeString("supername", _superName.FullName);
            //if (_name != null)
            //    writer.WriteElementString("name", _name.ToString());

            if (BaseTypeName != null)
            {
                writer.WriteElementString("super", BaseTypeName.ToString());
            }

            writer.WriteElementString("flags", Flags.ToString());

            if ((Flags & AbcClassFlags.ProtectedNamespace) != 0 && ProtectedNamespace != null)
            {
                writer.WriteStartElement("protectedNamespace");
                writer.WriteAttributeString("name", ProtectedNamespace.Name.Value);
                writer.WriteAttributeString("kind", ProtectedNamespace.Kind.ToString());
                writer.WriteEndElement();
            }

            if (_interfaces.Count > 0)
            {
                writer.WriteStartElement("interfaces");
                foreach (var i in _interfaces)
                {
                    writer.WriteStartElement("interface");
                    writer.WriteAttributeString("name", i.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
            }

            if (_initializer != null)
            {
                if (AbcDumpService.DumpInitializerCode)
                {
                    bool old = AbcDumpService.DumpCode;
                    AbcDumpService.DumpCode = true;
                    _initializer.DumpXml(writer, "iinit");
                    AbcDumpService.DumpCode = old;
                }
                else
                {
                    writer.WriteElementString("iinit", _initializer.ToString());
                }
            }

            _traits.DumpXml(writer);

            if (_class != null)
            {
                _class.DumpXml(writer);
            }

            writer.WriteEndElement();
        }
Esempio n. 27
0
        public void Read_ShortBuffer_ThrowArgumentException()
        {
            // Act/Assert

            Assert.Throws <ArgumentException>(() => Flags.Read(new byte[3]));
        }
 public InteractionContext(Flags flags)
 {
     m_NativePtr = Internal_Create((int)flags);
 }
Esempio n. 29
0
        public void Export(TextWriter writer)
        {
            writer.WriteIndent(2);
            foreach (string attribute in Attributes)
            {
                writer.Write("[{0}] ", attribute);
            }
            if (Flags.IsHideInEnspector())
            {
                writer.Write("[HideInInspector] ");
            }
            if (Flags.IsPerRendererData())
            {
                writer.Write("[PerRendererData] ");
            }
            if (Flags.IsNoScaleOffset())
            {
                writer.Write("[NoScaleOffset] ");
            }
            if (Flags.IsNormal())
            {
                writer.Write("[Normal] ");
            }
            if (Flags.IsHDR())
            {
                writer.Write("[HDR] ");
            }
            if (Flags.IsGamma())
            {
                writer.Write("[Gamma] ");
            }

            writer.Write("{0} (\"{1}\", ", Name, Description);

            switch (Type)
            {
            case SerializedPropertyType.Color:
            case SerializedPropertyType.Vector:
                writer.Write(nameof(SerializedPropertyType.Vector));
                break;

            case SerializedPropertyType.Int:
                //case SerializedPropertyType.Float:
                writer.Write(nameof(SerializedPropertyType.Float));
                break;

            case SerializedPropertyType.Range:
                writer.Write("{0}({1}, {2})",
                             nameof(SerializedPropertyType.Range),
                             DefValue1.ToString(CultureInfo.InvariantCulture),
                             DefValue2.ToString(CultureInfo.InvariantCulture));
                break;

            case SerializedPropertyType._2D:
                //case SerializedPropertyType._3D:
                //case SerializedPropertyType.Cube:
                switch (DefTexture.TexDim)
                {
                case 1:
                    writer.Write("any");
                    break;

                case 2:
                    writer.Write("2D");
                    break;

                case 3:
                    writer.Write("3D");
                    break;

                case 4:
                    writer.Write(nameof(SerializedPropertyType.Cube));
                    break;

                case 5:
                    writer.Write("2DArray");
                    break;

                case 6:
                    writer.Write(nameof(SerializedPropertyType.CubeArray));
                    break;

                default:
                    throw new NotSupportedException("Texture dimension isn't supported");
                }
                break;

            default:
                throw new NotSupportedException($"Serialized property type {Type} isn't supported");
            }
            writer.Write(") = ");

            switch (Type)
            {
            case SerializedPropertyType.Color:
            case SerializedPropertyType.Vector:
                writer.Write("({0},{1},{2},{3})",
                             DefValue0.ToString(CultureInfo.InvariantCulture),
                             DefValue1.ToString(CultureInfo.InvariantCulture),
                             DefValue2.ToString(CultureInfo.InvariantCulture),
                             DefValue3.ToString(CultureInfo.InvariantCulture));
                break;

            case SerializedPropertyType.Int:
            //case SerializedPropertyType.Float:
            case SerializedPropertyType.Range:
                writer.Write(DefValue0.ToString(CultureInfo.InvariantCulture));
                break;

            case SerializedPropertyType._2D:
                //case SerializedPropertyType._3D:
                //case SerializedPropertyType.Cube:
                writer.Write("\"{0}\" {{}}", DefTexture.DefaultName);
                break;

            default:
                throw new NotSupportedException($"Serialized property type {Type} isn't supported");
            }
            writer.Write('\n');
        }
Esempio n. 30
0
 /// <summary>
 /// Creates a delegate which can set the value of the field specified by <paramref name="name"/> and
 /// matching <paramref name="bindingFlags"/> on the given <paramref name="type"/>.
 /// </summary>
 public static MemberSetter DelegateForSetFieldValue( this Type type, string name, Flags bindingFlags )
 {
     var callInfo = new CallInfo(type, null, bindingFlags, MemberTypes.Field, name, null, null, false);
     return (MemberSetter) new MemberSetEmitter( callInfo ).GetDelegate();
 }
Esempio n. 31
0
 /// <summary>
 /// Sets the first field with the given <paramref name="name"/> on the given <paramref name="obj"/> object
 /// to the supplied <paramref name="value"/>. Returns true if a value was assigned to a field and false otherwise.
 /// Use the <paramref name="bindingFlags"/> parameter to limit the scope of the search.
 /// </summary>
 /// <param name="obj">The source object on which to find the field</param>
 /// <param name="name">The name of the field whose value should be retrieved</param>
 /// <param name="value">The value that should be assigned to the field</param>
 /// <param name="bindingFlags">A combination of Flags that define the scope of the search</param>
 /// <returns>True if the value was assigned to a field and false otherwise</returns>
 public static bool TrySetFieldValue( this object obj, string name, object value, Flags bindingFlags )
 {
     try
     {
         obj.SetFieldValue(name, value, bindingFlags );
         return true;
     }
     catch( MissingFieldException )
     {
         return false;
     }
 }
Esempio n. 32
0
        public void NewGame(string fen, GameMode gameMode, GameType gameType, OptionsBlitzClock blitzClock, OptionsLongClock longClock)
        {
            Stop();

            InitialBoardFen = fen;
            GameMode        = gameMode;
            GameType        = gameType;

            if (BeforeNewGame != null)
            {
                BeforeNewGame(this, EventArgs.Empty);
            }

            #region Init
            GameValidator = new GameW(this.InitialBoardFen);

            SpaceBarCounter = 0;

            CloseEngines();

            if (GameType == GameType.LongGame)
            {
                GameTime.Init(longClock, true);
            }
            else
            {
                GameTime.Init(blitzClock, true);
            }

            GameResult  = GameResultE.InProgress;
            CurrentMove = null;

            Flags.Reset();
            #endregion

            #region Switch gameMode
            switch (GameMode)
            {
            case GameMode.None:
                break;

            case GameMode.HumanVsHuman:
                Player1.PlayerType = PlayerType.Human;
                Player2.PlayerType = PlayerType.Human;

                Player1.Engine = null;
                Player2.Engine = null;

                Player1.PlayerTitle = GameData.WhiteTitle;
                Player2.PlayerTitle = GameData.BlackTitle;
                break;

            case GameMode.HumanVsEngine:
                Player1.PlayerType    = PlayerType.Human;
                Player2.PlayerType    = PlayerType.Engine;
                Player2EngineFileName = InfinitySettings.Settings.DefaultEngineXml.FilePath;
                Player1.Engine        = null;
                if (DefaultEngine == null)
                {
                    Player2.Engine = UCIEngine.Load(Player2EngineFileName, Options.DefaultHashTableSize);
                    Player2.Engine.UseTablebases = EngineParameters.UseTablebases;

                    DefaultEngine = Player2.Engine;
                }
                else
                {
                    Player2.Engine = DefaultEngine;
                }

                Player2.Book = Book;
                DefaultBook  = Player2.Book;

                Player1.PlayerTitle = Ap.UserProfile.LastName;
                Player2.PlayerTitle = Player2.Engine.EngineName;

                break;

            case GameMode.EngineVsEngine:
                Player1.PlayerType = PlayerType.Engine;
                Player2.PlayerType = PlayerType.Engine;

                Player1.Engine = UCIEngine.Load(Player1EngineFileName, Player1EngineHashTableSize);
                Player1.Engine.UseTablebases = EngineParameters.UseTablebases;

                Player2.Engine = UCIEngine.Load(Player2EngineFileName, Player2EngineHashTableSize);
                Player2.Engine.UseTablebases = EngineParameters.UseTablebases;

                Player1.PlayerTitle = Player1.Engine.EngineName;
                Player2.PlayerTitle = Player2.Engine.EngineName;

                break;

            case GameMode.OnlineHumanVsHuman:
                #region OnlineHumanVsHuman
                StartOnlineH2HGame();
                #endregion
                break;

            case GameMode.OnlineHumanVsEngine:
                break;

            case GameMode.OnlineEngineVsEngine:

                if (PlayingMode.SelectedEngine == null)
                {
                    StartOnlineH2HGame();
                }
                else
                {
                    StartOnlineE2EGame();
                }

                break;

            case GameMode.Kibitzer:
                #region Kibitzer
                GameTime.Set(DbGame);
                GameResult = DbGame.GameResultIDE;     //GameResultE.InProgress;

                Player1.PlayerType  = PlayerType.Human;
                Player1.PlayerTitle = DbGame.WhiteUser.UserName;
                Player2.PlayerType  = PlayerType.Human;
                Player2.PlayerTitle = DbGame.BlackUser.UserName;

                if (DbGame.IsRated)
                {
                    gameTypeTitle = GameType.ToString() + " " + DbGame.TimeMin.ToString() + "m + " + DbGame.GainPerMoveMin.ToString() + "s, " + "Rated";

                    if (DbGame.EloBlackBefore != 0 && !DbGame.BlackUser.IsGuest)
                    {
                        Player2.PlayerTitle += " " + DbGame.EloBlackBefore.ToString();
                    }

                    if (DbGame.EloWhiteBefore != 0 && !DbGame.WhiteUser.IsGuest)
                    {
                        Player1.PlayerTitle += " " + DbGame.EloWhiteBefore.ToString();
                    }
                }
                else
                {
                    gameTypeTitle = GameType.ToString() + " " + DbGame.TimeMin.ToString() + "m + " + DbGame.GainPerMoveMin.ToString() + "s, " + "Unrated";
                }
                #endregion
                break;

            default:
                break;
            }
            #endregion

            if (DefaultEngine != null)
            {
                if (DefaultEngine.IsClosed)
                {
                    DefaultEngine.Load();
                }
            }

            Flags.IsEngineBlack = true;

            #region Start

            gameTypeTitle = Ap.GetGameTypeTitle(GameType);

            Player1.Active = true;
            Player2.Active = false;

            Notations.SetupNewGame();
            CapturedPieces.SetupNewGame();
            Clock.SetupNewGame();
            Book.SetupNewGame();

            Clipboard.Reset();

            CurrentPlayer = Player1;

            GameData.SetupNewGame();


            if (Flags.IsChangeNamesAllowed)
            {
                GameData.White1 = Player1.PlayerTitle;
                GameData.White2 = Ap.UserProfile.FirstName;
                GameData.Black1 = Player2.PlayerTitle;
            }
            GameData.Tournament = GameTypeTitle;

            InitTablebases();

            Ap.Options.GameType = gameType;
            Ap.Options.Save();


            #endregion

            if (CreateDocking != null)
            {
                CreateDocking(this, EventArgs.Empty);
            }

            Flags.IsInfiniteAnalysisOn = false;
            SetFen(fen);

            if (Flags.IsOnline)
            {
                // Flags.IsChallengerSendsGame = Flags.IsPositionSetupAllowed;
            }

            if (AfterNewGame != null)
            {
                AfterNewGame(this, EventArgs.Empty);
            }
        }
Esempio n. 33
0
 public ItemBlockBlock()
 {
     this._flags = new Flags(4);
 }
Esempio n. 34
0
 public override Flags HasPointerToEnumInParam(Flags pointerToEnum)
 {
     return(base.HasPointerToEnumInParam(pointerToEnum));
 }
Esempio n. 35
0
 private bool IsFlagSet(Flags flags)
 {
     return(((Flags)af.Low & flags) == flags);
 }
 public override void ToStream(Stream output)
 {
     output.Write(TLUtils.SignatureToBytes(Signature));
     Flags.ToStream(output);
     UntilDate.ToStream(output);
 }
        internal static PaletteData GetPalette(ref byte background, ref byte orientation, byte squareX, byte squareY)
        {
            if (background > 0x3f)
            {
                throw new ArgumentOutOfRangeException();
            }
            if ((orientation & 0x3f) != 0)
            {
                throw new ArgumentOutOfRangeException();
            }

            // ReSharper disable InlineOutVariableDeclaration
            byte accumulator;
            // ReSharper restore InlineOutVariableDeclaration
            Flags flags = new Flags();

            Load(out accumulator, BackgroundPaletteLookup[background], ref flags);
            var backgroundPalette = accumulator;

            if (!flags.Zero)
            {
                goto palette_not_zero;
            }

// palette 0
            Load(out accumulator, squareY, ref flags);
            flags.Carry = true;
            SubtractWithBorrow(ref accumulator, 0x54, ref flags);
            LogicalShiftRight(ref accumulator, ref flags);
            LogicalShiftRight(ref accumulator, ref flags);
            LogicalShiftRight(ref accumulator, ref flags);
            LogicalShiftRight(ref accumulator, ref flags);
            byte index = accumulator;

            Load(out accumulator, WallPaletteZeroLookup[index], ref flags);

palette_not_zero:
            Compare(accumulator, 0x03, ref flags);
            if (flags.Carry)
            {
                goto palette_not_one_or_two;
            }

// palette 1 or 2
            AddWithCarry(ref accumulator, 0xb1, ref flags);
            BitTest(accumulator, squareY, ref flags);
            if (!flags.Negative)
            {
                goto palette_not_six;
            }
            ArithmeticShiftLeft(ref accumulator, ref flags);
            AddWithCarry(ref accumulator, 0x90, ref flags);

palette_not_one_or_two:
            Compare(accumulator, 0x03, ref flags);
            if (!flags.Zero)
            {
                goto palette_not_three;
            }

// palette 3
            Load(out accumulator, orientation, ref flags);
            RotateLeft(ref accumulator, ref flags);
            RotateLeft(ref accumulator, ref flags);
            RotateLeft(ref accumulator, ref flags);
            SubtractWithBorrow(ref accumulator, squareY, ref flags);
            RotateRight(ref accumulator, ref flags);
            flags.Carry = false;
            AddWithCarry(ref accumulator, squareX, ref flags);
            And(ref accumulator, 0x03, ref flags);
            index       = accumulator;
            accumulator = WallPaletteThreeLookup[index];

palette_not_three:
            Compare(accumulator, 0x04, ref flags);
            if (!flags.Zero)
            {
                goto palette_not_four;
            }

// palette 4
            Load(out accumulator, squareY, ref flags);
            RotateLeft(ref accumulator, ref flags);
            RotateLeft(ref accumulator, ref flags);
            RotateLeft(ref accumulator, ref flags);
            RotateLeft(ref accumulator, ref flags);
            And(ref accumulator, 0x7, ref flags);
            index       = accumulator;
            accumulator = WallPaletteFourLookup[index];

palette_not_four:
            Compare(accumulator, 0x05, ref flags);
            if (!flags.Zero)
            {
                goto palette_not_five;
            }

// palette 5
            Load(out accumulator, squareY, ref flags);
            RotateRight(ref accumulator, ref flags);
            RotateRight(ref accumulator, ref flags);
            Eor(ref accumulator, squareY, ref flags);
            RotateRight(ref accumulator, ref flags);
            if (flags.Carry)
            {
                background = 0x19;
            }
            RotateRight(ref accumulator, ref flags);
            SubtractWithBorrow(ref accumulator, squareY, ref flags);
            And(ref accumulator, 0x40, ref flags);
            Eor(ref accumulator, orientation, ref flags);
            BitTest(accumulator, orientation, ref flags);
            orientation = accumulator;
            Load(out accumulator, 0xB1, ref flags);
            if (!flags.Overflow)
            {
                goto palette_not_six;
            }
            AddWithCarry(ref accumulator, 0x0a, ref flags);

palette_not_five:
            Compare(accumulator, 0x06, ref flags);
            if (!flags.Zero)
            {
                goto palette_not_six;
            }

// palette 6
            Load(out accumulator, 0x9c, ref flags);
            BitTest(accumulator, orientation, ref flags);
            if (!flags.Overflow)
            {
                goto palette_not_six;
            }
            Load(out accumulator, 0xcf, ref flags);

palette_not_six:
            var displayedPalette = accumulator;
            var result = new PaletteData {
                BackgroundPalette = backgroundPalette, Palette = SquarePalette.FromByte(displayedPalette)
            };

            return(result);
        }
	public bool CheckFlag(Flags mask) { return (flags & mask) != Flags.None; }
Esempio n. 39
0
        private IEnumerable <FileInfo> InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
        {
            if (destinationPath.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("destinationPath");
            }

            if (!Directory.Exists(sourcePath))
            {
                throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
            }

            IList <FileInfo> uploadedFiles = new List <FileInfo>();

            DirectoryInfo sourceDirectory = new DirectoryInfo(sourcePath);

#if SILVERLIGHT
            var sourceFiles = sourceDirectory.EnumerateFiles(searchPattern);
#else
            var sourceFiles = sourceDirectory.GetFiles(searchPattern);
#endif

            if (sourceFiles == null || !sourceFiles.Any())
            {
                return(uploadedFiles);
            }

            #region Existing Files at The Destination

            var destFiles = InternalListDirectory(destinationPath, null);
            Dictionary <string, SftpFile> destDict = new Dictionary <string, SftpFile>();
            foreach (var destFile in destFiles)
            {
                if (destFile.IsDirectory)
                {
                    continue;
                }
                destDict.Add(destFile.Name, destFile);
            }

            #endregion

            #region Upload the difference

            const Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
            foreach (var localFile in sourceFiles)
            {
                bool isDifferent = !destDict.ContainsKey(localFile.Name);

                if (!isDifferent)
                {
                    SftpFile temp = destDict[localFile.Name];
                    //  TODO:   Use md5 to detect a difference
                    //ltang: File exists at the destination => Using filesize to detect the difference
                    isDifferent = localFile.Length != temp.Length;
                }

                if (isDifferent)
                {
                    var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
                    try
                    {
                        using (var file = File.OpenRead(localFile.FullName))
                        {
                            this.InternalUploadFile(file, remoteFileName, uploadFlag, null, null);
                        }

                        uploadedFiles.Add(localFile);

                        if (asynchResult != null)
                        {
                            asynchResult.Update(uploadedFiles.Count);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
                    }
                }
            }

            #endregion

            return(uploadedFiles);
        }
Esempio n. 40
0
 public FormalParam(Text.Span span, string /*!*/ name, Text.Span nameSpan, TypeRef typeHint, Flags flags,
                    Expression initValue, List <CustomAttribute> attributes)
     : base(span)
 {
     _name      = new VariableNameRef(nameSpan, name);
     _typeHint  = typeHint;
     _flags     = flags;
     _initValue = initValue;
     if (attributes != null && attributes.Count != 0)
     {
         this.Attributes = new CustomAttributes(attributes);
     }
 }
Esempio n. 41
0
        /// <summary>
        /// Converts a given public key (compressed/uncompressed or ethereum format (uncompressed without prefix)) to the specified format.
        /// </summary>
        /// <param name="publicKey">The public key to convert the format of.</param>
        /// <param name="compressed">If true, outputs a compressed public key.</param>
        /// <param name="slicedPrefix">If true, slices off the prefix byte from the public key.</param>
        /// <returns>Returns the provided public key, converted to the format specified.</returns>
        private static byte[] ConvertPublicKeyFormat(Memory <byte> publicKey, bool compressed = false, bool slicedPrefix = true)
        {
            // Define the public key array
            Span <byte> parsedPublicKey = new byte[PUBLIC_KEY_SIZE];

            // Add our uncompressed prefix to our key.
            byte[] prefixedPublicKey = null;
            if (publicKey.Length == Secp256k1.PUBKEY_LENGTH)
            {
                // We add our uncompressed prefix.
                prefixedPublicKey = new byte[] { 0x04 }.Concat(publicKey.ToArray());
            }
            else if (publicKey.Length == Secp256k1.SERIALIZED_COMPRESSED_PUBKEY_LENGTH ||
                     publicKey.Length == Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH)
            {
                // The provided key is already prefixed, so we set it as is.
                prefixedPublicKey = publicKey.ToArray();
            }
            else
            {
                throw new ArgumentException($"Unmanaged EC library failed to normalize public key because key length was invalid ({publicKey.Length}).");
            }

            // Declare our serialized public key
            using (AutoObjectPool <Secp256k1> .Get(out var secp256k1))
            {
                // Parse our public key from the serialized data.
                if (!secp256k1.PublicKeyParse(parsedPublicKey, prefixedPublicKey))
                {
                    var errMsg = "Unmanaged EC library failed to deserialize public key. ";
                    if (IncludeKeyDataInExceptions)
                    {
                        errMsg += $"PrefixedPublicKey: {prefixedPublicKey.ToHexString()}";
                    }

                    throw new Exception(errMsg);
                }

                // Serialize the public key
                int         serializedKeyLength = compressed ? Secp256k1.SERIALIZED_COMPRESSED_PUBKEY_LENGTH : Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH;
                Flags       serializedKeyFlags  = compressed ? Flags.SECP256K1_EC_COMPRESSED : Flags.SECP256K1_EC_UNCOMPRESSED;
                Span <byte> serializedKey       = new byte[serializedKeyLength];
                if (!secp256k1.PublicKeySerialize(serializedKey, parsedPublicKey, serializedKeyFlags))
                {
                    var errMsg = "Unmanaged EC library failed to serialize public key. ";
                    if (IncludeKeyDataInExceptions)
                    {
                        errMsg += $"PublicKey: {parsedPublicKey.ToHexString()}";
                    }

                    throw new Exception(errMsg);
                }

                // Slice off any prefix.
                if (slicedPrefix)
                {
                    serializedKey = serializedKey.Slice(1);
                }

                // Return it
                return(serializedKey.ToArray());
            }
        }
Esempio n. 42
0
        /// <summary>
        /// Obtains the binary data representation of our public key.
        /// </summary>
        /// <returns>Returns a binary data representation of the public key.</returns>
        public override byte[] ToPublicKeyArray(bool compressed = false, bool slicedPrefix = true)
        {
            // Throw an error if trying to slice prefix off of compressed public key
            if (compressed && slicedPrefix)
            {
                throw new ArgumentException("Should not be slicing the prefix off of a compressed public key, as compressed keys solely include X and Y is derived using the prefix.");
            }

            // Define the public key array
            Span <byte> publicKey = new byte[PUBLIC_KEY_SIZE];

            // Declare our serialized public key
            using (AutoObjectPool <Secp256k1> .Get(out var secp256k1))
            {
                // If this is the public key, we can simply return this
                if (KeyType == EthereumEcdsaKeyType.Public)
                {
                    // Add our uncompressed prefix to our key.
                    byte[] uncompressedPrefixedPublicKey = new byte[] { 0x04 }.Concat(UnmanagedKey.ToArray());

                    // Parse our public key from the serialized data.
                    if (!secp256k1.PublicKeyParse(publicKey, uncompressedPrefixedPublicKey))
                    {
                        var errMsg = "Unmanaged EC library failed to deserialize public key. ";
                        if (IncludeKeyDataInExceptions)
                        {
                            errMsg += $"PublicKey: {UnmanagedKey.ToHexString()}";
                        }

                        throw new Exception(errMsg);
                    }
                }
                else
                {
                    // Obtain the public key from the private key.
                    if (!secp256k1.PublicKeyCreate(publicKey, UnmanagedKey.Span))
                    {
                        var errMsg = "Unmanaged EC library failed to obtain public key from private key. ";
                        if (IncludeKeyDataInExceptions)
                        {
                            errMsg += $"PrivateKey: {UnmanagedKey.ToHexString()}";
                        }

                        throw new Exception(errMsg);
                    }
                }

                // Serialize the public key
                int         serializedKeyLength = compressed ? Secp256k1.SERIALIZED_COMPRESSED_PUBKEY_LENGTH : Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH;
                Flags       serializedKeyFlags  = compressed ? Flags.SECP256K1_EC_COMPRESSED : Flags.SECP256K1_EC_UNCOMPRESSED;
                Span <byte> serializedKey       = new byte[serializedKeyLength];
                if (!secp256k1.PublicKeySerialize(serializedKey, publicKey, serializedKeyFlags))
                {
                    var errMsg = "Unmanaged EC library failed to serialize public key. ";
                    if (IncludeKeyDataInExceptions)
                    {
                        errMsg += $"PublicKey: {publicKey.ToHexString()}";
                    }

                    throw new Exception(errMsg);
                }

                // Slice off any prefix.
                if (slicedPrefix)
                {
                    serializedKey = serializedKey.Slice(1);
                }

                // Return it
                return(serializedKey.ToArray());
            }
        }
Esempio n. 43
0
        private Query ProcessAxis(Axis root, Flags flags, out Props props)
        {
            Query result = null;

            if (root.Prefix.Length > 0)
            {
                _needContext = true;
            }
            _firstInput = null;
            Query qyInput;

            {
                if (root.Input != null)
                {
                    Flags inputFlags = Flags.None;
                    if ((flags & Flags.PosFilter) == 0)
                    {
                        Axis input = root.Input as Axis;
                        if (input != null)
                        {
                            if (
                                root.TypeOfAxis == Axis.AxisType.Child &&
                                input.TypeOfAxis == Axis.AxisType.DescendantOrSelf && input.NodeType == XPathNodeType.All
                                )
                            {
                                Query qyGrandInput;
                                if (input.Input != null)
                                {
                                    qyGrandInput = ProcessNode(input.Input, Flags.SmartDesc, out props);
                                }
                                else
                                {
                                    qyGrandInput = new ContextQuery();
                                    props        = Props.None;
                                }
                                result = new DescendantQuery(qyGrandInput, root.Name, root.Prefix, root.NodeType, false, input.AbbrAxis);
                                if ((props & Props.NonFlat) != 0)
                                {
                                    result = new DocumentOrderQuery(result);
                                }
                                props |= Props.NonFlat;
                                return(result);
                            }
                        }
                        if (root.TypeOfAxis == Axis.AxisType.Descendant || root.TypeOfAxis == Axis.AxisType.DescendantOrSelf)
                        {
                            inputFlags |= Flags.SmartDesc;
                        }
                    }

                    qyInput = ProcessNode(root.Input, inputFlags, out props);
                }
                else
                {
                    qyInput = new ContextQuery();
                    props   = Props.None;
                }
            }

            switch (root.TypeOfAxis)
            {
            case Axis.AxisType.Ancestor:
                result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, false);
                props |= Props.NonFlat;
                break;

            case Axis.AxisType.AncestorOrSelf:
                result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, true);
                props |= Props.NonFlat;
                break;

            case Axis.AxisType.Child:
                if ((props & Props.NonFlat) != 0)
                {
                    result = new CacheChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                }
                else
                {
                    result = new ChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                }
                break;

            case Axis.AxisType.Parent:
                result = new ParentQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                break;

            case Axis.AxisType.Descendant:
                if ((flags & Flags.SmartDesc) != 0)
                {
                    result = new DescendantOverDescendantQuery(qyInput, false, root.Name, root.Prefix, root.NodeType, /*abbrAxis:*/ false);
                }
                else
                {
                    result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, false, /*abbrAxis:*/ false);
                    if ((props & Props.NonFlat) != 0)
                    {
                        result = new DocumentOrderQuery(result);
                    }
                }
                props |= Props.NonFlat;
                break;

            case Axis.AxisType.DescendantOrSelf:
                if ((flags & Flags.SmartDesc) != 0)
                {
                    result = new DescendantOverDescendantQuery(qyInput, true, root.Name, root.Prefix, root.NodeType, root.AbbrAxis);
                }
                else
                {
                    result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, true, root.AbbrAxis);
                    if ((props & Props.NonFlat) != 0)
                    {
                        result = new DocumentOrderQuery(result);
                    }
                }
                props |= Props.NonFlat;
                break;

            case Axis.AxisType.Preceding:
                result = new PrecedingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                props |= Props.NonFlat;
                break;

            case Axis.AxisType.Following:
                result = new FollowingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                props |= Props.NonFlat;
                break;

            case Axis.AxisType.FollowingSibling:
                result = new FollSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                if ((props & Props.NonFlat) != 0)
                {
                    result = new DocumentOrderQuery(result);
                }
                break;

            case Axis.AxisType.PrecedingSibling:
                result = new PreSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                break;

            case Axis.AxisType.Attribute:
                result = new AttributeQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                break;

            case Axis.AxisType.Self:
                result = new XPathSelfQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                break;

            case Axis.AxisType.Namespace:
                if ((root.NodeType == XPathNodeType.All || root.NodeType == XPathNodeType.Element || root.NodeType == XPathNodeType.Attribute) && root.Prefix.Length == 0)
                {
                    result = new NamespaceQuery(qyInput, root.Name, root.Prefix, root.NodeType);
                }
                else
                {
                    result = new EmptyQuery();
                }
                break;

            default:
                throw XPathException.Create(SR.Xp_NotSupported, _query);
            }

            return(result);
        }
Esempio n. 44
0
 public MemberGetEmitter(MemberInfo memberInfo, Flags bindingFlags)
     : this(memberInfo.DeclaringType, bindingFlags, memberInfo.MemberType, memberInfo.Name, memberInfo)
 {
 }
Esempio n. 45
0
        private Query ProcessFilter(Filter root, Flags flags, out Props props)
        {
            bool first = ((flags & Flags.Filter) == 0);

            Props propsCond;
            Query cond = ProcessNode(root.Condition, Flags.None, out propsCond);

            if (
                CanBeNumber(cond) ||
                (propsCond & (Props.HasPosition | Props.HasLast)) != 0
                )
            {
                propsCond |= Props.HasPosition;
                flags     |= Flags.PosFilter;
            }

            // We don't want DescendantOverDescendant pattern to be recognized here (in case descendent::foo[expr]/descendant::bar)
            // So we clean this flag here:
            flags &= ~Flags.SmartDesc;
            // ToDo: Instead it would be nice to wrap descendent::foo[expr] into special query that will flatten it -- i.e.
            //       remove all nodes that are descendant of other nodes. This is very easy because for sorted nodesets all children
            //       follow its parent. One step caching. This can be easily done by rightmost DescendantQuery itself.
            //       Interesting note! Can we guarantee that DescendantOverDescendant returns flat nodeset? This definitely true if it's input is flat.

            Query qyInput = ProcessNode(root.Input, flags | Flags.Filter, out props);

            if (root.Input.Type != AstNode.AstType.Filter)
            {
                // Props.PosFilter is for nested filters only.
                // We clean it here to avoid cleaning it in all other ast nodes.
                props &= ~Props.PosFilter;
            }
            if ((propsCond & Props.HasPosition) != 0)
            {
                // this condition is positional rightmost filter should be avare of this.
                props |= Props.PosFilter;
            }

            /*merging predicates*/
            {
                FilterQuery qyFilter = qyInput as FilterQuery;
                if (qyFilter != null && (propsCond & Props.HasPosition) == 0 && qyFilter.Condition.StaticType != XPathResultType.Any)
                {
                    Query prevCond = qyFilter.Condition;
                    if (prevCond.StaticType == XPathResultType.Number)
                    {
                        prevCond = new LogicalExpr(Operator.Op.EQ, new NodeFunctions(FT.FuncPosition, null), prevCond);
                    }
                    cond    = new BooleanExpr(Operator.Op.AND, prevCond, cond);
                    qyInput = qyFilter.qyInput;
                }
            }

            if ((props & Props.PosFilter) != 0 && qyInput is DocumentOrderQuery)
            {
                qyInput = ((DocumentOrderQuery)qyInput).input;
            }
            if (_firstInput == null)
            {
                _firstInput = qyInput as BaseAxisQuery;
            }

            bool merge   = (qyInput.Properties & QueryProps.Merge) != 0;
            bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0;

            if ((propsCond & Props.HasPosition) != 0)
            {
                if (reverse)
                {
                    qyInput = new ReversePositionQuery(qyInput);
                }
                else if ((propsCond & Props.HasLast) != 0)
                {
                    qyInput = new ForwardPositionQuery(qyInput);
                }
            }

            if (first && _firstInput != null)
            {
                if (merge && (props & Props.PosFilter) != 0)
                {
                    qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/ false);
                    Query parent = _firstInput.qyInput;
                    if (!(parent is ContextQuery))
                    { // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ?
                        _firstInput.qyInput = new ContextQuery();
                        _firstInput         = null;
                        return(new MergeFilterQuery(parent, qyInput));
                    }
                    _firstInput = null;
                    return(qyInput);
                }
                _firstInput = null;
            }
            return(new FilterQuery(qyInput, cond, /*noPosition:*/ (propsCond & Props.HasPosition) == 0));
        }
Esempio n. 46
0
 public MemberGetEmitter(Type targetType, Flags bindingFlags, MemberTypes memberType, string fieldOrPropertyName)
     : this(targetType, bindingFlags, memberType, fieldOrPropertyName, null)
 {
 }
Esempio n. 47
0
        internal static void Boot()
        {
            Logger.Log(LogLevel.Info, "core", "Booting Everest");
            Logger.Log(LogLevel.Info, "core", $"VersionCelesteString: {VersionCelesteString}");

            if (Type.GetType("Mono.Runtime") != null)
            {
                // Mono hates HTTPS.
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
                    return(true);
                };
            }

            // enable TLS 1.2 to fix connecting to everestapi.github.io
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

            PathGame = Path.GetDirectoryName(typeof(Celeste).Assembly.Location);

            // .NET hates it when strong-named dependencies get updated.
            AppDomain.CurrentDomain.AssemblyResolve += (asmSender, asmArgs) => {
                AssemblyName asmName = new AssemblyName(asmArgs.Name);
                if (!asmName.Name.StartsWith("Mono.Cecil") &&
                    !asmName.Name.StartsWith("YamlDotNet") &&
                    !asmName.Name.StartsWith("NLua"))
                {
                    return(null);
                }

                Assembly asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(other => other.GetName().Name == asmName.Name);
                if (asm != null)
                {
                    return(asm);
                }

                return(Assembly.LoadFrom(Path.Combine(PathGame, asmName.Name + ".dll")));
            };

            // Preload some basic dependencies.
            Assembly.Load("MonoMod.RuntimeDetour");
            Assembly.Load("MonoMod.Utils");
            Assembly.Load("Mono.Cecil");
            Assembly.Load("YamlDotNet");
            Assembly.Load("Newtonsoft.Json");
            Assembly.Load("Jdenticon");

            if (!File.Exists(Path.Combine(PathGame, "EverestXDGFlag")))
            {
                XDGPaths    = false;
                PathEverest = PathGame;
            }
            else
            {
                XDGPaths = true;
                var dataDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                Directory.CreateDirectory(PathEverest = Path.Combine(dataDir, "Everest"));
                Directory.CreateDirectory(Path.Combine(dataDir, "Everest", "Mods")); // Make sure it exists before content gets initialized
            }

            // Old versions of Everest have used a separate ModSettings folder.
            string modSettingsOld = Path.Combine(PathEverest, "ModSettings");
            string modSettingsRIP = Path.Combine(PathEverest, "ModSettings-OBSOLETE");

            if (Directory.Exists(modSettingsOld) || Directory.Exists(modSettingsRIP))
            {
                Logger.Log(LogLevel.Warn, "core", "THE ModSettings FOLDER IS OBSOLETE AND WILL NO LONGER BE USED!");
                if (Directory.Exists(modSettingsOld) && !Directory.Exists(modSettingsRIP))
                {
                    Directory.Move(modSettingsOld, modSettingsRIP);
                }
            }

            // Before even initializing anything else, make sure to prepare any static flags.
            Flags.Initialize();

            if (!Flags.IsDisabled && !Flags.IsDisabled)
            {
                // 0.1 parses into 1 in regions using ,
                // This also somehow sets the exception message language to English.
                CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
                CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
            }

            if (!Flags.IsHeadless)
            {
                // Initialize the content helper.
                Content.Initialize();

                // Initialize all main managers before loading any mods.
                TouchInputManager.Instance = new TouchInputManager(Celeste.Instance);
                // Don't add it yet, though - add it in Initialize.
            }

            MainThreadHelper.Instance = new MainThreadHelper(Celeste.Instance);

            // Register our core module and load any other modules.
            new CoreModule().Register();

            // Note: Everest fulfills some mod dependencies by itself.
            new NullModule(new EverestModuleMetadata()
            {
                Name          = "Celeste",
                VersionString = $"{Celeste.Instance.Version.ToString()}-{(typeof(Game).Assembly.FullName.Contains("FNA") ? "fna" : "xna")}"
            }).Register();
            new NullModule(new EverestModuleMetadata()
            {
                Name          = "DialogCutscene",
                VersionString = "1.0.0"
            }).Register();
            new NullModule(new EverestModuleMetadata()
            {
                Name          = "UpdateChecker",
                VersionString = "1.0.2"
            }).Register();

            LuaLoader.Initialize();

            Loader.LoadAuto();

            if (!Flags.IsHeadless && !Flags.IsDisabled)
            {
                // Load stray .bins afterwards.
                Content.Crawl(new MapBinsInModsModContent(Path.Combine(PathEverest, "Mods")));
            }

            // Also let all mods parse the arguments.
            Queue <string> args = new Queue <string>(Args);

            while (args.Count > 0)
            {
                string arg = args.Dequeue();
                foreach (EverestModule mod in _Modules)
                {
                    if (mod.ParseArg(arg, args))
                    {
                        break;
                    }
                }
            }

            // Start requesting the version list ASAP.
            Updater.RequestAll();

            if (CoreModule.Settings.AutoUpdateModsOnStartup)
            {
                // Request the mod update list as well.
                ModUpdaterHelper.RunAsyncCheckForModUpdates();
            }
        }
Esempio n. 48
0
 private MemberGetEmitter(Type targetType, Flags bindingFlags, MemberTypes memberType, string fieldOrPropertyName, MemberInfo memberInfo)
     : base(new CallInfo(targetType, null, bindingFlags, memberType, fieldOrPropertyName, Type.EmptyTypes, memberInfo, true))
 {
 }
Esempio n. 49
0
 public bool Is_Undefined(Flags flagName)
 {
     return(this.GetTv(flagName) == Tv.UNDEFINED);
 }
Esempio n. 50
0
 private void SetFlag(Flags flags)
 {
     af.Low |= (byte)flags;
 }
Esempio n. 51
0
 /// <summary>
 /// Gets the first field with the given <paramref name="name"/> on the given <paramref name="obj"/> object.
 /// Returns the value of the field if a match was found and null otherwise.
 /// Use the <paramref name="bindingFlags"/> parameter to limit the scope of the search.
 /// </summary>
 /// <remarks>
 /// When using this method it is not possible to distinguish between a missing field and a field whose value is null.
 /// </remarks>
 /// <param name="obj">The source object on which to find the field</param>
 /// <param name="name">The name of the field whose value should be retrieved</param>
 /// <param name="bindingFlags">A combination of Flags that define the scope of the search</param>
 /// <returns>The value of the field or null if no field was found</returns>
 public static object TryGetFieldValue( this object obj, string name, Flags bindingFlags )
 {
     try
     {
         return obj.GetFieldValue( name, bindingFlags );
     }
     catch( MissingFieldException )
     {
         return null;
     }
 }
Esempio n. 52
0
 protected override void HandleInvalidSegment(SegmentGeometry geometry)
 {
     Flags.resetSegmentVehicleRestrictions(geometry.SegmentId);
     ClearCache(geometry.SegmentId);
 }
Esempio n. 53
0
        private static IList<FieldInfo> GetFields( Type type, Flags bindingFlags )
        {
            bool recurse = bindingFlags.IsNotSet( Flags.DeclaredOnly );

            if( ! recurse )
            {
                return type.GetFields( bindingFlags ) ?? new FieldInfo[0];
            }

            bindingFlags |= Flags.DeclaredOnly;
            bindingFlags &= ~BindingFlags.FlattenHierarchy;

            var fields = new List<FieldInfo>();
            fields.AddRange( type.GetFields( bindingFlags ) );
            Type baseType = type.BaseType;
            while( baseType != null && baseType != typeof(object) )
            {
                fields.AddRange( baseType.GetFields( bindingFlags ) );
                baseType = baseType.BaseType;
            }
            return fields;
        }
Esempio n. 54
0
        public static void Eat(FoodStuff foodstuff)
        {
            if (foodstuff == null)
            {
                return;
            }

            FoodStuffProps Props = foodstuff.Props;

            if (!string.IsNullOrEmpty(Props.ConditionName))
            {
                if (UnityEngine.Random.value <= Props.ConditionChance)
                {
                    Player.Local.Status.AddCondition(Props.ConditionName);
                }
            }

            PlayerStatusRestore    hungerRestore = PlayerStatusRestore.A_None;
            PlayerStatusRestore    healthRestore = PlayerStatusRestore.A_None;
            PlayerStatusRestore    healthReduce  = PlayerStatusRestore.A_None;
            HallucinogenicStrength hallucinogen  = HallucinogenicStrength.None;
            bool wellFed = false;

            if (Flags.Check((uint)Props.Type, (uint)FoodStuffEdibleType.Edible, Flags.CheckType.MatchAny))
            {
                hungerRestore = Props.HungerRestore;
            }
            if (Flags.Check((uint)Props.Type, (uint)FoodStuffEdibleType.Hallucinogen, Flags.CheckType.MatchAny))
            {
                hallucinogen = Props.Hallucinogen;
            }
            if (Flags.Check((uint)Props.Type, (uint)FoodStuffEdibleType.Medicinal, Flags.CheckType.MatchAny))
            {
                healthRestore = Props.HealthRestore;
            }
            if (Flags.Check((uint)Props.Type, (uint)FoodStuffEdibleType.Poisonous, Flags.CheckType.MatchAny))
            {
                healthReduce = Props.HealthReduce;
            }
            if (Flags.Check((uint)Props.Type, (uint)FoodStuffEdibleType.WellFed, Flags.CheckType.MatchAny))
            {
                hungerRestore = PlayerStatusRestore.F_Full;
                wellFed       = true;
            }

            Player.Local.Status.ReduceStatus(healthReduce, "Health");
            if (foodstuff.Props.IsLiquid)
            {
                Player.Local.Status.RestoreStatus(hungerRestore, "Thirst");
            }
            else
            {
                Player.Local.Status.RestoreStatus(hungerRestore, "Hunger");
            }
            Player.Local.Status.RestoreStatus(healthRestore, "Health");

            if (wellFed)
            {
                Player.Local.Status.AddCondition("WellFed");
            }
            MasterAudio.PlaySound(MasterAudio.SoundType.PlayerVoice, Props.EatFoodSound);

            if (!string.IsNullOrEmpty(Props.CustomStatusKeeperRestore))
            {
                Player.Local.Status.RestoreStatus(Props.CustomRestore, Props.CustomStatusKeeperRestore);
            }
            if (!string.IsNullOrEmpty(Props.CustomStatusKeeperReduce))
            {
                Player.Local.Status.RestoreStatus(Props.CustomRestore, Props.CustomStatusKeeperReduce);
            }

            if (foodstuff.worlditem != null && !foodstuff.worlditem.IsTemplate)
            {
                foodstuff.OnEat.SafeInvoke();
                if (foodstuff.State.ConsumeOnEat)
                {
                    //Debug.Log ("FOODSTUFF: Setting mode to RemovedFromGame");
                    foodstuff.worlditem.SetMode(WIMode.RemovedFromGame);
                }
            }
        }
Esempio n. 55
0
        /// <summary>
        /// Gets the field identified by <paramref name="name"/> on the given <paramref name="type"/>. 
        /// Use the <paramref name="bindingFlags"/> parameter to define the scope of the search.
        /// </summary>
        /// <returns>A single FieldInfo instance of the first found match or null if no match was found.</returns>
        public static FieldInfo Field( this Type type, string name, Flags bindingFlags )
        {
            // we need to check all fields to do partial name matches
            if( bindingFlags.IsAnySet( Flags.PartialNameMatch | Flags.TrimExplicitlyImplemented ) )
            {
                return type.Fields( bindingFlags, name ).FirstOrDefault();
            }

            var result = type.GetField( name, bindingFlags );
            if( result == null && bindingFlags.IsNotSet( Flags.DeclaredOnly ) )
            {
                if( type.BaseType != typeof(object) && type.BaseType != null )
                {
                    return type.BaseType.Field( name, bindingFlags );
                }
            }
            bool hasSpecialFlags = bindingFlags.IsAnySet( Flags.ExcludeBackingMembers | Flags.ExcludeExplicitlyImplemented | Flags.ExcludeHiddenMembers );
            if( hasSpecialFlags )
            {
                IList<FieldInfo> fields = new List<FieldInfo> { result };
                fields = fields.Filter( bindingFlags );
                return fields.Count > 0 ? fields[ 0 ] : null;
            }
            return result;
        }
Esempio n. 56
0
        public static string DescribeProperties(FoodStuffProps props, string stateName)
        {                                       //TODO use a f'ing string builder
            string description = "When " + stateName + ", it's";

            if (Flags.Check((uint)props.Type, (uint)FoodStuffEdibleType.Edible, Flags.CheckType.MatchAny))
            {
                description += " edible,";
                if (Flags.Check((uint)props.Type, (uint)FoodStuffEdibleType.Poisonous, Flags.CheckType.MatchAny))
                {
                    description += " and can make for a";
                    switch (props.HungerRestore)
                    {
                    case PlayerStatusRestore.F_Full:
                    case PlayerStatusRestore.E_FourFifths:
                        description += " full meal,";
                        break;

                    case PlayerStatusRestore.D_ThreeFifths:
                    case PlayerStatusRestore.C_TwoFifths:
                        description += " large snack,";
                        break;

                    default:
                        description += " small snack,";
                        break;
                    }
                    description += " but it's also";
                    switch (props.HealthReduce)
                    {
                    case PlayerStatusRestore.F_Full:
                    case PlayerStatusRestore.E_FourFifths:
                        description += " seriously";
                        break;

                    case PlayerStatusRestore.D_ThreeFifths:
                    case PlayerStatusRestore.C_TwoFifths:
                        description += " moderately";
                        break;

                    default:
                        description += " mildly";
                        break;
                    }
                    description += " poisonous";
                }
                else
                {
                    description += " and it's good for a";
                    switch (props.HungerRestore)
                    {
                    case PlayerStatusRestore.F_Full:
                    case PlayerStatusRestore.E_FourFifths:
                        description += " full meal";
                        break;

                    case PlayerStatusRestore.D_ThreeFifths:
                    case PlayerStatusRestore.C_TwoFifths:
                        description += " large snack";
                        break;

                    default:
                        description += " small snack";
                        break;
                    }
                }

                if (Flags.Check((uint)props.Type, (uint)FoodStuffEdibleType.Medicinal, Flags.CheckType.MatchAny))
                {
                    description += " It also has";
                    switch (props.HealthRestore)
                    {
                    case PlayerStatusRestore.F_Full:
                    case PlayerStatusRestore.E_FourFifths:
                        description += " powerful.";
                        break;

                    case PlayerStatusRestore.D_ThreeFifths:
                    case PlayerStatusRestore.C_TwoFifths:
                        description += " moderate.";
                        break;

                    default:
                        description += " mild.";
                        break;
                    }
                    description += " medicinal properties";
                }

                if (Flags.Check((uint)props.Type, (uint)FoodStuffEdibleType.Hallucinogen, Flags.CheckType.MatchAny))
                {
                    description += ", but it's a ";
                    switch (props.Hallucinogen)
                    {
                    case HallucinogenicStrength.Strong:
                        description += " string";
                        break;

                    case HallucinogenicStrength.Moderate:
                        description += " moderate";
                        break;

                    default:
                        description += " mild";
                        break;
                    }
                    description += " hallucinogen so I'd better be careful.";
                }
                else
                {
                    description += ".";
                }
            }
            else
            {
                description += " inedible.";
            }
            return(description);
        }
	public void SetFlag(Flags mask, bool value) { 
		if (CheckFlag(mask) != value) {
			if (value) {
				flags |= mask; 
			}
			else {
				flags &= ~mask; 
			}
			Build();
		}
	}
Esempio n. 58
0
        public PyDataType InjectSkillIntoBrain(PyList itemIDs, CallInformation call)
        {
            foreach (PyInteger item in itemIDs.GetEnumerable <PyInteger>())
            {
                try
                {
                    // get the item by it's ID and change the location of it
                    Skill skill = this.ItemFactory.GetItem <Skill>(item);

                    // check if the character already has this skill injected
                    if (this.Character.InjectedSkillsByTypeID.ContainsKey(skill.Type.ID) == true)
                    {
                        throw new CharacterAlreadyKnowsSkill(skill.Type);
                    }

                    // is this a stack of skills?
                    if (skill.Quantity > 1)
                    {
                        // add one of the skill into the character's brain
                        Skill newStack = this.ItemFactory.CreateSkill(skill.Type, this.Character, 0, SkillHistoryReason.None);

                        // subtract one from the quantity
                        skill.Quantity -= 1;

                        // save to database
                        skill.Persist();

                        // finally notify the client
                        call.Client.NotifyMultiEvent(OnItemChange.BuildQuantityChange(skill, skill.Quantity + 1));
                        call.Client.NotifyMultiEvent(OnItemChange.BuildNewItemChange(newStack));
                    }
                    else
                    {
                        // store old values for the notification
                        int   oldLocationID = skill.LocationID;
                        Flags oldFlag       = skill.Flag;

                        // now set the new values
                        skill.LocationID = this.Character.ID;
                        skill.Flag       = Flags.Skill;
                        skill.Level      = 0;
                        skill.Singleton  = true;

                        // ensure the character has the skill in his/her brain
                        this.Character.AddItem(skill);

                        // ensure the changes are saved
                        skill.Persist();

                        // notify the character of the change in the item
                        call.Client.NotifyMultiEvent(OnItemChange.BuildLocationChange(skill, oldFlag, oldLocationID));
                        call.Client.NotifyMultiEvent(OnItemChange.BuildSingletonChange(skill, false));
                    }
                }
                catch (CharacterAlreadyKnowsSkill)
                {
                    throw;
                }
                catch (Exception)
                {
                    Log.Error($"Cannot inject itemID {item} into {this.Character.ID}'s brain...");
                    throw;
                }
            }

            // send the skill injected notification to refresh windows if needed
            call.Client.NotifyMultiEvent(new OnSkillInjected());

            return(null);
        }
	public void SetFlag(Flags mask, bool value) { if (value) flags |= mask;	else flags &= ~mask; }
Esempio n. 60
0
 public Result(List <Obj_AI_Base> _units, Flags _objects)
 {
     Units   = _units;
     Objects = _objects;
 }