public static Obj_AI_Hero GetTarget(this Spell spell,
     bool ignoreShields = true,
     Vector3 from = default(Vector3),
     IEnumerable<Obj_AI_Hero> ignoredChampions = null)
 {
     return TargetSelector.GetTarget(spell, ignoreShields, from, ignoredChampions);
 }
 /// <summary>
 /// Repeats the specified <see cref="Action"/> the number of times.
 /// </summary>
 /// <param name="input">The number of times to repeat the <see cref="Action"/>.</param>
 /// <param name="action">The <see cref="Action"/> to repeat.</param>
 public static void Times(this int input, Action action)
 {
     while (input-- > 0)
     {
         action();
     }
 }
		public static MouseButton ToOpenTKSingle(this MouseButtons buttons)
		{
			if ((buttons & MouseButtons.Left) != MouseButtons.None) return MouseButton.Left;
			else if ((buttons & MouseButtons.Right) != MouseButtons.None) return MouseButton.Right;
			else if ((buttons & MouseButtons.Middle) != MouseButtons.None) return MouseButton.Middle;
			else return MouseButton.LastButton;
		}
 public static void DeserializeObject(this Stream stream, object obj, List<string> nameTable)
 {
     while (stream.Position < stream.Length)
     {
         stream.ReadAndMapProperty(obj, nameTable);
     }
 }
        public static IServiceCollection AddFromAssembly(this IServiceCollection serviceCollection, Assembly assembly)
        {
            var builder = new ServiceDescriptorsBuilder().AddSourceAssembly(assembly);
            BuildAndFill(serviceCollection, builder);

            return serviceCollection;
        }
        public static SmtpClient GenerateSmtpClient(this SmtpConfigurationEntity config)
        {
            if (config.DeliveryMethod != SmtpDeliveryMethod.Network)
            {
                return new SmtpClient
                {
                    DeliveryFormat = config.DeliveryFormat,
                    DeliveryMethod = config.DeliveryMethod,
                    PickupDirectoryLocation = config.PickupDirectoryLocation,
                };
            }
            else
            {
                SmtpClient client = EmailLogic.SafeSmtpClient(config.Network.Host, config.Network.Port);
                client.DeliveryFormat = config.DeliveryFormat;
                client.UseDefaultCredentials = config.Network.UseDefaultCredentials;
                client.Credentials = config.Network.Username.HasText() ? new NetworkCredential(config.Network.Username, config.Network.Password) : null;
                client.EnableSsl = config.Network.EnableSSL;

                foreach (var cc in config.Network.ClientCertificationFiles)
                {
                    client.ClientCertificates.Add(cc.CertFileType == CertFileType.CertFile ?
                        X509Certificate.CreateFromCertFile(cc.FullFilePath)
                        : X509Certificate.CreateFromSignedFile(cc.FullFilePath));
                }

                return client;
            }
        }
        /// <summary>
        /// Appends key=value to the string.
        /// Does not append ? or &amp; before key=value.
        /// </summary>
        public static StringBuilder AppendQueryParam(this StringBuilder sb, string key, string value)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(key));
            Debug.Assert(value != null);

            return sb.Append(key).Append('=').Append(value);
        }
Пример #8
1
        // Create an md5 sum string of this string
        public static string GetMd5Sum(this string str)
        {
            // First we need to convert the string into bytes, which
            // means using a text encoder.
            Encoder enc = System.Text.Encoding.Unicode.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] unicodeText = new byte[str.Length * 2];
            enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

            // Now that we have a byte array we can ask the CSP to hash it
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(unicodeText);

            // Build the final string by converting each byte
            // into hex and appending it to a StringBuilder
            var sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }

            // And return it
            return sb.ToString();
        }
Пример #9
1
 /// <summary>
 /// 	Sets the time on the specified DateTime value using the specified time zone.
 /// </summary>
 /// <param name = "datetimeOff">The base date.</param>
 /// <param name = "timespan">The TimeSpan to be applied.</param>
 /// <param name = "localTimeZone">The local time zone.</param>
 /// <returns>/// The DateTimeOffset including the new time value/// </returns>
 public static DateTimeOffset SetTime(this DateTimeOffset datetimeOff, TimeSpan timespan,
                                      TimeZoneInfo localTimeZone)
 {
     var localDate = datetimeOff.ToLocalDateTime(localTimeZone);
     localDate.SetTime(timespan);
     return localDate.ToDateTimeOffset(localTimeZone);
 }
Пример #10
1
        public static bool IsLegalSize(this int size, KeySizes[] legalSizes, out bool validatedByZeroSkipSizeKeySizes)
        {
            validatedByZeroSkipSizeKeySizes = false;
            for (int i = 0; i < legalSizes.Length; i++)
            {
                KeySizes currentSizes = legalSizes[i];
                
                // If a cipher has only one valid key size, MinSize == MaxSize and SkipSize will be 0
                if (currentSizes.SkipSize == 0)
                {
                    if (currentSizes.MinSize == size)
                    {
                        // Signal that we were validated by a 0-skipsize KeySizes entry. Needed to preserve a very obscure
                        // piece of back-compat behavior.
                        validatedByZeroSkipSizeKeySizes = true;
                        return true;
                    }
                }
                else if (size >= currentSizes.MinSize && size <= currentSizes.MaxSize)
                {
                    // If the number is in range, check to see if it's a legal increment above MinSize
                    int delta = size - currentSizes.MinSize;

                    // While it would be unusual to see KeySizes { 10, 20, 5 } and { 11, 14, 1 }, it could happen.
                    // So don't return false just because this one doesn't match.
                    if (delta % currentSizes.SkipSize == 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
Пример #11
1
		/// <summary>
		/// Return the substring up to but not including the first instance of 'c'.
		/// If 'c' is not found, the entire string is returned.
		/// </summary>
		public static string SubstringBefore (this String src, char c) {
			if (String.IsNullOrEmpty(src)) return "";
 
			int idx = Math.Min(src.Length, src.IndexOf(c));
			if (idx < 0) return src;
			return src.Substring(0, idx);
		}
Пример #12
1
        public static void Dump(this IMix mix, string name = null)
        {
            Console.WriteLine("-------------------------------------------------------");

            if (name != null)
            {
                Console.WriteLine(name);
                Console.WriteLine("-------------------------------------------------------");
            }

            for (int i = 0; i < mix.Count; i++)
            {
                IMixItem item = mix[i];

                Transition transition = item.Transition;

                string strategy = transition.Strategy == null
                                   ? "<null strategy>"
                                   : transition.Strategy.Description;

                Console.WriteLine(">>> {0} --> {1} using {2}", transition.FromKey, transition.ToKey, strategy);
                Console.WriteLine("{0}. {1}/{2:0.#}bpm {3}", i, item.ActualKey, item.ActualBpm, item.Track);
            }

            Console.WriteLine("{0} tracks total.", mix.Count);
            Console.WriteLine("-------------------------------------------------------");
        }
Пример #13
1
        public static Type GetEntityType(this Type type)
        {
            if (!type.IsCrudController()) return null;

            var @interface = type.FindInterfaceThatCloses(typeof(CrudController<,>));
            return @interface.GetGenericArguments()[0];
        }
Пример #14
0
 public static void AssertNotNullOrEmpty(this string source, string message = null)
 {
     if (string.IsNullOrEmpty(source))
     {
         throw new Exception("Assertion failed: " + (message ?? "expected to not be null or empty"));
     }
 }
Пример #15
0
        public static string CreateAutoCompleteDictionaryEntryHash(this string entry, bool log = true)
        {
            if (!string.IsNullOrWhiteSpace(entry))
            {
                //Trim white space
                string hash = entry.Trim();
                
                //Hashes are stored without diacritics (accents etc)
                hash = hash.RemoveDiacritics();

                //Hashes are stored as uppercase
                hash = hash.ToUpper();
                
                if (!string.IsNullOrWhiteSpace(hash))
                {
                    if (log)
                    {
                        Log.DebugFormat("Entry of '{0}' hashed to '{1}'", entry, hash);
                    }

                    return hash;
                }
            }

            return null;
        }
Пример #16
0
 public static LEAP_VECTOR ToCVector(this Vector3 vector) {
   LEAP_VECTOR cVector = new LEAP_VECTOR();
   cVector.x = vector.x;
   cVector.y = vector.y;
   cVector.z = vector.z;
   return cVector;
 }
Пример #17
0
        public static string Decrypt(this string stringToDecrypt, string key)
        {
            if (string.IsNullOrEmpty(stringToDecrypt))
            {
                throw new ArgumentException("An empty string value cannot be encrypted.");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
            }

            //var cspp = new CspParameters { KeyContainerName = key };
            var cspp = new CspParameters { KeyContainerName = key, Flags = CspProviderFlags.UseMachineKeyStore };

            var rsa = new RSACryptoServiceProvider(cspp) { PersistKeyInCsp = true };

            var decryptArray = stringToDecrypt.Split(new[] { "-" }, StringSplitOptions.None);
            var decryptByteArray = Array.ConvertAll(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


            byte[] bytes = rsa.Decrypt(decryptByteArray, true);

            string result = System.Text.Encoding.UTF8.GetString(bytes);

            return result;
        }
Пример #18
0
		/// <summary>
		/// Return the substring after to but not including the last instance of 'c'.
		/// If 'c' is not found, the entire string is returned.
		/// </summary>
		public static string SubstringAfterLast (this String src, char c) {
			if (String.IsNullOrEmpty(src)) return "";
 
			int idx = Math.Min(src.Length - 1, src.LastIndexOf(c) + 1);
			if (idx < 0) return src;
			return src.Substring(idx);
		}
Пример #19
0
 public static void DisposeIfNotNull(this IDisposable disposable)
 {
     if (disposable != null)
     {
         disposable.Dispose();
     }
 }
Пример #20
0
 public static StringBuilder AppendEscapedXml(this StringBuilder builder, string value)
 {
   if (value == null) return builder;
   builder.EnsureCapacity(builder.Length + value.Length + 10);
   for (var i = 0; i < value.Length; i++)
   {
     switch (value[i])
     {
       case '&':
         builder.Append("&amp;");
         break;
       case '<':
         builder.Append("&lt;");
         break;
       case '>':
         builder.Append("&gt;");
         break;
       case '"':
         builder.Append("&quot;");
         break;
       case '\'':
         builder.Append("&apos;");
         break;
       default:
         builder.Append(value[i]);
         break;
     }
   }
   return builder;
 }
        public static UITextureAtlas GetInfoTooltip(this AssetManager assetManager, string infoTooltipName, string infoTooltipPath)
        {
            var infoTooltipAtlas = ScriptableObject.CreateInstance<UITextureAtlas>();
            infoTooltipAtlas.padding = 0;
            infoTooltipAtlas.name = infoTooltipName;

            var shader = Shader.Find("UI/Default UI Shader");
            if (shader != null) infoTooltipAtlas.material = new Material(shader);

            var texture = assetManager.GetTexture(infoTooltipPath);

            infoTooltipAtlas.material.mainTexture = texture;

            const int ittW = 535;
            const int ittH = 150;

            var sprite = new UITextureAtlas.SpriteInfo
            {
                name = string.Format(infoTooltipName.ToUpper()),
                region = new Rect(0f, 0f, 1f, 1f),
                texture = new Texture2D(ittW, ittH, TextureFormat.ARGB32, false)
            };

            infoTooltipAtlas.AddSprite(sprite);

            return infoTooltipAtlas;
        }
Пример #22
0
        /*public static float NextFloat(this Random rand, float maxValue = 1.0f, float minValue=0.0f)
        {
            return (float)rand.NextDouble() * (maxValue - minValue) + minValue;
        }*/
        public static Vector2 NextVector2(this Random rand, float maxLength = 1.0f, float minLength = 1.0f)
        {
            double theta = rand.NextDouble() * 2 * Math.PI;
            float length = rand.NextFloat(minLength, maxLength);

            return new Vector2(length * (float)Math.Cos(theta), length * (float)Math.Sin(theta));
        }
        public static IIntermediarySocket AsIntermediary(this EasyZMqConfigurer configurer, string backendAddress)
        {
            var frontendAddressBinder = configurer.AddressBinder;
            var backendAddressBinder = new BindAddressBinder(new Uri(backendAddress));

            return CreateIntermediarySocket(frontendAddressBinder, backendAddressBinder);
        }
Пример #24
0
 /// <summary>
 ///  Returns maximum spell range based on hitbox of unit. 
 /// </summary>
 /// <param name="spell"></param>
 /// <param name="unit"></param>
 /// <returns>Maximum spell range</returns>
 public static float ActualMaxRange(this WoWSpell spell, WoWUnit unit)
 {
     if (spell.MaxRange == 0)
         return 0;
     // 0.3 margin for error
     return unit != null ? spell.MaxRange + unit.CombatReach + 1f : spell.MaxRange;
 }
        public static string FQN(this XElement element)
        {
            if (element == null)
                return string.Empty;

            var ns = element.Name.NamespaceName;
            var prefix = element.Document.Root.GetPrefixOfNamespace(ns);

            if (string.IsNullOrWhiteSpace(prefix))
            {
                var nsRoot = element.Document.Root.GetDefaultNamespace().NamespaceName;
                if (!string.IsNullOrWhiteSpace(nsRoot))
                {
                    if (string.IsNullOrWhiteSpace(prefix) && nsRoot.Equals(ns))
                    {
                        prefix = Common.DefaultNamespace;
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(prefix))
                prefix = prefix + ":";

            return prefix + element.Name.LocalName;
        }
        public static string FQN(this XAttribute element)
        {
            if (element == null)
                return string.Empty;

            return "@" + element.Name.LocalName;
        }
Пример #27
0
	    public static string Series(this UrlHelper helper, int seriesId, string seriesSlug)
	    {
	        return helper.Action(
                MVC.Posts.ActionNames.Series,
	            MVC.Posts.Name,
	            new { seriesId, seriesSlug });
	    }
 private static void TraceMessage(this Message message)
 {
     Console.WriteLine("\tTime:       {0}", DateTime.Now.ToString("HH:mm:ss.ffffff"));
     Console.WriteLine("\tMessage ID: {0}", message.Id);
     Console.WriteLine("\tCorrel. ID: {0}", message.CorrelationId);
     Console.WriteLine("\tContents:   {0}", message.Body);
 }
Пример #29
0
		public static Field.Index GetIndex(this IndexDefinition self, string name, Field.Index? defaultIndex)
		{
			if (self.Indexes == null)
				return defaultIndex ?? Field.Index.ANALYZED_NO_NORMS;
			FieldIndexing value;
			if (self.Indexes.TryGetValue(name, out value) == false)
			{
				if (self.Indexes.TryGetValue(Constants.AllFields, out value) == false)
				{
					string ignored;
					if (self.Analyzers.TryGetValue(name, out ignored) ||
						self.Analyzers.TryGetValue(Constants.AllFields, out ignored))
					{
						return Field.Index.ANALYZED; // if there is a custom analyzer, the value should be analyzed
					}
					return defaultIndex ?? Field.Index.ANALYZED_NO_NORMS;
				}
			}
			switch (value)
			{
				case FieldIndexing.No:
					return Field.Index.NO;
				case FieldIndexing.Analyzed:
					return Field.Index.ANALYZED_NO_NORMS;
				case FieldIndexing.NotAnalyzed:
					return Field.Index.NOT_ANALYZED_NO_NORMS;
				case FieldIndexing.Default:
					return defaultIndex ?? Field.Index.ANALYZED_NO_NORMS;
				default:
					throw new ArgumentOutOfRangeException();
			}
		}
Пример #30
0
 public static AttributeGroup FixedDates(this AttributeGroup group)
 {
     group.UtcCreated = FixedSystemDate;
     group.UtcModified = FixedSystemDate;
     group.UtcStatusChanged = FixedSystemDate;
     return group;
 }
Пример #31
0
 public (long, error) Write(slice <byte> p) => s_WriteByRef?.Invoke(ref this, p) ?? s_WriteByVal?.Invoke(this, p) ?? WriteCloser?.Write(p) ?? throw new PanicException(RuntimeErrorPanic.NilPointerDereference);
Пример #32
0
 public static float AddDT(ref this float val)
 {
     return(val += Time.deltaTime);
 }
Пример #33
0
 public static unsafe bool Read(ref this BufferReader <byte> r, out B x)
 internal static BitArray ReadBitArray(ref this SequenceReader <byte> reader, int length, bool defaultValue = false)
Пример #35
0
 public static void SetAlpha(ref this RgbaFloat color, float alpha)
Пример #36
0
 public static void WriteVarInt <TBufferWriter>(ref this Writer <TBufferWriter> writer, sbyte value) where TBufferWriter : IBufferWriter <byte> => WriteVarInt(ref writer, ZigZagEncode(value));
Пример #37
0
 public static int Add(ref this int value, int operand)
 => Interlocked.Add(ref value, operand);
Пример #38
0
 // 構造体(値型)は OK
 public static void M(ref this int x)
 {
 }
 public static JobHandle ScheduleRef <T>(ref this T str, JobHandle dependsOn = default) where T : unmanaged, IJob
Пример #40
0
 public static void SetValuesFromArray(ref this Matrix4x4 matrix, float[] array)
Пример #41
0
 internal static unsafe void WriteAsciiNoValidation(ref this BufferWriter <PipeWriter> buffer, string data)
 public static ref UnsafePtrList ListData(ref this UnsafeArchetypePtrList from) => ref UnsafeUtilityEx.As <UnsafeArchetypePtrList, UnsafePtrList>(ref from);
 public static ref UnsafePtrList ListData(ref this UnsafeEntityQueryDataPtrList from) => ref UnsafeUtilityEx.As <UnsafeEntityQueryDataPtrList, UnsafePtrList>(ref from);
 internal static unsafe bool TryRead <T>(ref this SequenceReader <byte> reader, out T value)
Пример #45
0
 public static bool CompareAndSet(ref this int value, int expected, int update)
 => Interlocked.CompareExchange(ref value, update, expected) == expected;
Пример #46
0
 public static ScopedIValueLockEntry <TLock> EnterScoped <TLock>(ref this TLock @lock) where TLock : struct, IValueLock
 {
     return(new ScopedIValueLockEntry <TLock>(ref @lock));
 }
Пример #47
0
 public static int DecrementAndGet(ref this int value)
 => Interlocked.Decrement(ref value);
 public static ref UnsafeList ListData(ref this UnsafeUintList from) => ref UnsafeUtilityEx.As <UnsafeUintList, UnsafeList>(ref from);
Пример #49
0
 public static int SetAndGet(ref this int value, int update)
 {
     VolatileWrite(ref value, update);
     return(update);
 }
Пример #50
0
 // Special case so we don't *need* to use SpinLockWrapped
 public static ScopedIValueLockEntry EnterScoped(ref this SpinLock @lock)
 {
     return(new ScopedIValueLockEntry(ref @lock));
 }
Пример #51
0
 public static int GetAndSet(ref this int value, int update)
 => Interlocked.Exchange(ref value, update);
Пример #52
0
 public static unsafe NativeArray <T> SkipFirst <T>(ref this NativeArray <T> array) where T : struct
Пример #53
0
 public static string ReadString(ref this SequenceReader <byte> reader, long length = 0)
Пример #54
0
 public static void AddDependency(ref this JobHandle self, JobHandle handle0)
Пример #55
0
 public static unsafe bool TryParse(ref this BufferReader <byte> reader, out bool value)
Пример #56
0
 public static void Clamp <T>(ref this T val, T min, T max) where T : struct, IComparable <T>
Пример #57
0
 // 制約が付いていないとダメ。コンパイル エラー
 public static void M1 <T>(ref this T x)
 {
 }
Пример #58
0
 /// <summary>
 /// Adds or removes a flag.
 /// </summary>
 /// <param name="t"></param>
 /// <param name="flag">One or more flags to add or remove.</param>
 /// <param name="add">If true, adds flag, else removes flag.</param>
 public static unsafe void SetFlag <T>(ref this T t, T flag, bool add) where T : unmanaged, Enum
Пример #59
0
 // クラス(参照型)はダメ。コンパイル エラー
 public static void M(ref this string x)
 {
 }
Пример #60
0
 // struct 制約が付いていれば OK
 public static void M2 <T>(ref this T x) where T : struct
 {
 }