commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
362007e5d352d3eafcc260a2270fa8833d2bbf05
correct the assembly information for SQLiteNG
TomDataworks/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC
OpenSim/Data/SQLiteNG/Properties/AssemblyInfo.cs
OpenSim/Data/SQLiteNG/Properties/AssemblyInfo.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Reflection; using System.Runtime.InteropServices; // General information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly : AssemblyTitle("OpenSim.Data.SQLiteNG")] [assembly : AssemblyDescription("")] [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("http://opensimulator.org")] [assembly : AssemblyProduct("OpenSim.Data.SQLiteNG")] [assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly : ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly : Guid("6113d5ce-4547-49f4-9236-0dcc503457b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly : AssemblyVersion("0.6.5.*")] [assembly : AssemblyFileVersion("0.6.5.0")]
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Reflection; using System.Runtime.InteropServices; // General information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly : AssemblyTitle("OpenSim.Data.SQLite")] [assembly : AssemblyDescription("")] [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("http://opensimulator.org")] [assembly : AssemblyProduct("OpenSim.Data.SQLite")] [assembly : AssemblyCopyright("Copyright (c) OpenSimulator.org Developers 2007-2009")] [assembly : AssemblyTrademark("")] [assembly : AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly : ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly : Guid("6113d5ce-4547-49f4-9236-0dcc503457b1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly : AssemblyVersion("0.6.5.*")] [assembly : AssemblyFileVersion("0.6.5.0")]
bsd-3-clause
C#
d0bead69a709d8dfaeb827746e5f492b7e295915
Fix clear of histogram
FSchiltz/RawParser,FSchiltz/RawParser,FSchiltz/RawParser
Source/RawParser/View/UIHelper/Histogram.cs
Source/RawParser/View/UIHelper/Histogram.cs
using System; using Windows.ApplicationModel.Core; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; namespace RawEditor.View.UIHelper { class Histogram { //TODO simplify if memory saver mode public static async void Create(int[] value, ushort colorDepth, uint height, uint width, Canvas histogramCanvas) { await CoreApplication.MainView.CoreWindow.Dispatcher .RunAsync(CoreDispatcherPriority.Normal, () => { histogramCanvas.Children.Clear(); }); for (int i = 0; i < value.Length; i++) { Line line = null; await CoreApplication.MainView.CoreWindow.Dispatcher .RunAsync(CoreDispatcherPriority.Normal, () => { int widthstep = (int)(value.Length / histogramCanvas.ActualWidth); value[i] = (int)(value[i] / ((height * width) / (256 * 10))); line = new Line(); line.Stroke = new SolidColorBrush(Colors.Black); line.StrokeThickness = 1; line.X1 = line.X2 = (i * widthstep); line.Y1 = histogramCanvas.Height; line.Y2 = (int)(histogramCanvas.Height - value[i]); histogramCanvas.Children.Add(line); }); } } } }
using System; using Windows.ApplicationModel.Core; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; namespace RawEditor.View.UIHelper { class Histogram { //TODO simplify if memory saver mode public static async void Create(int[] value, ushort colorDepth, uint height, uint width, Canvas histogramCanvas) { for (int i = 0; i < value.Length; i++) { Line line = null; await CoreApplication.MainView.CoreWindow.Dispatcher .RunAsync(CoreDispatcherPriority.Normal, () => { int widthstep = (int)(value.Length / histogramCanvas.ActualWidth); value[i] = (int)(value[i] / ((height * width) / (256 * 10))); line = new Line(); line.Stroke = new SolidColorBrush(Colors.Black); line.StrokeThickness = 1; line.X1 = line.X2 = (i * widthstep); line.Y1 = histogramCanvas.Height; line.Y2 = (int)(histogramCanvas.Height - value[i]); histogramCanvas.Children.Add(line); }); } } } }
mit
C#
c0ade649cda80ad143d4ba48a63fe9dc598f24bb
Fix CF - comment
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Extensions/MemoryExtensions.cs
WalletWasabi/Extensions/MemoryExtensions.cs
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.Caching.Memory { public static class MemoryExtensions { private static Dictionary<IMemoryCache, Dictionary<object, AsyncLock>> AsyncLocks { get; } = new Dictionary<IMemoryCache, Dictionary<object, AsyncLock>>(); private static object AsyncLocksLock { get; } = new object(); public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (cache.TryGetValue(key, out TItem value)) { return value; } AsyncLock asyncLock; lock (AsyncLocksLock) { // If we have no dic for the cache yet then create one. if (!AsyncLocks.TryGetValue(cache, out Dictionary<object, AsyncLock> cacheDic)) { cacheDic = new Dictionary<object, AsyncLock>(); AsyncLocks.Add(cache, cacheDic); } if (!cacheDic.TryGetValue(key, out asyncLock)) { asyncLock = new AsyncLock(); cacheDic.Add(key, asyncLock); } } using (await asyncLock.LockAsync().ConfigureAwait(false)) { if (!cache.TryGetValue(key, out value)) { value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false); lock (AsyncLocksLock) { var cacheDic = AsyncLocks[cache]; // Note that if a cache is disposed, then the cleanup will never happen. This should not cause normally issues, but keep in mind. // Cleanup the evicted asynclocks. foreach (var toRemove in cacheDic.Keys.Where(x => !cache.TryGetValue(x, out _)).ToList()) { cacheDic.Remove(toRemove); } } } return value; } } } }
using Nito.AsyncEx; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Extensions.Caching.Memory { public static class MemoryExtensions { private static Dictionary<IMemoryCache, Dictionary<object, AsyncLock>> AsyncLocks { get; } = new Dictionary<IMemoryCache, Dictionary<object, AsyncLock>>(); private static object AsyncLocksLock { get; } = new object(); public static async Task<TItem> AtomicGetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory) { if (cache.TryGetValue(key, out TItem value)) { return value; } AsyncLock asyncLock; lock (AsyncLocksLock) { // If we have no dic for the cache yet then create one. if (!AsyncLocks.TryGetValue(cache, out Dictionary<object, AsyncLock> cacheDic)) { cacheDic = new Dictionary<object, AsyncLock>(); AsyncLocks.Add(cache, cacheDic); } if (!cacheDic.TryGetValue(key, out asyncLock)) { asyncLock = new AsyncLock(); cacheDic.Add(key, asyncLock); } } using (await asyncLock.LockAsync().ConfigureAwait(false)) { if (!cache.TryGetValue(key, out value)) { value = await cache.GetOrCreateAsync(key, factory).ConfigureAwait(false); lock (AsyncLocksLock) { var cacheDic = AsyncLocks[cache]; // Note that if a cache is disposed, then the cleanup will never happen. This should not cause normally issues, but keep in mind. // Cleanup the evicted asynclocks. foreach (var toRemove in cacheDic.Keys.Where(x => !cache.TryGetValue(x, out _)).ToList()) { cacheDic.Remove(toRemove); } } } return value; } } } }
mit
C#
8e65642dc2ba5dcfc710ae35ead6bf9f4a684872
Rename variable.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Extensions/StreamExtensions.cs
WalletWasabi/Extensions/StreamExtensions.cs
using System.Buffers; using System.Threading; using System.Threading.Tasks; namespace System.IO { public static class StreamExtensions { public static async Task<int> ReadByteAsync(this Stream stream, CancellationToken ctsToken = default) { ArrayPool<byte> pool = ArrayPool<byte>.Shared; byte[] buffer = pool.Rent(1); try { int len = await stream.ReadAsync(buffer.AsMemory(0, 1), ctsToken).ConfigureAwait(false); // End of stream. if (len == 0) { return -1; } return buffer[0]; } finally { pool.Return(buffer); } } /// <summary> /// Attempts to read <paramref name="count"/> bytes from <paramref name="stream"/>. /// </summary> /// <param name="stream">Stream to read from.</param> /// <param name="buffer">Buffer whose length must be at least <paramref name="count"/> elements.</param> /// <param name="count">Number of bytes to read.</param> /// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param> /// <returns>Number of read bytes. At most <paramref name="count"/>.</returns> public static async Task<int> ReadBlockAsync(this Stream stream, byte[] buffer, int count, CancellationToken cancellationToken = default) { int remaining = count; while (remaining != 0) { int read = await stream.ReadAsync(buffer.AsMemory(count - remaining, remaining), cancellationToken).ConfigureAwait(false); // End of stream. if (read == 0) { break; } remaining -= read; } return count - remaining; } } }
using System.Buffers; using System.Threading; using System.Threading.Tasks; namespace System.IO { public static class StreamExtensions { public static async Task<int> ReadByteAsync(this Stream stream, CancellationToken ctsToken = default) { ArrayPool<byte> pool = ArrayPool<byte>.Shared; byte[] buffer = pool.Rent(1); try { int len = await stream.ReadAsync(buffer.AsMemory(0, 1), ctsToken).ConfigureAwait(false); // End of stream. if (len == 0) { return -1; } return buffer[0]; } finally { pool.Return(buffer); } } /// <summary> /// Attempts to read <paramref name="count"/> bytes from <paramref name="stream"/>. /// </summary> /// <param name="stream">Stream to read from.</param> /// <param name="buffer">Buffer whose length must be at least <paramref name="count"/> elements.</param> /// <param name="count">Number of bytes to read.</param> /// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param> /// <returns>Number of read bytes. At most <paramref name="count"/>.</returns> public static async Task<int> ReadBlockAsync(this Stream stream, byte[] buffer, int count, CancellationToken cancellationToken = default) { int left = count; while (left != 0) { int read = await stream.ReadAsync(buffer.AsMemory(count - left, left), cancellationToken).ConfigureAwait(false); // End of stream. if (read == 0) { break; } left -= read; } return count - left; } } }
mit
C#
07f2b1e75386275480869858b22f43fb22c6b823
Tweak to wrapper
mcintyre321/Noodles,mcintyre321/Noodles
WebNoodle/Reflection/ObjectMethodWrapper.cs
WebNoodle/Reflection/ObjectMethodWrapper.cs
using System.Collections.Generic; namespace WebNoodle { public class ObjectMethodWrapper : IObjectMethod, IHasPath { private readonly IObjectMethod _inner; private string _innerName; private string _innerDisplayName; public string Name { get { return _innerName ?? _inner.Name; } set { _innerName = value; } } public string DisplayName { get { return _innerDisplayName ?? _inner.DisplayName; } set { _innerDisplayName = value; } } public IEnumerable<ObjectMethodParameter> Parameters { get { return _inner.Parameters; } } public object Target { get { return _inner.Target; } } public object Parent { set; private get; } public string SuccessMessage { get { return _inner.SuccessMessage; } } public void Invoke(object[] parameters) { _inner.Invoke(parameters); } public ObjectMethodWrapper(IObjectMethod inner) { _inner = inner; } public string Path { get { return (Parent ?? (this.Target.Path())) + "?action=getNodeMethod"; } } } }
using System.Collections.Generic; namespace WebNoodle { public class ObjectMethodWrapper : IObjectMethod, IHasPath { private readonly IObjectMethod _inner; private string _innerName; private string _innerDisplayName; private string _path; public string Name { get { return _innerName ?? _inner.Name; } set { _innerName = value; } } public string DisplayName { get { return _innerDisplayName ?? _inner.DisplayName; } set { _innerDisplayName = value; } } public IEnumerable<ObjectMethodParameter> Parameters { get { return _inner.Parameters; } } public object Target { get { return _inner.Target; } } public string SuccessMessage { get { return _inner.SuccessMessage; } } public void Invoke(object[] parameters) { _inner.Invoke(parameters); } public ObjectMethodWrapper(IObjectMethod inner) { _inner = inner; } public string Path { get { return _path ?? this.Target.Path(); } set { _path = value; } } } }
mit
C#
f03b8206da2c2a3e7eaa045b8631c882c352785f
Make banana showers always last in combo (explodey)
ZLima12/osu,peppy/osu-new,ZLima12/osu,ppy/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu,Frontear/osuKyzer,2yangk23/osu,DrabWeb/osu,UselessToucan/osu,peppy/osu,naoey/osu,smoogipoo/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,Nabile-Rahmani/osu,UselessToucan/osu,ppy/osu,naoey/osu,johnneijzen/osu,EVAST9919/osu,naoey/osu,2yangk23/osu,peppy/osu,DrabWeb/osu
osu.Game.Rulesets.Catch/Objects/BananaShower.cs
osu.Game.Rulesets.Catch/Objects/BananaShower.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.MathUtils; using osu.Game.Rulesets.Objects.Types; using OpenTK.Graphics; namespace osu.Game.Rulesets.Catch.Objects { public class BananaShower : CatchHitObject, IHasEndTime { public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana; public override bool LastInCombo => true; protected override void CreateNestedHitObjects() { base.CreateNestedHitObjects(); createBananas(); } private void createBananas() { double spacing = Duration; while (spacing > 100) spacing /= 2; if (spacing <= 0) return; for (double i = StartTime; i <= EndTime; i += spacing) AddNested(new Banana { Samples = Samples, ComboColour = getNextComboColour(), StartTime = i, X = RNG.NextSingle() }); } private Color4 getNextComboColour() { switch (RNG.Next(0, 3)) { default: return new Color4(255, 240, 0, 255); case 1: return new Color4(255, 192, 0, 255); case 2: return new Color4(214, 221, 28, 255); } } public double EndTime => StartTime + Duration; public double Duration { get; set; } public class Banana : Fruit { public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.MathUtils; using osu.Game.Rulesets.Objects.Types; using OpenTK.Graphics; namespace osu.Game.Rulesets.Catch.Objects { public class BananaShower : CatchHitObject, IHasEndTime { public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana; protected override void CreateNestedHitObjects() { base.CreateNestedHitObjects(); createBananas(); } private void createBananas() { double spacing = Duration; while (spacing > 100) spacing /= 2; if (spacing <= 0) return; for (double i = StartTime; i <= EndTime; i += spacing) AddNested(new Banana { Samples = Samples, ComboColour = getNextComboColour(), StartTime = i, X = RNG.NextSingle() }); } private Color4 getNextComboColour() { switch (RNG.Next(0, 3)) { default: return new Color4(255, 240, 0, 255); case 1: return new Color4(255, 192, 0, 255); case 2: return new Color4(214, 221, 28, 255); } } public double EndTime => StartTime + Duration; public double Duration { get; set; } public class Banana : Fruit { public override FruitVisualRepresentation VisualRepresentation => FruitVisualRepresentation.Banana; } } }
mit
C#
452faa02c1fdfe092e35607d267b471f9a5ca204
Update SlimyYoyo.cs
Minesap/TheMinepack
Items/Weapons/SlimyYoyo.cs
Items/Weapons/SlimyYoyo.cs
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Minepack.Items; namespace Minepack.Items.Weapons { public class SlimyYoyo : ModItem { public override void SetDefaults() { item.CloneDefaults(ItemID.Valor); item.name = "Slimy Yoyo"; item.damage = 12; item.channel = true; item.melee = true; item.knockBack = 4; item.value = 50000; item.rare = 3; item.autoReuse = false; item.shoot = mod.ProjectileType("SlimyYoyoProjectile"); } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "GelatinousBar", 10); recipe.AddIngredient(null, "YoyoString", 1); recipe.AddTile(TileID.Solidifier); recipe.SetResult(this); recipe.AddRecipe(); } }}
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Terraria; using Terraria.DataStructures; using Terraria.ID; using Terraria.ModLoader; using Minepack.Items; namespace Minepack.Items.Weapons { public class SlimyYoyo : ModItem { public override void SetDefaults() { item.CloneDefaults(ItemID.Valor); item.name = "Slimy Yoyo"; item.damage = 12; item.channel = true; item.melee = true; item.knockBack = 4; item.value = 50000; item.rare = 3; item.autoReuse = false; item.shoot = mod.ProjectileType("SlimyYoyo"); } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "GelatinousBar", 10); recipe.AddIngredient(null, "YoyoString", 1); recipe.AddTile(TileID.Solidifier); recipe.SetResult(this); recipe.AddRecipe(); } }}
mit
C#
6965f1400f8fdfb8d292c70639c22e725f6d86a1
Add string extension method
emoacht/Monitorian
Source/Monitorian.Core/Helper/StringExtension.cs
Source/Monitorian.Core/Helper/StringExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Monitorian.Core.Helper { /// <summary> /// Extension methods for <see cref="String"/> /// </summary> public static class StringExtension { /// <summary> /// Indicates whether a specified string is composed of all ASCII characters. /// </summary> /// <param name="source">Source string</param> /// <returns>True if all ASCII characters</returns> public static bool IsAscii(this string source) { if (source is null) return true; return source.Select(x => (int)x).All(x => x < 0x80); } /// <summary> /// Replaces a specified character with the characters of a specified length. /// </summary> /// <param name="source">Source string</param> /// <param name="value">Target character</param> /// <param name="repeatCount">Length of characters</param> /// <returns>Replaced string</returns> public static string Replace(this string source, char value, int repeatCount) { var buffer = new StringBuilder(); var isFound = false; foreach (var c in source) { if (char.Equals(value, c)) { isFound = true; continue; } if (isFound) { isFound = false; buffer.Append(value, repeatCount); } buffer.Append(c); } if (isFound) { buffer.Append(value, repeatCount); } return buffer.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Monitorian.Core.Helper { /// <summary> /// Extension methods for <see cref="String"/> /// </summary> public static class StringExtension { public static bool IsAscii(this string source) { if (source is null) return true; return source.Select(x => (int)x).All(x => x < 0x80); } } }
mit
C#
59474a611b59ffaa64ada299a37a4305ba7879a8
Improve logging.
rmcardle/LazerTagHost,rmcardle/LazerTagHost
LazerTagHostLibrary/Log.cs
LazerTagHostLibrary/Log.cs
using System; using System.ComponentModel; using System.Diagnostics; namespace LazerTagHostLibrary { public class Log { #region Public methods public static void Add(Severity severity, string format, params object[] arguments) { try { var time = DateTime.Now; var message = string.Format(format, arguments); Debug.WriteLine("{0}\t{1}\t{2}", time, severity, message); OnEntryAdded(new Entry(time, severity, message)); } catch (FormatException ex) { Add(String.Format("Error in format string: {0}", format), ex); } } public static void Add(string message, Exception ex) { Add(Severity.Error, string.Join(Environment.NewLine, new[] {message, GetExceptionMessageRecursive(ex)})); } public static string GetExceptionMessageRecursive(Exception ex) { return GetExceptionMessageRecursive(ex, Environment.NewLine); } public static string GetExceptionMessageRecursive(Exception ex, string separator) { var message = ex.Message; if (ex.InnerException != null) { var innerMessage = GetExceptionMessageRecursive(ex, separator); message = string.Join(separator, new[] {message, innerMessage}); } return message; } #endregion #region Events private static void OnEntryAdded(Entry entry) { if (EntryAdded != null) EntryAdded(null, new EntryAddedEventArgs(entry)); } public static event EntryAddedEventHandler EntryAdded; public delegate void EntryAddedEventHandler(object sender, EntryAddedEventArgs e); [ImmutableObject(true)] public class EntryAddedEventArgs : EventArgs { public EntryAddedEventArgs(Entry entry) { Entry = entry; } public Entry Entry { get; private set; } } #endregion #region Public classes [ImmutableObject(true)] public class Entry { public Entry(DateTime time, Severity severity, string message) { Time = time; Severity = severity; Message = message; } public DateTime Time { get; private set; } public Severity Severity { get; private set; } public string Message { get; private set; } } #endregion #region Public enumerations public enum Severity { Debug = 0, Information = 1, Warning = 2, Error = 3, } #endregion } }
using System; using System.ComponentModel; using System.Diagnostics; namespace LazerTagHostLibrary { public class Log { public static void Add(Severity severity, string format, params object[] arguments) { if (severity < LogLevel) return; try { var message = string.Format(format, arguments); var entry = string.Format("{0}\t{1}", DateTime.Now, message); Debug.WriteLine(entry); OnEntryAdded(severity, entry); } catch (FormatException ex) { Add(String.Format("Error in format string: {0}", format), ex); } } public static void Add(string message, Exception ex) { Add(Severity.Error, string.Join(Environment.NewLine, new[] {message, GetExceptionMessageRecursive(ex)})); } public static string GetExceptionMessageRecursive(Exception ex) { return GetExceptionMessageRecursive(ex, Environment.NewLine); } public static string GetExceptionMessageRecursive(Exception ex, string separator) { var message = ex.Message; if (ex.InnerException != null) { var innerMessage = GetExceptionMessageRecursive(ex, separator); message = string.Join(separator, new[] {message, innerMessage}); } return message; } #if DEBUG public static Severity LogLevel = Severity.Debug; #else public static Severity LogLevel = Severity.Information; #endif public delegate void EntryAddedEventHandler(object sender, EntryAddedEventArgs e); public static event EntryAddedEventHandler EntryAdded; public enum Severity { Debug = 0, Information = 1, Warning = 2, Error = 3, } [ImmutableObject(true)] public class EntryAddedEventArgs : EventArgs { public EntryAddedEventArgs(Severity severity, string entry) { Severity = severity; Entry = entry; } public Severity Severity { get; private set; } public string Entry { get; private set; } } private static void OnEntryAdded(Severity severity, string entry) { if (EntryAdded != null) EntryAdded(null, new EntryAddedEventArgs(severity, entry)); } } }
mit
C#
8f15681a87d59a30e7f42bdb9012f975d94446c4
Update DistributedCacheQueryRepository.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/Cache/Distributed/DistributedCacheQueryRepository.cs
TIKSN.Core/Data/Cache/Distributed/DistributedCacheQueryRepository.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Options; using TIKSN.Serialization; namespace TIKSN.Data.Cache.Distributed { public class DistributedCacheQueryRepository<TEntity, TIdentity> : DistributedCacheRepository<TEntity, TIdentity>, IQueryRepository<TEntity, TIdentity> where TEntity : IEntity<TIdentity> where TIdentity : IEquatable<TIdentity> { public DistributedCacheQueryRepository( IDistributedCache distributedCache, ISerializer<byte[]> serializer, IDeserializer<byte[]> deserializer, IOptions<DistributedCacheDecoratorOptions> genericOptions, IOptions<DistributedCacheDecoratorOptions<TEntity>> specificOptions) : base(distributedCache, serializer, deserializer, genericOptions, specificOptions) { } public async Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken) { var cachedBytes = await this._distributedCache.GetAsync(this.CreateEntryCacheKey(id), cancellationToken); return cachedBytes != null; } public async Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken) { var result = await this.GetFromDistributedCacheAsync<TEntity>(this.CreateEntryCacheKey(id), cancellationToken); if (result == null) { throw new NullReferenceException("Result retrieved from cache or from original source is null."); } return result; } public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken) => this.GetFromDistributedCacheAsync<TEntity>(this.CreateEntryCacheKey(id), cancellationToken); public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken) => await BatchOperationHelper.BatchOperationAsync(ids, cancellationToken, (id, ct) => this.GetAsync(id, ct)); } }
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TIKSN.Serialization; namespace TIKSN.Data.Cache.Distributed { public class DistributedCacheQueryRepository<TEntity, TIdentity> : DistributedCacheRepository<TEntity, TIdentity>, IQueryRepository<TEntity, TIdentity> where TEntity : IEntity<TIdentity> where TIdentity : IEquatable<TIdentity> { public DistributedCacheQueryRepository( IDistributedCache distributedCache, ISerializer<byte[]> serializer, IDeserializer<byte[]> deserializer, IOptions<DistributedCacheDecoratorOptions> genericOptions, IOptions<DistributedCacheDecoratorOptions<TEntity>> specificOptions) : base(distributedCache, serializer, deserializer, genericOptions, specificOptions) { } public async Task<bool> ExistsAsync(TIdentity id, CancellationToken cancellationToken) { var cachedBytes = await _distributedCache.GetAsync(CreateEntryCacheKey(id), cancellationToken); return cachedBytes != null; } public async Task<TEntity> GetAsync(TIdentity id, CancellationToken cancellationToken) { var result = await GetFromDistributedCacheAsync<TEntity>(CreateEntryCacheKey(id), cancellationToken); if (result == null) { throw new NullReferenceException("Result retrieved from cache or from original source is null."); } return result; } public Task<TEntity> GetOrDefaultAsync(TIdentity id, CancellationToken cancellationToken) { return GetFromDistributedCacheAsync<TEntity>(CreateEntryCacheKey(id), cancellationToken); } public async Task<IEnumerable<TEntity>> ListAsync(IEnumerable<TIdentity> ids, CancellationToken cancellationToken) { return await BatchOperationHelper.BatchOperationAsync(ids, cancellationToken, (id, ct) => GetAsync(id, ct)); } } }
mit
C#
b00169a6cfdfd8ca01a0b0a3c3c3ffcc90830607
Add a helper method for multi delegates
mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp
binding/HarfBuzzSharp.Shared/DelegateProxies.cs
binding/HarfBuzzSharp.Shared/DelegateProxies.cs
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace HarfBuzzSharp { // public delegates public delegate void ReleaseDelegate (object context); public delegate Blob GetTableDelegate (Face face, Tag tag, object context); // bad choices. // this should not have had the "blob" prefix // it is a global dispose method, but we can't switch now // it is a breaking change since it will become ambiguous public delegate void BlobReleaseDelegate (object context); // internal proxy delegates [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate void ReleaseDelegateProxyDelegate (IntPtr context); [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate IntPtr GetTableDelegateProxyDelegate (IntPtr face, Tag tag, IntPtr context); internal static partial class DelegateProxies { // references to the proxy implementations public static readonly ReleaseDelegateProxyDelegate ReleaseDelegateProxy = ReleaseDelegateProxyImplementation; public static readonly ReleaseDelegateProxyDelegate ReleaseDelegateProxyForMulti = ReleaseDelegateProxyImplementationForMulti; public static readonly GetTableDelegateProxyDelegate GetTableDelegateProxy = GetTableDelegateProxyImplementation; // helper methods [MethodImpl (MethodImplOptions.AggressiveInlining)] public static IntPtr CreateMulti<T> (T wrappedDelegate, object context, ReleaseDelegate destroy) where T : Delegate { var destroyDelegate = destroy != null && context != null ? new ReleaseDelegate ((_) => destroy (context)) : destroy; var del = new GetMultiDelegateDelegate ((type) => { if (type == typeof (T)) return wrappedDelegate; if (type == typeof (ReleaseDelegate)) return destroyDelegate; throw new ArgumentOutOfRangeException (nameof (type)); }); Create (del, out _, out var ctx); return ctx; } [MethodImpl (MethodImplOptions.AggressiveInlining)] public static T GetMulti<T> (IntPtr contextPtr, out GCHandle gch) where T : Delegate { var multi = Get<GetMultiDelegateDelegate> (contextPtr, out gch); return (T)multi.Invoke (typeof (T)); } // internal proxy implementations [MonoPInvokeCallback (typeof (ReleaseDelegateProxyDelegate))] private static void ReleaseDelegateProxyImplementation (IntPtr context) { var del = Get<ReleaseDelegate> (context, out var gch); try { del.Invoke (null); } finally { gch.Free (); } } [MonoPInvokeCallback (typeof (GetTableDelegateProxyDelegate))] private static IntPtr GetTableDelegateProxyImplementation (IntPtr face, Tag tag, IntPtr context) { var del = GetMulti<GetTableDelegate> (context, out var gch); var blob = del.Invoke (null, tag, null); return blob?.Handle ?? IntPtr.Zero; } [MonoPInvokeCallback (typeof (ReleaseDelegateProxyDelegate))] private static void ReleaseDelegateProxyImplementationForMulti (IntPtr context) { var del = GetMulti<ReleaseDelegate> (context, out var gch); try { del?.Invoke (null); } finally { gch.Free (); } } } }
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace HarfBuzzSharp { // public delegates public delegate void ReleaseDelegate (object context); public delegate Blob GetTableDelegate (Face face, Tag tag, object context); // bad choices. // this should not have had the "blob" prefix // it is a global dispose method, but we can't switch now // it is a breaking change since it will become ambiguous public delegate void BlobReleaseDelegate (object context); // internal proxy delegates [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate void ReleaseDelegateProxyDelegate (IntPtr context); [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate IntPtr GetTableDelegateProxyDelegate (IntPtr face, Tag tag, IntPtr context); internal static partial class DelegateProxies { // references to the proxy implementations public static readonly ReleaseDelegateProxyDelegate ReleaseDelegateProxy = ReleaseDelegateProxyImplementation; public static readonly ReleaseDelegateProxyDelegate ReleaseDelegateProxyForMulti = ReleaseDelegateProxyImplementationForMulti; public static readonly GetTableDelegateProxyDelegate GetTableDelegateProxy = GetTableDelegateProxyImplementation; // helper methods [MethodImpl (MethodImplOptions.AggressiveInlining)] public static IntPtr CreateMulti<T> (T wrappedDelegate, object context, ReleaseDelegate destroy) where T : Delegate { var destroyDelegate = destroy != null && context != null ? new ReleaseDelegate ((_) => destroy (context)) : destroy; var del = new GetMultiDelegateDelegate ((type) => { if (type == typeof (T)) return wrappedDelegate; if (type == typeof (ReleaseDelegate)) return destroyDelegate; throw new ArgumentOutOfRangeException (nameof (type)); }); Create (del, out _, out var ctx); return ctx; } // internal proxy implementations [MonoPInvokeCallback (typeof (ReleaseDelegateProxyDelegate))] private static void ReleaseDelegateProxyImplementation (IntPtr context) { var del = Get<ReleaseDelegate> (context, out var gch); try { del.Invoke (null); } finally { gch.Free (); } } [MonoPInvokeCallback (typeof (GetTableDelegateProxyDelegate))] private static IntPtr GetTableDelegateProxyImplementation (IntPtr face, Tag tag, IntPtr context) { var multi = Get<GetMultiDelegateDelegate> (context, out var gch); var del = (GetTableDelegate)multi.Invoke (typeof (GetTableDelegate)); var blob = del.Invoke (null, tag, null); return blob?.Handle ?? IntPtr.Zero; } [MonoPInvokeCallback (typeof (ReleaseDelegateProxyDelegate))] private static void ReleaseDelegateProxyImplementationForMulti (IntPtr context) { var multi = Get<GetMultiDelegateDelegate> (context, out var gch); var del = (ReleaseDelegate)multi.Invoke (typeof (ReleaseDelegate)); try { del?.Invoke (null); } finally { gch.Free (); } } } }
mit
C#
d8167aaf807d0e2fe91cb79763e7ad8664cf3014
Add fog to PizzaModel.
saschb2b/mugo
mugo/PizzaModel.cs
mugo/PizzaModel.cs
using System; using Engine.cgimin.material.simpletexture; using Engine.cgimin.object3d; using Engine.cgimin.texture; using OpenTK; using Engine.cgimin.material.normalmappingfog; namespace Mugo { class PizzaModel : ClonedObject<PizzaModelInternal>, ITunnelSegementElementModel { private static readonly NormalMappingMaterialFog material = new NormalMappingMaterialFog(); public float Radius => radius; public new Matrix4 Transformation { get { return base.Transformation; } set { base.Transformation = value; } } public void Draw () { material.Draw(this, internalObject.TextureId, 0, 1f); } } internal class PizzaModelInternal : ObjLoaderObject3D { private const String objFilePath = "data/objects/Pizza.model"; private const String texturePath = "data/textures/Pizza.png"; public PizzaModelInternal () : base (objFilePath, 0.2f) { TextureId = TextureManager.LoadTexture (texturePath); Transformation *= Matrix4.CreateRotationY (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateRotationX (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateTranslation (0f, 1.5f, -TunnelSegmentConfig.Depth / 2f); DefaultTransformation = Transformation; } public int TextureId { get; private set; } public Matrix4 DefaultTransformation { get; } } }
using System; using Engine.cgimin.material.simpletexture; using Engine.cgimin.object3d; using Engine.cgimin.texture; using OpenTK; namespace Mugo { class PizzaModel : ClonedObject<PizzaModelInternal>, ITunnelSegementElementModel { private static readonly SimpleTextureMaterial material = new SimpleTextureMaterial(); public float Radius => radius; public new Matrix4 Transformation { get { return base.Transformation; } set { base.Transformation = value; } } public void Draw () { material.Draw(this, internalObject.TextureId); } } internal class PizzaModelInternal : ObjLoaderObject3D { private const String objFilePath = "data/objects/Pizza.model"; private const String texturePath = "data/textures/Pizza.png"; public PizzaModelInternal () : base (objFilePath, 0.2f) { TextureId = TextureManager.LoadTexture (texturePath); Transformation *= Matrix4.CreateRotationY (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateRotationX (MathHelper.DegreesToRadians (90)); Transformation *= Matrix4.CreateTranslation (0f, 1.5f, -TunnelSegmentConfig.Depth / 2f); DefaultTransformation = Transformation; } public int TextureId { get; private set; } public Matrix4 DefaultTransformation { get; } } }
mit
C#
392bc247e993db277f10aff164c07cb57d7e1379
remove code that would be deprecated on arrival
FacturAPI/facturapi-net
facturapi-net/Models/Organization.cs
facturapi-net/Models/Organization.cs
using System; using System.Collections.Generic; namespace Facturapi { public class Organization { public string Id { get; set; } public DateTime CreatedAt { get; set; } public bool IsProductionReady { get; set; } public List<CompletionStep> PendingSteps { get; set; } public Legal Legal { get; set; } public Customization Customization { get; set; } public Certificate Certificate { get; set; } } }
using Facturapi.Wrappers; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace Facturapi { public class Organization { public string Id { get; set; } public DateTime CreatedAt { get; set; } public bool IsProductionReady { get; set; } public List<CompletionStep> PendingSteps { get; set; } public Legal Legal { get; set; } public Customization Customization { get; set; } public Certificate Certificate { get; set; } public static Task<SearchResult<Organization>> ListAsync (Dictionary<string, object> query = null) { return new OrganizationWrapper().ListAsync(query); } public static Task<Organization> CreateAsync (Dictionary<string, object> data) { return new OrganizationWrapper().CreateAsync(data); } public static Task<Organization> RetrieveAsync (string id) { return new OrganizationWrapper().RetrieveAsync(id); } public static Task<Organization> DeleteAsync (string id) { return new OrganizationWrapper().DeleteAsync(id); } public static Task<Organization> UploadLogoAsync (string id, Stream file) { return new OrganizationWrapper().UploadLogoAsync(id, file); } public static Task<Organization> UploadCertificateAsync (string id, Stream cerFile, Stream keyFile, string password) { return new OrganizationWrapper().UploadCertificateAsync(id, cerFile, keyFile, password); } } }
mit
C#
a772ca5acffd65cb216aa4078f3eb4152f025830
Tweak skybox rotation direction and speed
iridinite/shiftdrive
Client/Skybox.cs
Client/Skybox.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace ShiftDrive { /// <summary> /// Contains static utilities to render a skybox. /// </summary> internal static class Skybox { private static float rotation; private static bool idleRotation; public static void SetIdleRotation(bool enabled) { idleRotation = enabled; } public static void Draw(GraphicsDevice graphicsDevice) { // Use the unlit shader to render a skybox. Effect fx = Assets.fxUnlit; // shortcut fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateRotationZ(rotation) * Matrix.CreateLookAt(new Vector3(0f, -0.25f, 2f), new Vector3(0, 0, 0), Vector3.Up) * SDGame.Inst.Projection); fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]); foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = fx; } fx.CurrentTechnique.Passes[0].Apply(); mesh.Draw(); } } public static void Update(GameTime gameTime) { if (!idleRotation) return; rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.04); while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace ShiftDrive { /// <summary> /// Contains static utilities to render a skybox. /// </summary> internal static class Skybox { private static float rotation; private static bool idleRotation; public static void SetIdleRotation(bool enabled) { idleRotation = enabled; } public static void Draw(GraphicsDevice graphicsDevice) { // Use the unlit shader to render a skybox. Effect fx = Assets.fxUnlit; // shortcut fx.Parameters["WVP"].SetValue(Matrix.CreateRotationY(rotation) * Matrix.CreateLookAt(new Vector3(0f, -0.2f, 2f), new Vector3(0, 0, 0), Vector3.Up) * SDGame.Inst.Projection); fx.Parameters["ModelTexture"].SetValue(Assets.textures["ui/skybox"]); foreach (ModelMesh mesh in Assets.mdlSkybox.Meshes) { foreach (ModelMeshPart part in mesh.MeshParts) { part.Effect = fx; } fx.CurrentTechnique.Passes[0].Apply(); mesh.Draw(); } } public static void Update(GameTime gameTime) { if (!idleRotation) return; rotation += (float)(gameTime.ElapsedGameTime.TotalSeconds * 0.05); while (rotation >= MathHelper.TwoPi) rotation -= MathHelper.TwoPi; } } }
bsd-3-clause
C#
6df8346f58e5a2e523ffe567ae46e358259b317c
Set Assembly Information
msarchet/Flipper
Flipper/Properties/AssemblyInfo.cs
Flipper/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Flipper")] [assembly: AssemblyDescription("A library for Flipping .NET features on and off")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Flipper")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6c4a3139-4ccf-48b4-adb8-7be7cf7b6833")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Flipper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Flipper")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6c4a3139-4ccf-48b4-adb8-7be7cf7b6833")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
b95176587ec911d4cff55216ef06b58e37c8f480
Add LocalMemoryType.None
sharwell/NOpenCL,tunnelvisionlabs/NOpenCL
NOpenCL/LocalMemoryType.cs
NOpenCL/LocalMemoryType.cs
namespace NOpenCL { public enum LocalMemoryType { None = 0, Local = 1, Global = 2, } }
namespace NOpenCL { public enum LocalMemoryType { Local = 1, Global = 2, } }
mit
C#
335fe3e3037d2320e763087f76d19ddfb7255e0f
update version
ezaurum/dapper
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Dapper Repository")] [assembly: AssemblyDescription("Dapper auto generated repository extension")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ezaurum")] [assembly: AssemblyProduct("dapper extention")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c3a998b9-1a09-4589-9e91-481383acb2ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.21")] [assembly: AssemblyFileVersion("0.0.1.21")] [assembly: NeutralResourcesLanguageAttribute("ko-KR")]
using System.Reflection; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Dapper Repository")] [assembly: AssemblyDescription("Dapper auto generated repository extension")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ezaurum")] [assembly: AssemblyProduct("dapper extention")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c3a998b9-1a09-4589-9e91-481383acb2ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.20")] [assembly: AssemblyFileVersion("0.0.1.20")] [assembly: NeutralResourcesLanguageAttribute("ko-KR")]
mit
C#
574ca1f4824549b5542985f873d231a80392beba
Update nullable annotations in Experiments folder
wvdd007/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,jmarolf/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,genlu/roslyn,weltkante/roslyn,KevinRansom/roslyn,tmat/roslyn,genlu/roslyn,panopticoncentral/roslyn,brettfo/roslyn,diryboy/roslyn,dotnet/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,AmadeusW/roslyn,jmarolf/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,wvdd007/roslyn,weltkante/roslyn,bartdesmet/roslyn,diryboy/roslyn,aelij/roslyn,tmat/roslyn,gafter/roslyn,heejaechang/roslyn,brettfo/roslyn,sharwell/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,physhi/roslyn,genlu/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,gafter/roslyn,mgoertz-msft/roslyn,physhi/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,sharwell/roslyn,mavasani/roslyn,stephentoub/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,weltkante/roslyn,heejaechang/roslyn,tannergooding/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,gafter/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,heejaechang/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,tannergooding/roslyn,tmat/roslyn,tannergooding/roslyn
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists"; public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Experiments { internal interface IExperimentationService : IWorkspaceService { bool IsExperimentEnabled(string experimentName); } [ExportWorkspaceService(typeof(IExperimentationService)), Shared] internal class DefaultExperimentationService : IExperimentationService { public bool ReturnValue = false; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public DefaultExperimentationService() { } public bool IsExperimentEnabled(string experimentName) => ReturnValue; } internal static class WellKnownExperimentNames { public const string PartialLoadMode = "Roslyn.PartialLoadMode"; public const string TypeImportCompletion = "Roslyn.TypeImportCompletion"; public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter"; public const string TriggerCompletionInArgumentLists = "Roslyn.TriggerCompletionInArgumentLists"; public const string SQLiteInMemoryWriteCache = "Roslyn.SQLiteInMemoryWriteCache"; } }
mit
C#
92498865aa4728074d6cdff2c3b9547d1a345979
update version to 25
ezaurum/dapper
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Dapper Repository")] [assembly: AssemblyDescription("Dapper auto generated repository extension")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ezaurum")] [assembly: AssemblyProduct("dapper extention")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c3a998b9-1a09-4589-9e91-481383acb2ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.25")] [assembly: AssemblyFileVersion("0.0.1.25")] [assembly: NeutralResourcesLanguageAttribute("ko-KR")]
using System.Reflection; using System.Runtime.InteropServices; using System.Resources; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Dapper Repository")] [assembly: AssemblyDescription("Dapper auto generated repository extension")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ezaurum")] [assembly: AssemblyProduct("dapper extention")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c3a998b9-1a09-4589-9e91-481383acb2ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.24")] [assembly: AssemblyFileVersion("0.0.1.24")] [assembly: NeutralResourcesLanguageAttribute("ko-KR")]
mit
C#
d686a84a759e52c3f72b92bcf15d2d4aad9bfcce
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
dparra0007/Autofac.Mvc,jango2015/Autofac.Mvc,autofac/Autofac.Mvc
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Web; using Autofac.Integration.Mvc; [assembly: AssemblyTitle("Autofac.Integration.Mvc")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mvc, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")] [assembly: ComVisible(false)]
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Web; using Autofac.Integration.Mvc; [assembly: AssemblyTitle("Autofac.Integration.Mvc")] [assembly: AssemblyDescription("Autofac ASP.NET MVC 4 Integration")] [assembly: InternalsVisibleTo("Autofac.Tests.Integration.Mvc, PublicKey=00240000048000009400000006020000002400005253413100040000010001008728425885ef385e049261b18878327dfaaf0d666dea3bd2b0e4f18b33929ad4e5fbc9087e7eda3c1291d2de579206d9b4292456abffbe8be6c7060b36da0c33b883e3878eaf7c89fddf29e6e27d24588e81e86f3a22dd7b1a296b5f06fbfb500bbd7410faa7213ef4e2ce7622aefc03169b0324bcd30ccfe9ac8204e4960be6")] [assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")] [assembly: ComVisible(false)]
mit
C#
d3058c5cd2ca1820178e6ac61c7121f1b8f7ecbb
Throw a CommandException if no hostname is specified
appharbor/appharbor-cli
src/AppHarbor/Commands/AddHostnameCommand.cs
src/AppHarbor/Commands/AddHostnameCommand.cs
using System; namespace AppHarbor.Commands { public class AddHostnameCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("No hostname was specified"); } throw new NotImplementedException(); } } }
using System; namespace AppHarbor.Commands { public class AddHostnameCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddHostnameCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
mit
C#
8dd7fa10d7d54d1fa5fbba73ba1679d38e83953e
Fix documentation on IEnumIDENTITY_ATTRIBUTE
CDuke/FusionPInvoke,CDuke/FusionPInvoke
src/FusionPInvoke/IEnumIDENTITY_ATTRIBUTE.cs
src/FusionPInvoke/IEnumIDENTITY_ATTRIBUTE.cs
using System; using System.Runtime.InteropServices; using System.Security; namespace FusionPInvoke { /// <summary> /// Serves as an enumerator for the attributes of the code object in the current scope. /// </summary> [Guid("9cdaae75-246e-4b00-a26d-b9aec137a3eb")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumIDENTITY_ATTRIBUTE { /// <summary> /// Gets the specified number of attributes, starting at the current position. /// </summary> /// <param name="count">Count of items to get.</param> /// <param name="attributes">Readed attributes.</param> /// <returns>Readed attributes count.</returns> /// <remarks>If return value less then <paramref name="count"/>, then no more attributes.</remarks> [SecurityCritical] int Next(int count, [Out, MarshalAs(UnmanagedType.LPArray)] IDENTITY_ATTRIBUTE[] attributes); /// <summary> /// Writes the data contained in the elements of this <see cref="IEnumIDENTITY_ATTRIBUTE"/> to the specified data buffer. /// </summary> /// <param name="available"></param> /// <param name="data"></param> /// <returns></returns> /// <remarks>Use <see cref="Next"/>.</remarks> [SecurityCritical] int CurrentIntoBuffer(int available, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] data); /// <summary> /// Moves the instruction pointer forward by the specified number of elements, starting at the current position. /// </summary> /// <param name="count">Element count to skip.</param> [SecurityCritical] void Skip(int count); /// <summary> /// Moves the instruction pointer to the beginning of this <see cref="IEnumIDENTITY_ATTRIBUTE"/>. /// </summary> [SecurityCritical] void Reset(); /// <summary> /// Gets an interface pointer to a new <see cref="IEnumIDENTITY_ATTRIBUTE"/> that contains the same members as this <see cref="IEnumIDENTITY_ATTRIBUTE"/>. /// </summary> /// <returns><see cref="IEnumIDENTITY_ATTRIBUTE"/> instance.</returns> [SecurityCritical] IEnumIDENTITY_ATTRIBUTE Clone(); } }
using System; using System.Runtime.InteropServices; using System.Security; namespace FusionPInvoke { /// <summary> /// Serves as an enumerator for the attributes of the code object in the current scope. /// </summary> [Guid("9cdaae75-246e-4b00-a26d-b9aec137a3eb")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumIDENTITY_ATTRIBUTE { /// <summary> /// Gets the specified number of attributes, starting at the current position. /// </summary> /// <param name="count">Count of items to get.</param> /// <param name="attributes">Readed attributes.</param> /// <returns><see cref="HRESULT"/>.</returns> [SecurityCritical] int Next(int count, [Out, MarshalAs(UnmanagedType.LPArray)] IDENTITY_ATTRIBUTE[] attributes); /// <summary> /// Writes the data contained in the elements of this <see cref="IEnumIDENTITY_ATTRIBUTE"/> to the specified data buffer. /// </summary> /// <param name="available"></param> /// <param name="data"></param> /// <returns></returns> [SecurityCritical] int CurrentIntoBuffer(int available, [Out, MarshalAs(UnmanagedType.LPArray)] byte[] data); /// <summary> /// Moves the instruction pointer forward by the specified number of elements, starting at the current position. /// </summary> /// <param name="count">Element count to skip.</param> [SecurityCritical] void Skip(int count); /// <summary> /// Moves the instruction pointer to the beginning of this <see cref="IEnumIDENTITY_ATTRIBUTE"/>. /// </summary> [SecurityCritical] void Reset(); /// <summary> /// Gets an interface pointer to a new <see cref="IEnumIDENTITY_ATTRIBUTE"/> that contains the same members as this <see cref="IEnumIDENTITY_ATTRIBUTE"/>. /// </summary> /// <returns></returns> [SecurityCritical] IEnumIDENTITY_ATTRIBUTE Clone(); } }
mit
C#
59e5bd1bc068e5427b3e0ce276a6373761667aad
Clean up LockRecursionException
murador/xsp,stormleoxia/xsp,murador/xsp,arthot/xsp,murador/xsp,murador/xsp,stormleoxia/xsp,stormleoxia/xsp,arthot/xsp,arthot/xsp,stormleoxia/xsp,arthot/xsp
src/Mono.WebServer/LockRecursionException.cs
src/Mono.WebServer/LockRecursionException.cs
/* * System.Threading.LockRecursionException * * Author(s) * Marek Safar <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Runtime.Serialization; namespace System.Threading { [Serializable] class LockRecursionException : Exception { public LockRecursionException () { } public LockRecursionException (string message) : base (message) { } public LockRecursionException (string message, Exception e) : base (message, e) { } protected LockRecursionException (SerializationInfo info, StreamingContext sc) : base (info, sc) { } } }
/* * System.Threading.LockRecursionException * * Author(s) * Marek Safar <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Runtime.Serialization; namespace System.Threading { [Serializable] class LockRecursionException : Exception { public LockRecursionException () : base () { } public LockRecursionException (string message) : base (message) { } public LockRecursionException (string message, Exception e) : base (message, e) { } protected LockRecursionException (SerializationInfo info, StreamingContext sc) : base (info, sc) { } } }
mit
C#
a2a35568873543f83698067b38274c07290b4792
Update JSON.cs
Ryanb58/JSONTool
JSONTool/JSON.cs
JSONTool/JSON.cs
namespace JSONTool { public class JSON { public static string minify(string json) { //Return the json string. return System.Text.RegularExpressions.Regex.Replace(json, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace JSONTool { public class JSON { public string minify(string json) { //This will hold the result of the string. string jsonResult = ""; //int to tell which " or ' you are at. int quotes = 0; //Loops through each character in the json sent. foreach (char c in json) { if (c.ToString() == "\"" || c.ToString() == "\'") { quotes += 1; if (quotes == 2) { quotes = 0; } } //If any white or null spaces are found, remove them. Except in quotes. if (!String.IsNullOrWhiteSpace(c.ToString())) { jsonResult += c.ToString(); } else if (quotes == 1) { jsonResult += c.ToString(); } } //Return the json string. return jsonResult; } } }
mit
C#
4b20c893598bd48e3bdb2a2698dfa8d6bdb1952d
add method to report local time
Liwoj/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,cvent/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,huoxudong125/Metrics.NET
Src/Metrics/Utils/Clock.cs
Src/Metrics/Utils/Clock.cs
 using System; using System.Diagnostics; namespace Metrics.Utils { public abstract class Clock { private sealed class StopwatchClock : Clock { private static readonly long factor = (1000L * 1000L * 1000L) / Stopwatch.Frequency; public override long Nanoseconds { get { return Stopwatch.GetTimestamp() * factor; } } public override DateTime LocalDateTime { get { return DateTime.Now; } } } private sealed class SystemClock : Clock { public override long Nanoseconds { get { return DateTime.UtcNow.Ticks * 100L; } } public override DateTime LocalDateTime { get { return DateTime.Now; } } } public static readonly Clock SystemDateTime = new SystemClock(); public static readonly Clock Default = new StopwatchClock(); public abstract long Nanoseconds { get; } public abstract DateTime LocalDateTime { get; } public long Seconds { get { return TimeUnit.Nanoseconds.ToSeconds(Nanoseconds); } } } }
 using System; namespace Metrics.Utils { public abstract class Clock { private sealed class StopwatchClock : Clock { private static readonly long factor = (1000L * 1000L * 1000L) / System.Diagnostics.Stopwatch.Frequency; public override long Nanoseconds { get { return System.Diagnostics.Stopwatch.GetTimestamp() * factor; } } } private sealed class SystemClock : Clock { public override long Nanoseconds { get { return DateTime.UtcNow.Ticks * 100L; } } } public static readonly Clock SystemDateTime = new SystemClock(); public static readonly Clock Default = new StopwatchClock(); public abstract long Nanoseconds { get; } public long Seconds { get { return TimeUnit.Nanoseconds.ToSeconds(Nanoseconds); } } } }
apache-2.0
C#
4e55f787e26961f81b6bafcbf2d28c66345d6d59
add XML doc to ObjectExtensions
OlegKleyman/Omego.Extensions
core/Omego.Extensions/NullExtensions/SmartGet.cs
core/Omego.Extensions/NullExtensions/SmartGet.cs
namespace Omego.Extensions.NullExtensions { using System; using System.Linq.Expressions; using Poco; /// <summary> /// Contains extension methods for <see cref="object"/>. /// </summary> public static class ObjectExtensions { /// <summary> /// Gets an instance or value specified by <paramref name="result"/> or throws /// an exception if part of the <paramref name="qualifierPath"/> is null. /// </summary> /// <typeparam name="TTarget">The type check qualifying path on.</typeparam> /// <typeparam name="TObject">The final type of the qualifying path to check.</typeparam> /// <typeparam name="TResult">The type to return if nothing is null.</typeparam> /// <param name="target">The target object or value to check qualifying path on.</param> /// <param name="qualifierPath">The qualifying path to check.</param> /// <param name="result">The object or value to retrieve when the qualifying path is not null.</param> /// <param name="exception"> /// The exception to throw when the qualifying path contains null. /// </param> /// <returns>The <typeparamref name="TResult"/>.</returns> /// <exception cref="ArgumentNullException"> /// Occurs when <paramref name="result"/> or <paramref name="exception"/> is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Occurs when <paramref name="exception"/> returns null. /// </exception> public static TResult SmartGet<TTarget, TObject, TResult>( this TTarget target, Expression<Func<TTarget, TObject>> qualifierPath, Func<TObject, TResult> result, Func<string, Exception> exception) { var visitor = new SmartGetVisitor(target); visitor.OnNull( qualifierPath, nullQualifier => { if (exception == null) throw new ArgumentNullException(nameof(exception)); var toThrow = exception(nullQualifier); if (toThrow == null) throw new InvalidOperationException("Exception to throw returned null."); throw exception(nullQualifier); }); if(result == null) throw new ArgumentNullException(nameof(result)); return result((TObject)visitor.Current); } } }
namespace Omego.Extensions.NullExtensions { using System; using System.Linq.Expressions; using Omego.Extensions.Poco; public static class ObjectExtensions { public static TResult SmartGet<TTarget, TOrig, TResult>( this TTarget target, Expression<Func<TTarget, TOrig>> qualifierPath, Func<TOrig, TResult> result, Func<string, Exception> exception) { var visitor = new SmartGetVisitor(target); visitor.OnNull( qualifierPath, nullQualifier => { if (exception == null) throw new ArgumentNullException(nameof(exception)); var toThrow = exception(nullQualifier); if (toThrow == null) throw new InvalidOperationException("Exception to throw returned null."); throw exception(nullQualifier); }); if(result == null) throw new ArgumentNullException(nameof(result)); return result((TOrig)visitor.Current); } } }
unlicense
C#
f993923eeafdef8575e3d5278bdf5f03f3f79b60
Update to Region
malcolmstill/Wayland.NET,malcolmstill/Wayland.NET
Server/Region.cs
Server/Region.cs
using System; using System.Collections.Generic; namespace Wayland.Server { public class WlRect { public enum Operation { ADD, SUBTRACT }; public WlRect(int x, int y, int width, int height, Operation op) { this.x = x; this.y = y; this.width = width; this.height = height; operation = op; } public int x { get; set; } public int y { get; set; } public int width { get; set; } public int height { get; set; } public Operation operation { get; set; } public bool ContainsPoint(int x, int y) { return (x >= this.x && x <= (this.x + this.width) && y >= this.y && y <= (this.y + this.height)); } } }
using System; using System.Collections.Generic; namespace Wayland.Server { public class WlRect { public enum Operation { ADD, SUBTRACT }; public int x { get; set; } public int y { get; set; } public int width { get; set; } public int height { get; set; } public Operation operation { get; set; } public bool ContainsPoint(int x, int y) { return (x >= this.x && x <= (this.x + this.width) && y >= this.y && y <= (this.y + this.height)); } } public class WlRegion { public IntPtr regionPtr { get; set; } public List<WlRect> rects = new List<WlRect>(); } }
bsd-3-clause
C#
768701dc393bf675338a4d7bec3d6c57b639a9c7
Fix non-critical typo in hex constant. (#586)
LtRipley36706/ACE,LtRipley36706/ACE,Lidefeath/ACE,ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE
Source/ACE/Network/PacketHeader.cs
Source/ACE/Network/PacketHeader.cs
using System.IO; using System.Runtime.InteropServices; using ACE.Common.Cryptography; namespace ACE.Network { [StructLayout(LayoutKind.Sequential, Pack = 1)] public class PacketHeader { public static uint HeaderSize { get; } = 20u; public uint Sequence { get; set; } public PacketHeaderFlags Flags { get; set; } public uint Checksum { get; set; } public ushort Id { get; set; } public ushort Time { get; set; } public ushort Size { get; set; } public ushort Table { get; set; } public PacketHeader() { } public PacketHeader(BinaryReader payload) { Sequence = payload.ReadUInt32(); Flags = (PacketHeaderFlags)payload.ReadUInt32(); Checksum = payload.ReadUInt32(); Id = payload.ReadUInt16(); Time = payload.ReadUInt16(); Size = payload.ReadUInt16(); Table = payload.ReadUInt16(); } public byte[] GetRaw() { var headerHandle = GCHandle.Alloc(this, GCHandleType.Pinned); try { byte[] bytes = new byte[Marshal.SizeOf(typeof(PacketHeader))]; Marshal.Copy(headerHandle.AddrOfPinnedObject(), bytes, 0, bytes.Length); return bytes; } finally { headerHandle.Free(); } } public uint CalculateHash32() { uint checksum = 0; uint original = Checksum; Checksum = 0xBADD70DD; byte[] rawHeader = GetRaw(); checksum = Hash32.Calculate(rawHeader, rawHeader.Length); Checksum = original; return checksum; } public bool HasFlag(PacketHeaderFlags flags) { return (flags & Flags) != 0; } } }
using System.IO; using System.Runtime.InteropServices; using ACE.Common.Cryptography; namespace ACE.Network { [StructLayout(LayoutKind.Sequential, Pack = 1)] public class PacketHeader { public static uint HeaderSize { get; } = 20u; public uint Sequence { get; set; } public PacketHeaderFlags Flags { get; set; } public uint Checksum { get; set; } public ushort Id { get; set; } public ushort Time { get; set; } public ushort Size { get; set; } public ushort Table { get; set; } public PacketHeader() { } public PacketHeader(BinaryReader payload) { Sequence = payload.ReadUInt32(); Flags = (PacketHeaderFlags)payload.ReadUInt32(); Checksum = payload.ReadUInt32(); Id = payload.ReadUInt16(); Time = payload.ReadUInt16(); Size = payload.ReadUInt16(); Table = payload.ReadUInt16(); } public byte[] GetRaw() { var headerHandle = GCHandle.Alloc(this, GCHandleType.Pinned); try { byte[] bytes = new byte[Marshal.SizeOf(typeof(PacketHeader))]; Marshal.Copy(headerHandle.AddrOfPinnedObject(), bytes, 0, bytes.Length); return bytes; } finally { headerHandle.Free(); } } public uint CalculateHash32() { uint checksum = 0; uint original = Checksum; Checksum = 0x0BADD70DD; byte[] rawHeader = GetRaw(); checksum = Hash32.Calculate(rawHeader, rawHeader.Length); Checksum = original; return checksum; } public bool HasFlag(PacketHeaderFlags flags) { return (flags & Flags) != 0; } } }
agpl-3.0
C#
10e0479268d3f0c5367fb5c2f471aa4b76f3997c
add gui labels for counts
vankovilija/everyoneisafriend,vankovilija/everyoneisafriend,vankovilija/everyoneisafriend
Assets/Scripts/GameSetup.cs
Assets/Scripts/GameSetup.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameSetup : MonoBehaviour { public static List<GameObject> happyFriends = new List<GameObject>(); public static List<GameObject> angryFriends = new List<GameObject>(); public int lifesLost = 0; private Camera mainCam; void Start () { GameObject.FindGameObjectWithTag (PlayerControl.PLAYER_TAG).GetComponent<Health>().OnDeath += PlayerDeathHandler; FriendScript[] friends = GameObject.FindObjectsOfType<FriendScript> (); for(int i = 0; i < friends.Length; i++){ friends[i].ChangeState += onFriendStateChange; onFriendStateChange(friends[i].gameObject, friends[i].state); } } void OnGUI(){ GUI.Label (new Rect (10, 10, 200, 50), "Happy friends: " + happyFriends.Count); GUI.Label (new Rect (10, 22, 200, 50), "Lifes lost: " + lifesLost); } void PlayerDeathHandler(){ lifesLost ++; Debug.Log ("Lifes lost: " + lifesLost); } void onFriendStateChange(GameObject friend, FriendState state){ if (state == FriendState.happy) { if(happyFriends.IndexOf(friend) == -1) happyFriends.Add(friend); angryFriends.Remove(friend); } else if (state == FriendState.angry || state == FriendState.veryAngry) { if(angryFriends.IndexOf(friend) == -1) angryFriends.Add(friend); happyFriends.Remove(friend); } Debug.Log ("happy friends: " + happyFriends.Count + " angry friends: " + angryFriends.Count); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameSetup : MonoBehaviour { public static List<GameObject> happyFriends = new List<GameObject>(); public static List<GameObject> angryFriends = new List<GameObject>(); public int lifesLost = 0; private Camera mainCam; void Start () { GameObject.FindGameObjectWithTag (PlayerControl.PLAYER_TAG).GetComponent<Health>().OnDeath += PlayerDeathHandler; FriendScript[] friends = GameObject.FindObjectsOfType<FriendScript> (); for(int i = 0; i < friends.Length; i++){ friends[i].ChangeState += onFriendStateChange; onFriendStateChange(friends[i].gameObject, friends[i].state); } } void PlayerDeathHandler(){ lifesLost ++; Debug.Log ("Lifes lost: " + lifesLost); } void onFriendStateChange(GameObject friend, FriendState state){ if (state == FriendState.happy) { if(happyFriends.IndexOf(friend) == -1) happyFriends.Add(friend); angryFriends.Remove(friend); } else if (state == FriendState.angry || state == FriendState.veryAngry) { if(angryFriends.IndexOf(friend) == -1) angryFriends.Add(friend); happyFriends.Remove(friend); } Debug.Log ("happy friends: " + happyFriends.Count + " angry friends: " + angryFriends.Count); } }
mit
C#
727517baa7f26a04355abbdc0c2a0fe1f75b1385
Move sound to mouth open
renaudbedard/cooldog-assistant
Assets/Scripts/TextTyper.cs
Assets/Scripts/TextTyper.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; [System.Serializable] public class DialoguePart { public string Line; public float speed = 1.5f; public DialoguePart(string line, float speed) { this.Line = line; this.speed = speed; } } public class TextTyper : MonoBehaviour { [SerializeField] Text dialogueBox; [SerializeField] GameObject hideAlso; [SerializeField] AudioClip[] coolBark; Cooldog cooldog; float speed; AudioSource talkingSpeaker; public bool typing = false; string targetText = ""; public bool busy = false; // Use this for initialization void Start () { dialogueBox.enabled = false; hideAlso.SetActive(false); busy = false; talkingSpeaker = GetComponent<AudioSource> (); cooldog = GetComponent<Cooldog>(); talkingSpeaker.clip = coolBark[Random.Range(0, coolBark.Length)]; talkingSpeaker.Play(); } public void Play(List<DialoguePart> parts) { busy = true; StartCoroutine(PlayInternal(parts)); } IEnumerator PlayInternal(List<DialoguePart> parts) { foreach (DialoguePart part in parts) { targetText = part.Line; speed = part.speed; dialogueBox.text = ""; dialogueBox.enabled = true; hideAlso.SetActive(true); foreach (char letter in targetText.ToCharArray()) { if (targetText == "") { break; } dialogueBox.text += letter; if (letter == ' ' || letter == '0') { cooldog.CloseMouth(); } if (".aeiou?!1".Contains(letter.ToString())) { talkingSpeaker.clip = coolBark[Random.Range(0, coolBark.Length)]; talkingSpeaker.Play(); cooldog.OpenMouth(); } yield return new WaitForSeconds(speed / (float)targetText.Length); } cooldog.CloseMouth(); yield return new WaitForSeconds(0.5f); } busy = false; Hide(); } public void Hide() { dialogueBox.enabled = false; hideAlso.SetActive(false); dialogueBox.text = ""; targetText = ""; typing = false; StopCoroutine("PlayInternal"); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; [System.Serializable] public class DialoguePart { public string Line; public float speed = 1.5f; public DialoguePart(string line, float speed) { this.Line = line; this.speed = speed; } } public class TextTyper : MonoBehaviour { [SerializeField] Text dialogueBox; [SerializeField] GameObject hideAlso; [SerializeField] AudioClip[] coolBark; Cooldog cooldog; float speed; AudioSource talkingSpeaker; public bool typing = false; string targetText = ""; public bool busy = false; // Use this for initialization void Start () { dialogueBox.enabled = false; hideAlso.SetActive(false); busy = false; talkingSpeaker = GetComponent<AudioSource> (); cooldog = GetComponent<Cooldog>(); talkingSpeaker.clip = coolBark[Random.Range(0, coolBark.Length)]; talkingSpeaker.Play(); } public void Play(List<DialoguePart> parts) { busy = true; StartCoroutine(PlayInternal(parts)); } IEnumerator PlayInternal(List<DialoguePart> parts) { foreach (DialoguePart part in parts) { targetText = part.Line; speed = part.speed; dialogueBox.text = ""; dialogueBox.enabled = true; hideAlso.SetActive(true); foreach (char letter in targetText.ToCharArray()) { if (targetText == "") { break; } dialogueBox.text += letter; if (letter == ' ' || letter == '0') { talkingSpeaker.clip = coolBark[Random.Range(0, coolBark.Length)]; talkingSpeaker.Play(); cooldog.CloseMouth(); } if (".aeiou?!1".Contains(letter.ToString())) { cooldog.OpenMouth(); } yield return new WaitForSeconds(speed / (float)targetText.Length); } cooldog.CloseMouth(); yield return new WaitForSeconds(0.5f); } busy = false; Hide(); } public void Hide() { dialogueBox.enabled = false; hideAlso.SetActive(false); dialogueBox.text = ""; targetText = ""; typing = false; StopCoroutine("PlayInternal"); } }
mit
C#
836953370d0468c8f38a1d0281650a78682edc6b
Remove unused IoC resolve from SharedCombatModeComponent.cs
space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Shared/GameObjects/Components/Mobs/SharedCombatModeComponent.cs
Content.Shared/GameObjects/Components/Mobs/SharedCombatModeComponent.cs
using System; using Robust.Shared.GameObjects; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; namespace Content.Shared.GameObjects.Components.Mobs { public abstract class SharedCombatModeComponent : Component { public sealed override uint? NetID => ContentNetIDs.COMBATMODE; public override string Name => "CombatMode"; private bool _isInCombatMode; private TargetingZone _activeZone; [ViewVariables(VVAccess.ReadWrite)] public virtual bool IsInCombatMode { get => _isInCombatMode; set { _isInCombatMode = value; Dirty(); } } [ViewVariables(VVAccess.ReadWrite)] public virtual TargetingZone ActiveZone { get => _activeZone; set { _activeZone = value; Dirty(); } } public override void HandleComponentState(ComponentState curState, ComponentState nextState) { base.HandleComponentState(curState, nextState); if (!(curState is CombatModeComponentState state)) return; IsInCombatMode = state.IsInCombatMode; ActiveZone = state.TargetingZone; } public override ComponentState GetComponentState() { return new CombatModeComponentState(IsInCombatMode, ActiveZone); } [Serializable, NetSerializable] protected sealed class CombatModeComponentState : ComponentState { public bool IsInCombatMode { get; } public TargetingZone TargetingZone { get; } public CombatModeComponentState(bool isInCombatMode, TargetingZone targetingZone) : base(ContentNetIDs.COMBATMODE) { IsInCombatMode = isInCombatMode; TargetingZone = targetingZone; } } } }
using System; using Robust.Shared.GameObjects; using Robust.Shared.Interfaces.Timing; using Robust.Shared.IoC; using Robust.Shared.Serialization; using Robust.Shared.ViewVariables; namespace Content.Shared.GameObjects.Components.Mobs { public abstract class SharedCombatModeComponent : Component { public sealed override uint? NetID => ContentNetIDs.COMBATMODE; public override string Name => "CombatMode"; private bool _isInCombatMode; private TargetingZone _activeZone; [ViewVariables(VVAccess.ReadWrite)] public virtual bool IsInCombatMode { get => _isInCombatMode; set { var gt = IoCManager.Resolve<IGameTiming>(); _isInCombatMode = value; Dirty(); } } [ViewVariables(VVAccess.ReadWrite)] public virtual TargetingZone ActiveZone { get => _activeZone; set { _activeZone = value; Dirty(); } } public override void HandleComponentState(ComponentState curState, ComponentState nextState) { base.HandleComponentState(curState, nextState); if (!(curState is CombatModeComponentState state)) return; IsInCombatMode = state.IsInCombatMode; ActiveZone = state.TargetingZone; } public override ComponentState GetComponentState() { return new CombatModeComponentState(IsInCombatMode, ActiveZone); } [Serializable, NetSerializable] protected sealed class CombatModeComponentState : ComponentState { public bool IsInCombatMode { get; } public TargetingZone TargetingZone { get; } public CombatModeComponentState(bool isInCombatMode, TargetingZone targetingZone) : base(ContentNetIDs.COMBATMODE) { IsInCombatMode = isInCombatMode; TargetingZone = targetingZone; } } } }
mit
C#
80acafc132366fd6a7b5674f07913e314bfe3e33
Fix wrong column name.
crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin
SignInCheckIn/MinistryPlatform.Translation/Repositories/ChildCheckinRepository.cs
SignInCheckIn/MinistryPlatform.Translation/Repositories/ChildCheckinRepository.cs
using System.Collections.Generic; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories.Interfaces; using Crossroads.Utilities.Services.Interfaces; namespace MinistryPlatform.Translation.Repositories { public class ChildCheckinRepository : IChildCheckinRepository { private readonly IApiUserRepository _apiUserRepository; private readonly IMinistryPlatformRestRepository _ministryPlatformRestRepository; private readonly IApplicationConfiguration _applicationConfiguration; public ChildCheckinRepository(IApiUserRepository apiUserRepository, IMinistryPlatformRestRepository ministryPlatformRestRepository, IApplicationConfiguration applicationConfiguration) { _apiUserRepository = apiUserRepository; _ministryPlatformRestRepository = ministryPlatformRestRepository; _applicationConfiguration = applicationConfiguration; } public List<MpParticipantDto> GetChildrenByEventAndRoom(int eventId, int roomId) { var apiUserToken = _apiUserRepository.GetToken(); var columnList = new List<string> { "Event_ID_Table.Event_ID", "Room_ID_Table.Room_ID", "Event_Participants.Event_Participant_ID", "Participant_ID_Table.Participant_ID", "Participant_ID_Table_Contact_ID_Table.Contact_ID", "Participant_ID_Table_Contact_ID_Table.First_Name", "Participant_ID_Table_Contact_ID_Table.Last_Name", "Participation_Status_ID_Table.Participation_Status_ID" }; return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken). SearchTable<MpParticipantDto>("Event_Participants", $"Event_ID_Table.[Event_ID] = {eventId} AND Room_ID_Table.[Room_ID] = {roomId}", columnList); } public void CheckinChildrenForCurrentEventAndRoom(bool checkIn, int eventParticipantId) { var apiUserToken = _apiUserRepository.GetToken(); var checkinStatusId = checkIn ? _applicationConfiguration.CheckedInParticipationStatusId : _applicationConfiguration.SignedInParticipationStatusId; var updateObject = new Dictionary<string, object> { { "Participation_Status_ID_Table.Participation_Status_ID", checkinStatusId } }; _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken).UpdateRecord("Event_Participants", eventParticipantId, updateObject); } } }
using System.Collections.Generic; using MinistryPlatform.Translation.Models.DTO; using MinistryPlatform.Translation.Repositories.Interfaces; using Crossroads.Utilities.Services.Interfaces; namespace MinistryPlatform.Translation.Repositories { public class ChildCheckinRepository : IChildCheckinRepository { private readonly IApiUserRepository _apiUserRepository; private readonly IMinistryPlatformRestRepository _ministryPlatformRestRepository; private readonly IApplicationConfiguration _applicationConfiguration; public ChildCheckinRepository(IApiUserRepository apiUserRepository, IMinistryPlatformRestRepository ministryPlatformRestRepository, IApplicationConfiguration applicationConfiguration) { _apiUserRepository = apiUserRepository; _ministryPlatformRestRepository = ministryPlatformRestRepository; _applicationConfiguration = applicationConfiguration; } public List<MpParticipantDto> GetChildrenByEventAndRoom(int eventId, int roomId) { var apiUserToken = _apiUserRepository.GetToken(); var columnList = new List<string> { "Event_ID_Table.Event_ID", "Room_ID_Table.Room_ID_Table", "Event_Participants.Event_Participant_ID", "Participant_ID_Table.Participant_ID", "Participant_ID_Table_Contact_ID_Table.Contact_ID", "Participant_ID_Table_Contact_ID_Table.First_Name", "Participant_ID_Table_Contact_ID_Table.Last_Name", "Participation_Status_ID_Table.Participation_Status_ID" }; return _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken). SearchTable<MpParticipantDto>("Event_Participants", $"Event_ID_Table.[Event_ID] = {eventId} AND Room_ID_Table.[Room_ID] = {roomId}", columnList); } public void CheckinChildrenForCurrentEventAndRoom(bool checkIn, int eventParticipantId) { var apiUserToken = _apiUserRepository.GetToken(); var checkinStatusId = checkIn ? _applicationConfiguration.CheckedInParticipationStatusId : _applicationConfiguration.SignedInParticipationStatusId; var updateObject = new Dictionary<string, object> { { "Participation_Status_ID_Table.Participation_Status_ID", checkinStatusId } }; _ministryPlatformRestRepository.UsingAuthenticationToken(apiUserToken).UpdateRecord("Event_Participants", eventParticipantId, updateObject); } } }
bsd-2-clause
C#
ab0ca13dcdad5fa1f4783fa37efbe043ef8fcd6d
fix NullReferenceException in ClickedItem
tibel/Caliburn.Light
samples/Demo.HelloSpecialValues/ClickedItem.cs
samples/Demo.HelloSpecialValues/ClickedItem.cs
using Caliburn.Light; using Windows.UI.Xaml.Controls; namespace Demo.HelloSpecialValues { public class ClickedItem : ISpecialValue { public object Resolve(CoroutineExecutionContext context) { var args = context.EventArgs as ItemClickEventArgs; return (args != null) ? args.ClickedItem : null; } } }
using Caliburn.Light; using Windows.UI.Xaml.Controls; namespace Demo.HelloSpecialValues { public class ClickedItem : ISpecialValue { public object Resolve(CoroutineExecutionContext context) { return ((ItemClickEventArgs)context.EventArgs).ClickedItem; } } }
mit
C#
0212051ba6ad28ec2bd17ce9cc7a5c297a5c204e
update json constructor
DynamoDS/DynamoSamples
src/SampleLibraryUI/Examples/DropDown.cs
src/SampleLibraryUI/Examples/DropDown.cs
using System.Collections.Generic; using CoreNodeModels; using Dynamo.Graph.Nodes; using Dynamo.Utilities; using ProtoCore.AST.AssociativeAST; using Newtonsoft.Json; namespace SampleLibraryUI.Examples { [NodeName("Drop Down Example")] [NodeDescription("An example drop down node.")] [IsDesignScriptCompatible] public class DropDownExample : DSDropDownBase { public DropDownExample() : base("item"){} // Starting with Dynamo v2.0 you must add Json constructors for all nodeModel // dervived nodes to support the move from an Xml to Json file format. Failing to // do so will result in incorrect ports being generated upon serialization/deserialization. // This constructor is called when opening a Json graph. We must also pass the deserialized // ports with the json constructor and then call the base class passing the ports as parameters. [JsonConstructor] public DropDownExample(IEnumerable<PortModel> inPorts, IEnumerable<PortModel> outPorts) : base("item", inPorts, outPorts) { } protected override SelectionState PopulateItemsCore(string currentSelection) { // The Items collection contains the elements // that appear in the list. For this example, we // clear the list before adding new items, but you // can also use the PopulateItems method to add items // to the list. Items.Clear(); // Create a number of DynamoDropDownItem objects // to store the items that we want to appear in our list. var newItems = new List<DynamoDropDownItem>() { new DynamoDropDownItem("Tywin", 0), new DynamoDropDownItem("Cersei", 1), new DynamoDropDownItem("Hodor",2) }; Items.AddRange(newItems); // Set the selected index to something other // than -1, the default, so that your list // has a pre-selection. SelectedIndex = 0; return SelectionState.Done; } public override IEnumerable<AssociativeNode> BuildOutputAst(List<AssociativeNode> inputAstNodes) { // Build an AST node for the type of object contained in your Items collection. var intNode = AstFactory.BuildIntNode((int)Items[SelectedIndex].Item); var assign = AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), intNode); return new List<AssociativeNode> {assign}; } } }
using System.Collections.Generic; using CoreNodeModels; using Dynamo.Graph.Nodes; using Dynamo.Utilities; using ProtoCore.AST.AssociativeAST; using Newtonsoft.Json; namespace SampleLibraryUI.Examples { [NodeName("Drop Down Example")] [NodeDescription("An example drop down node.")] [IsDesignScriptCompatible] public class DropDownExample : DSDropDownBase { public DropDownExample() : base("item"){} [JsonConstructor] public DropDownExample(IEnumerable<PortModel> inPorts, IEnumerable<PortModel> outPorts) : base("item") { } protected override SelectionState PopulateItemsCore(string currentSelection) { // The Items collection contains the elements // that appear in the list. For this example, we // clear the list before adding new items, but you // can also use the PopulateItems method to add items // to the list. Items.Clear(); // Create a number of DynamoDropDownItem objects // to store the items that we want to appear in our list. var newItems = new List<DynamoDropDownItem>() { new DynamoDropDownItem("Tywin", 0), new DynamoDropDownItem("Cersei", 1), new DynamoDropDownItem("Hodor",2) }; Items.AddRange(newItems); // Set the selected index to something other // than -1, the default, so that your list // has a pre-selection. SelectedIndex = 0; return SelectionState.Done; } public override IEnumerable<AssociativeNode> BuildOutputAst(List<AssociativeNode> inputAstNodes) { // Build an AST node for the type of object contained in your Items collection. var intNode = AstFactory.BuildIntNode((int)Items[SelectedIndex].Item); var assign = AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), intNode); return new List<AssociativeNode> {assign}; } } }
mit
C#
85462c97fabd0f48d6314c79ae3a543816b4b870
Add StatusCode to options
mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype
src/Glimpse.Agent.Web/GlimpseAgentWebOptions.cs
src/Glimpse.Agent.Web/GlimpseAgentWebOptions.cs
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Glimpse.Agent.Web.Options; namespace Glimpse.Agent.Web { public class GlimpseAgentWebOptions { public GlimpseAgentWebOptions() { IgnoredUris = new List<IgnoredUrisDescriptor>(); StatusCodes = new List<IgnoredStatusCodeDescriptor>(); } public IList<IgnoredUrisDescriptor> IgnoredUris { get; } public IList<IgnoredStatusCodeDescriptor> StatusCodes { get; } } }
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Glimpse.Agent.Web.Options; namespace Glimpse.Agent.Web { public class GlimpseAgentWebOptions { public GlimpseAgentWebOptions() { IgnoredUris = new List<IgnoredUrisDescriptor>(); StatusCodes = new List<IgnoredUrisDescriptor>(); } public IList<IgnoredUrisDescriptor> IgnoredUris { get; } public IList<IgnoredUrisDescriptor> StatusCodes { get; } } }
mit
C#
b04858eacd129abdcbc4739a1215b1e19b6ed4a6
update header
AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,bjartebore/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet
src/ADAL.PCL.Desktop/UserPasswordCredential.cs
src/ADAL.PCL.Desktop/UserPasswordCredential.cs
//---------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ namespace Microsoft.IdentityModel.Clients.ActiveDirectory { /// <summary> /// Credential used for username/password authentication. /// </summary> public sealed class UserPasswordCredential : UserCredential { /// <summary> /// Constructor to create credential with client id and secret /// </summary> /// <param name="userName">Identifier of the user application requests token on behalf.</param> /// <param name="password">User password.</param> public UserPasswordCredential(string userName, string password):base(userName, UserAuthType.UsernamePassword) { this.Password = password; } internal string Password { get; private set; } internal override char[] PasswordToCharArray() { return (this.Password != null) ? this.Password.ToCharArray() : null; } internal char[] EscapedPasswordToCharArray() { string password = this.Password; password = password.Replace("&", "&amp;"); password = password.Replace("\"", "&quot;"); password = password.Replace("'", "&apos;"); password = password.Replace("<", "&lt;"); password = password.Replace(">", "&gt;"); return (password != null) ? password.ToCharArray() : null; } internal override void ApplyTo(DictionaryRequestParameters requestParameters) { requestParameters[OAuthParameter.GrantType] = OAuthGrantType.Password; requestParameters[OAuthParameter.Username] = this.UserName; requestParameters[OAuthParameter.Password] = this.Password; } } }
//---------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //---------------------------------------------------------------------- namespace Microsoft.IdentityModel.Clients.ActiveDirectory { /// <summary> /// Credential used for username/password authentication. /// </summary> public sealed class UserPasswordCredential : UserCredential { /// <summary> /// Constructor to create credential with client id and secret /// </summary> /// <param name="userName">Identifier of the user application requests token on behalf.</param> /// <param name="password">User password.</param> public UserPasswordCredential(string userName, string password):base(userName, UserAuthType.UsernamePassword) { this.Password = password; } internal string Password { get; private set; } internal override char[] PasswordToCharArray() { return (this.Password != null) ? this.Password.ToCharArray() : null; } internal char[] EscapedPasswordToCharArray() { string password = this.Password; password = password.Replace("&", "&amp;"); password = password.Replace("\"", "&quot;"); password = password.Replace("'", "&apos;"); password = password.Replace("<", "&lt;"); password = password.Replace(">", "&gt;"); return (password != null) ? password.ToCharArray() : null; } internal override void ApplyTo(DictionaryRequestParameters requestParameters) { requestParameters[OAuthParameter.GrantType] = OAuthGrantType.Password; requestParameters[OAuthParameter.Username] = this.UserName; requestParameters[OAuthParameter.Password] = this.Password; } } }
mit
C#
bd836472419fefc0416a06bdbdd9eaabde86b7b9
add of program area
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } public DateTime date_last_indexed { get; set; } public string act_cfr { get; set; } public string program_area { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } public DateTime date_last_indexed { get; set; } public string act_cfr { get; set; } } }
apache-2.0
C#
f09a4e9c5b0e5507d9d3a22b92682a2190030832
Fix potential crash in tests when attempting to lookup key bindings in cases the lookup is not available
peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu
osu.Game/Configuration/DevelopmentOsuConfigManager.cs
osu.Game/Configuration/DevelopmentOsuConfigManager.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { LookupKeyBindings = _ => "unknown"; LookupSkinName = _ => "unknown"; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Configuration { [ExcludeFromDynamicCompile] public class DevelopmentOsuConfigManager : OsuConfigManager { protected override string Filename => base.Filename.Replace(".ini", ".dev.ini"); public DevelopmentOsuConfigManager(Storage storage) : base(storage) { } } }
mit
C#
004dbf70c07fd2e1a8f801ef3950a77a464e55a2
Update AspNetExtensions.cs
NLog/NLog.Framework.Logging,NLog/NLog.Framework.Logging,NLog/NLog.Extensions.Logging
src/NLog.Framework.logging/AspNetExtensions.cs
src/NLog.Framework.logging/AspNetExtensions.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.PlatformAbstractions; using NLog.Config; namespace NLog.Framework.Logging { /// <summary> /// Helpers for ASP.NET /// </summary> public static class AspNetExtensions { /// <summary> /// Enable NLog /// </summary> /// <param name="factory"></param> /// <returns></returns> public static ILoggerFactory AddNLog(this ILoggerFactory factory) { //ignore this LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly); using (var provider = new NLogLoggerProvider()) { factory.AddProvider(provider); } return factory; } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IHostingEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(Directory.GetParent(env.WebRootPath).FullName, configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IApplicationEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(env.ApplicationBasePath, configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="fileName">absolute path NLog configuration file.</param> private static void ConfigureNLog(string fileName) { LogManager.Configuration = new XmlLoggingConfiguration(fileName, true); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.PlatformAbstractions; using NLog.Config; namespace NLog.Framework.Logging { /// <summary> /// Helpers for ASP.NET /// </summary> public static class AspNetExtensions { /// <summary> /// Enable NLog /// </summary> /// <param name="factory"></param> /// <returns></returns> public static ILoggerFactory AddNLog(this ILoggerFactory factory) { //ignore this LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly); var provider = new NLogLoggerProvider(); factory.AddProvider(provider); return factory; } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IHostingEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(Directory.GetParent(env.WebRootPath).ToString(), configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IApplicationEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(env.ApplicationBasePath, configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="fileName">absolute path NLog configuration file.</param> private static void ConfigureNLog(string fileName) { LogManager.Configuration = new XmlLoggingConfiguration(fileName, true); } } }
bsd-2-clause
C#
f21ef89ce2124bdb755106bc03c0bd44d2ecf6de
Allow overwriting code files on update (#350)
tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools
src/dotnet/APIView/APIViewWeb/Repositories/BlobCodeFileRepository.cs
src/dotnet/APIView/APIViewWeb/Repositories/BlobCodeFileRepository.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Threading.Tasks; using ApiView; using Azure.Storage.Blobs; using Microsoft.Extensions.Configuration; namespace APIViewWeb { public class BlobCodeFileRepository { private BlobContainerClient _container; public BlobCodeFileRepository(IConfiguration configuration) { var connectionString = configuration["Blob:ConnectionString"]; _container = new BlobContainerClient(connectionString, "codefiles"); } public Task<CodeFile> GetCodeFileAsync(ReviewRevisionModel revision) { return GetCodeFileAsync(revision.RevisionId, revision.SingleFile.ReviewFileId); } public async Task<CodeFile> GetCodeFileAsync(string revisionId, string codeFileId) { var info = await GetBlobClient(revisionId,codeFileId).DownloadAsync(); return await CodeFile.DeserializeAsync(info.Value.Content); } private BlobClient GetBlobClient(string revisionId, string codeFileId) { if (revisionId == codeFileId) { return _container.GetBlobClient(codeFileId); } else { return _container.GetBlobClient(revisionId + "/" + codeFileId); } } public async Task UpsertCodeFileAsync(string revisionId, string codeFileId, CodeFile codeFile) { var memoryStream = new MemoryStream(); await codeFile.SerializeAsync(memoryStream); memoryStream.Position = 0; await GetBlobClient(revisionId, codeFileId).UploadAsync(memoryStream, overwrite: true); } public async Task DeleteCodeFileAsync(string revisionId, string codeFileId) { await GetBlobClient(revisionId, codeFileId).DeleteAsync(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Threading.Tasks; using ApiView; using Azure.Storage.Blobs; using Microsoft.Extensions.Configuration; namespace APIViewWeb { public class BlobCodeFileRepository { private BlobContainerClient _container; public BlobCodeFileRepository(IConfiguration configuration) { var connectionString = configuration["Blob:ConnectionString"]; _container = new BlobContainerClient(connectionString, "codefiles"); } public Task<CodeFile> GetCodeFileAsync(ReviewRevisionModel revision) { return GetCodeFileAsync(revision.RevisionId, revision.SingleFile.ReviewFileId); } public async Task<CodeFile> GetCodeFileAsync(string revisionId, string codeFileId) { var info = await GetBlobClient(revisionId,codeFileId).DownloadAsync(); return await CodeFile.DeserializeAsync(info.Value.Content); } private BlobClient GetBlobClient(string revisionId, string codeFileId) { if (revisionId == codeFileId) { return _container.GetBlobClient(codeFileId); } else { return _container.GetBlobClient(revisionId + "/" + codeFileId); } } public async Task UpsertCodeFileAsync(string revisionId, string codeFileId, CodeFile codeFile) { var memoryStream = new MemoryStream(); await codeFile.SerializeAsync(memoryStream); memoryStream.Position = 0; await GetBlobClient(revisionId, codeFileId).UploadAsync(memoryStream); } public async Task DeleteCodeFileAsync(string revisionId, string codeFileId) { await GetBlobClient(revisionId, codeFileId).DeleteAsync(); } } }
mit
C#
5a2adee0446a788335d4d74e232998d4c084792a
change converters to use dark Mode variable
takenet/lime-csharp
src/Lime.Client.TestConsole/Converters/DataOperationToBrushConverter.cs
src/Lime.Client.TestConsole/Converters/DataOperationToBrushConverter.cs
using Lime.Protocol.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Media; namespace Lime.Client.TestConsole.Converters { public class DataOperationToBrushConverter : IMultiValueConverter { private readonly SolidColorBrush LightDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#424242")); private readonly SolidColorBrush NormalDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#212121")); #region IValueConverter Members public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var direction = values[0]; var darkMode = values[1]; if (direction is DataOperation && ((DataOperation)direction) == DataOperation.Receive) { if (darkMode is Style) { return NormalDarkMode; } return new SolidColorBrush(Colors.LightGray); } if (darkMode is Style) { return LightDarkMode; } return new SolidColorBrush(Colors.White); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
using Lime.Protocol.Network; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using System.Windows.Media; namespace Lime.Client.TestConsole.Converters { public class DataOperationToBrushConverter : IMultiValueConverter { private readonly SolidColorBrush LightDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#424242")); private readonly SolidColorBrush NormalDarkMode = (SolidColorBrush)(new BrushConverter().ConvertFrom("#212121")); #region IValueConverter Members public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var direction = values[0]; var darkMode = values[1]; if (direction is DataOperation && ((DataOperation)direction) == DataOperation.Receive) { if (values[1] is Style) { return NormalDarkMode; } return new SolidColorBrush(Colors.LightGray); } if (darkMode is Style) { return LightDarkMode; } return new SolidColorBrush(Colors.White); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
apache-2.0
C#
dd14a1b3ce0b6177af47c12e4fd5e9c59ff37075
Support reference types
jjnguy/LRU.Net
LRU.Net/LRU.Net/LruCache.cs
LRU.Net/LRU.Net/LruCache.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LRU.Net { public class LruCache<TKey, TValue> { private readonly int _maxObjects; private OrderedDictionary _data; public LruCache(int maxObjects = 1000) { _maxObjects = maxObjects; _data = new OrderedDictionary(); } public void Add(TKey key, TValue value) { if (_data.Count >= _maxObjects) { _data.RemoveAt(0); } _data.Add(key, value); } public TValue Get(TKey key) { if (!_data.Contains(key)) throw new Exception(); var result = _data[key]; if (result == null) throw new Exception(); _data.Remove(key); _data.Add(key, result); return (TValue)result; } public bool Contains(TKey key) { return _data.Contains(key); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LRU.Net { public class LruCache<TKey, TValue> where TValue : class { private readonly int _maxObjects; private OrderedDictionary _data; public LruCache(int maxObjects = 1000) { _maxObjects = maxObjects; _data = new OrderedDictionary(); } public void Add(TKey key, TValue value) { if (_data.Count >= _maxObjects) { _data.RemoveAt(0); } _data.Add(key, value); } public TValue Get(TKey key) { if (!_data.Contains(key)) throw new Exception(); var result = _data[key]; if (result == null) throw new Exception(); _data.Remove(key); _data.Add(key, result); return (TValue)result; } public bool Contains(TKey key) { return _data.Contains(key); } } }
mit
C#
b2059f29b97037e509186cc378297890d60327d4
Fix for wrong keys when using python binding
zebraxxl/Winium.Desktop,2gis/Winium.Desktop,jorik041/Winium.Desktop
src/Winium.Desktop.Driver/CommandExecutors/SendKeysToElementExecutor.cs
src/Winium.Desktop.Driver/CommandExecutors/SendKeysToElementExecutor.cs
namespace Winium.Desktop.Driver.CommandExecutors { internal class SendKeysToElementExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var text = string.Join(string.Empty, this.ExecutedCommand.Parameters["value"]); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); element.SetText(text); return this.JsonResponse(); } #endregion } }
namespace Winium.Desktop.Driver.CommandExecutors { internal class SendKeysToElementExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var text = this.ExecutedCommand.Parameters["value"].First.ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); element.SetText(text); return this.JsonResponse(); } #endregion } }
mpl-2.0
C#
0efd1c78210b41dbe7294998ed1d817b652e857f
Clean up build script
robertcoltheart/Conductor,robertcoltheart/Conductor
build.cake
build.cake
#tool "nuget:?package=GitVersion.CommandLine&version=3.6.1" #tool "nuget:?package=NUnit.ConsoleRunner&version=3.4.1" ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var nugetApiKey = Argument("nugetapikey", EnvironmentVariable("NUGET_API_KEY")); ////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES ////////////////////////////////////////////////////////////////////// var version = "1.0.0"; var artifacts = Directory("./artifacts"); var solution = File("./src/Conductor.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories("./src/**/bin"); CleanDirectories("./src/**/obj"); if (DirectoryExists(artifacts)) DeleteDirectory(artifacts, true); }); Task("Restore") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Versioning") .IsDependentOn("Clean") .WithCriteria(() => !BuildSystem.IsLocalBuild) .Does(() => { GitVersion(new GitVersionSettings { OutputType = GitVersionOutput.BuildServer }); var result = GitVersion(new GitVersionSettings { UpdateAssemblyInfo = true }); version = result.NuGetVersion; }); Task("Build") .IsDependentOn("Versioning") .IsDependentOn("Restore") .Does(() => { CreateDirectory(artifacts); DotNetBuild(solution, x => { x.SetConfiguration("Release"); x.WithProperty("GenerateDocumentation", "true"); }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var testResults = artifacts + File("TestResults.xml"); NUnit3("./src/**/bin/**/Release/*.Tests.dll", new NUnit3Settings { Results = testResults }); if (BuildSystem.IsRunningOnAppVeyor) AppVeyor.UploadTestResults(testResults, AppVeyorTestResultsType.NUnit3); }); Task("Package") .IsDependentOn("Build") .IsDependentOn("Test") .Does(() => { NuGetPack("./build/Conductor.nuspec", new NuGetPackSettings { Version = version, BasePath = "./src", OutputDirectory = artifacts }); }); Task("Publish") .IsDependentOn("Package") .Does(() => { var package = "./artifacts/Conductor." + version + ".nupkg"; NuGetPush(package, new NuGetPushSettings { ApiKey = nugetApiKey }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Package"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
#addin "nuget:?package=Cake.DocFx&version=0.1.6" #addin "nuget:?package=Cake.ReSharperReports&version=0.3.1" #tool "nuget:?package=GitVersion.CommandLine&version=3.6.1" #tool "nuget:?package=NUnit.ConsoleRunner&version=3.4.1" ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var nugetApiKey = Argument("nugetapikey", EnvironmentVariable("NUGET_API_KEY")); ////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES ////////////////////////////////////////////////////////////////////// var version = "1.0.0"; var artifacts = Directory("./artifacts"); var solution = File("./src/Conductor.sln"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories("./src/**/bin"); CleanDirectories("./src/**/obj"); if (DirectoryExists(artifacts)) DeleteDirectory(artifacts, true); }); Task("Restore") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solution); }); Task("Versioning") .IsDependentOn("Clean") .WithCriteria(() => !BuildSystem.IsLocalBuild) .Does(() => { GitVersion(new GitVersionSettings { OutputType = GitVersionOutput.BuildServer }); var result = GitVersion(new GitVersionSettings { UpdateAssemblyInfo = true }); version = result.NuGetVersion; }); Task("Build") .IsDependentOn("Versioning") .IsDependentOn("Restore") .Does(() => { CreateDirectory(artifacts); DotNetBuild(solution, x => { x.SetConfiguration("Release"); x.WithProperty("GenerateDocumentation", "true"); }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var testResults = artifacts + File("TestResults.xml"); NUnit3("./src/**/bin/**/Release/*.Tests.dll", new NUnit3Settings { Results = testResults }); if (BuildSystem.IsRunningOnAppVeyor) AppVeyor.UploadTestResults(testResults, AppVeyorTestResultsType.NUnit3); }); Task("Package") .IsDependentOn("Build") .IsDependentOn("Test") .Does(() => { NuGetPack("./build/Conductor.nuspec", new NuGetPackSettings { Version = version, BasePath = "./src", OutputDirectory = artifacts }); }); Task("Publish") .IsDependentOn("Package") .Does(() => { var package = "./artifacts/Conductor." + version + ".nupkg"; NuGetPush(package, new NuGetPushSettings { ApiKey = nugetApiKey }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Package"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
mit
C#
9de7d0f69d4e40aff5edef24c533a2a72f20e964
speed up msbuild
zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos
source/Cosmos.Build.Builder/BuildTasks/MSBuildTargetBuildTaskBase.cs
source/Cosmos.Build.Builder/BuildTasks/MSBuildTargetBuildTaskBase.cs
using System; using System.Collections.Generic; using Cosmos.Build.Builder.Services; namespace Cosmos.Build.Builder.BuildTasks { internal abstract class MSBuildTargetBuildTaskBase : ProcessBuildTaskBase { public abstract string ProjectFilePath { get; } public abstract IEnumerable<string> Targets { get; } protected abstract IReadOnlyDictionary<string, string> Properties { get; } private readonly IMSBuildService _msBuildService; protected MSBuildTargetBuildTaskBase(IMSBuildService msBuildService) : base(true, false) { _msBuildService = msBuildService; } protected override string GetExePath() => _msBuildService.GetMSBuildExePath(); protected override string GetArguments() { if (ProjectFilePath == null) { throw new InvalidOperationException("ProjectFilePath is null!"); } var args = $"\"{ProjectFilePath}\" /nologo /maxcpucount /m /nodeReuse:False /verbosity:minimal /t:\"{String.Join(";", Targets)}\""; if (Properties != null) { foreach (var property in Properties) { var value = property.Value; if (value.EndsWith("\\")) { value += '\\'; } args += $" /p:\"{property.Key}={value}\""; } } args += " /p:DeployExtension=False"; return args; } } }
using System; using System.Collections.Generic; using Cosmos.Build.Builder.Services; namespace Cosmos.Build.Builder.BuildTasks { internal abstract class MSBuildTargetBuildTaskBase : ProcessBuildTaskBase { public abstract string ProjectFilePath { get; } public abstract IEnumerable<string> Targets { get; } protected abstract IReadOnlyDictionary<string, string> Properties { get; } private readonly IMSBuildService _msBuildService; protected MSBuildTargetBuildTaskBase(IMSBuildService msBuildService) : base(true, false) { _msBuildService = msBuildService; } protected override string GetExePath() => _msBuildService.GetMSBuildExePath(); protected override string GetArguments() { if (ProjectFilePath == null) { throw new InvalidOperationException("ProjectFilePath is null!"); } var args = $"\"{ProjectFilePath}\" /nologo /maxcpucount /nodeReuse:False /verbosity:minimal /t:\"{String.Join(";", Targets)}\""; if (Properties != null) { foreach (var property in Properties) { var value = property.Value; if (value.EndsWith("\\")) { value += '\\'; } args += $" /p:\"{property.Key}={value}\""; } } args += " /p:DeployExtension=False"; return args; } } }
bsd-3-clause
C#
f6284970f6e0af5921578f73c4b39fc1d9d18600
Update NewtonsoftJsonSerializer.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D/Modules/Serializer.Newtonsoft/NewtonsoftJsonSerializer.cs
src/Core2D/Modules/Serializer.Newtonsoft/NewtonsoftJsonSerializer.cs
using System; using Core2D; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Core2D.Serializer.Newtonsoft { public sealed class NewtonsoftJsonSerializer : IJsonSerializer { private readonly IServiceProvider _serviceProvider; private static readonly JsonSerializerSettings Settings; static NewtonsoftJsonSerializer() { Settings = new JsonSerializerSettings() { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Objects, PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ProjectContractResolver(), NullValueHandling = NullValueHandling.Ignore, Converters = { new KeyValuePairConverter(), new FontStyleConverter(), new ShapeStateConverter() } }; } public NewtonsoftJsonSerializer(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } string IJsonSerializer.Serialize<T>(T value) { return JsonConvert.SerializeObject(value, Settings); } T IJsonSerializer.Deserialize<T>(string json) { return JsonConvert.DeserializeObject<T>(json, Settings); } } }
using System; using Core2D; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Core2D.Serializer.Newtonsoft { public sealed class NewtonsoftJsonSerializer : IJsonSerializer { private readonly IServiceProvider _serviceProvider; private static readonly JsonSerializerSettings Settings; static NewtonsoftJsonSerializer() { Settings = new JsonSerializerSettings() { Formatting = Formatting.Indented, TypeNameHandling = TypeNameHandling.Objects, PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ProjectContractResolver(), NullValueHandling = NullValueHandling.Ignore, Converters = { new KeyValuePairConverter(), new FontStyleConverter(), new ShapeStateConverter() } }; } public NewtonsoftJsonSerializer(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } string IJsonSerializer.Serialize<T>(T value) { return JsonConvert.SerializeObject(value); } T IJsonSerializer.Deserialize<T>(string json) { return JsonConvert.DeserializeObject<T>(json); } } }
mit
C#
672bb565e8891d29ad1a213860e5f1c8f32a9ba7
Update QuoteRepository.cs
ScarletKuro/NadekoBot,miraai/NadekoBot,shikhir-arora/NadekoBot,halitalf/NadekoMods,Nielk1/NadekoBot,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Blacnova/NadekoBot,powered-by-moe/MikuBot,Midnight-Myth/Mitternacht-NEW,PravEF/EFNadekoBot,Grinjr/NadekoBot,WoodenGlaze/NadekoBot,ShadowNoire/NadekoBot,Taknok/NadekoBot,Midnight-Myth/Mitternacht-NEW,gfrewqpoiu/NadekoBot,Youngsie1997/NadekoBot
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); return _set.Where(q => q.Text.Contains(text) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); return _set.Where(q => q.Text.Contains(text) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
mit
C#
305736221f75af6fa3d90d045af81ee45e0b0bde
Fix DI test
toddams/RazorLight,toddams/RazorLight
tests/RazorLight.Tests/Extensions/ServiceCollectionExtensionsTest.cs
tests/RazorLight.Tests/Extensions/ServiceCollectionExtensionsTest.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; using RazorLight.Extensions; using System; namespace RazorLight.Tests.Extensions { public class ServiceCollectionExtensionsTest { private string rootPath = PathUtility.GetViewsPath(); private IServiceCollection GetServices() { var services = new ServiceCollection(); var envMock = new Mock<IHostingEnvironment>(); envMock.Setup(m => m.ContentRootPath).Returns(rootPath); services.AddSingleton<IHostingEnvironment>(envMock.Object); return services; } [Fact] public void Throws_On_Null_EngineFactoryProvider() { var services = GetServices(); Assert.Throws<ArgumentNullException>(() => { services.AddRazorLight(null); }); } [Fact] public void Ensure_FactoryMethod_Is_Called() { var services = GetServices(); bool called = false; services.AddRazorLight(() => { called = true; return new RazorLightEngineBuilder().UseEmbeddedResourcesProject(typeof(Root).Assembly).Build(); }); var provider = services.BuildServiceProvider(); var engine = provider.GetService<IRazorLightEngine>(); Assert.NotNull(engine); Assert.True(called); } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Moq; using Xunit; using RazorLight.Extensions; using System; namespace RazorLight.Tests.Extensions { public class ServiceCollectionExtensionsTest { private string rootPath = PathUtility.GetViewsPath(); private IServiceCollection GetServices() { var services = new ServiceCollection(); var envMock = new Mock<IHostingEnvironment>(); envMock.Setup(m => m.ContentRootPath).Returns(rootPath); services.AddSingleton<IHostingEnvironment>(envMock.Object); return services; } [Fact] public void Throws_On_Null_EngineFactoryProvider() { var services = GetServices(); Assert.Throws<ArgumentNullException>(() => { services.AddRazorLight(null); }); } [Fact] public void Ensure_FactoryMethod_Is_Called() { var services = GetServices(); bool called = false; services.AddRazorLight(() => { called = true; return new RazorLightEngineBuilder().Build(); }); var provider = services.BuildServiceProvider(); var engine = provider.GetService<IRazorLightEngine>(); Assert.NotNull(engine); Assert.True(called); } } }
apache-2.0
C#
ab869b84b6f73be51ed02b273d782c09164738eb
use ints for ids for simpler integration w/domain
tbstudee/IntacctClient
Entities/IntacctLineItem.cs
Entities/IntacctLineItem.cs
using System; using System.Xml.Linq; using Intacct.Infrastructure; namespace Intacct.Entities { public class IntacctLineItem : IntacctObject { public IntacctLineItem(XElement data) { this.SetPropertyValue(x => AccountNumber, data); this.SetPropertyValue(x => AccountLabel, data, true); this.SetPropertyValue(x => Amount, data); this.SetPropertyValue(x => Memo, data); this.SetPropertyValue(x => LocationId, data); this.SetPropertyValue(x => DepartmentId, data); } [IntacctName("glaccountno")] public int AccountNumber { get; private set; } [IntacctName("accountlabel")] public string AccountLabel { get; private set; } public decimal Amount { get; set; } public string Memo { get; set; } public int LocationId { get; set; } public int DepartmentId { get; set; } public static IntacctLineItem CreateWithAccountNumber(int accountNumber, decimal amount) { return new IntacctLineItem(amount) { AccountNumber = accountNumber }; } public static IntacctLineItem CreateWithAccountLabel(string accountLabel, decimal amount) { return new IntacctLineItem(amount) { AccountLabel = accountLabel }; } private IntacctLineItem(decimal amount) { Amount = amount; } internal override XObject[] ToXmlElements() { return new XObject[] { GetAccountXmlElement(), new XElement("amount", Amount), new XElement("memo", Memo ?? ""), new XElement("locationid", LocationId), new XElement("departmentid", DepartmentId) }; } private XElement GetAccountXmlElement() { if (!string.IsNullOrWhiteSpace(AccountNumber.ToString())) return new XElement("glaccountno", AccountNumber); if (!string.IsNullOrWhiteSpace(AccountLabel)) return new XElement("accountlabel", AccountLabel); throw new Exception("Unable to generate line item XML because neither account number or label are set."); } } }
using System; using System.Xml.Linq; using Intacct.Infrastructure; namespace Intacct.Entities { public class IntacctLineItem : IntacctObject { public IntacctLineItem(XElement data) { this.SetPropertyValue(x => AccountNumber, data); this.SetPropertyValue(x => AccountLabel, data, true); this.SetPropertyValue(x => Amount, data); this.SetPropertyValue(x => Memo, data); this.SetPropertyValue(x => LocationId, data); this.SetPropertyValue(x => DepartmentId, data); } [IntacctName("glaccountno")] public string AccountNumber { get; private set; } [IntacctName("accountlabel")] public string AccountLabel { get; private set; } public decimal Amount { get; set; } public string Memo { get; set; } public string LocationId { get; set; } public string DepartmentId { get; set; } public static IntacctLineItem CreateWithAccountNumber(string accountNumber, decimal amount) { return new IntacctLineItem(amount) { AccountNumber = accountNumber }; } public static IntacctLineItem CreateWithAccountLabel(string accountLabel, decimal amount) { return new IntacctLineItem(amount) { AccountLabel = accountLabel }; } private IntacctLineItem(decimal amount) { Amount = amount; } internal override XObject[] ToXmlElements() { return new XObject[] { GetAccountXmlElement(), new XElement("amount", Amount), new XElement("memo", Memo ?? ""), new XElement("locationid", LocationId), new XElement("departmentid", DepartmentId) }; } private XElement GetAccountXmlElement() { if (!string.IsNullOrWhiteSpace(AccountNumber)) return new XElement("glaccountno", AccountNumber); if (!string.IsNullOrWhiteSpace(AccountLabel)) return new XElement("accountlabel", AccountLabel); throw new Exception("Unable to generate line item XML because neither account number or label are set."); } } }
mit
C#
a43948857c84b963ca057192a274e046db017eee
Add license disclaimer
dga711/CefSharp,windygu/CefSharp,joshvera/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,rlmcneary2/CefSharp,haozhouxu/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,gregmartinhtc/CefSharp,Octopus-ITSM/CefSharp,ITGlobal/CefSharp,zhangjingpu/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,zhangjingpu/CefSharp,windygu/CefSharp,battewr/CefSharp,jamespearce2006/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,windygu/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,battewr/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,AJDev77/CefSharp,dga711/CefSharp,VioletLife/CefSharp,NumbersInternational/CefSharp,NumbersInternational/CefSharp,Livit/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,rover886/CefSharp,twxstar/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp,VioletLife/CefSharp,windygu/CefSharp,Haraguroicha/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,ruisebastiao/CefSharp,Livit/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,Octopus-ITSM/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,illfang/CefSharp,AJDev77/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,zhangjingpu/CefSharp,battewr/CefSharp,rover886/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,gregmartinhtc/CefSharp,wangzheng888520/CefSharp,joshvera/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,rlmcneary2/CefSharp,yoder/CefSharp,rover886/CefSharp,ITGlobal/CefSharp,ruisebastiao/CefSharp
CefSharp/TransitionType.cs
CefSharp/TransitionType.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { [Flags] public enum TransitionType : uint { /// <summary> /// Source is a link click or the JavaScript window.open function. This is /// also the default value for requests like sub-resource loads that are not navigations. /// </summary> LinkClicked = 0, /// <summary> /// Source is some other "explicit" navigation action such as creating a new /// browser or using the LoadURL function. This is also the default value /// for navigations where the actual type is unknown. /// </summary> Explicit = 1, /// <summary> /// Source is a subframe navigation. This is any content that is automatically /// loaded in a non-toplevel frame. For example, if a page consists of several /// frames containing ads, those ad URLs will have this transition type. /// The user may not even realize the content in these pages is a separate /// frame, so may not care about the URL. /// </summary> AutoSubFrame = 3, /// <summary> /// Source is a subframe navigation explicitly requested by the user that will /// generate new navigation entries in the back/forward list. These are /// probably more important than frames that were automatically loaded in /// the background because the user probably cares about the fact that this /// link was loaded. /// </summary> ManualSubFrame = 4, /// <summary> /// Source is a form submission by the user. NOTE: In some situations /// submitting a form does not result in this transition type. This can happen /// if the form uses a script to submit the contents. /// </summary> FormSubmit = 7, /// <summary> /// Source is a "reload" of the page via the Reload function or by re-visiting /// the same URL. NOTE: This is distinct from the concept of whether a /// particular load uses "reload semantics" (i.e. bypasses cached data). /// </summary> Reload = 8, /// <summary> /// General mask defining the bits used for the source values. /// </summary> SourceMask = 0xFF, /// <summary> /// Attempted to visit a URL but was blocked. /// </summary> Blocked = 0x00800000, /// <summary> /// Used the Forward or Back function to navigate among browsing history. /// </summary> ForwardBack = 0x01000000, /// <summary> /// The beginning of a navigation chain. /// </summary> ChainStart = 0x10000000, /// <summary> /// The last transition in a redirect chain. /// </summary> ChainEnd = 0x20000000, /// <summary> /// Redirects caused by JavaScript or a meta refresh tag on the page. /// </summary> CliendRedirect = 0x40000000, /// <summary> /// Redirects sent from the server by HTTP headers. /// </summary> ServerRedirect = 0x80000000, /// <summary> /// Used to test whether a transition involves a redirect. /// </summary> IsRedirect = 0xC0000000, /// <summary> /// General mask defining the bits used for the qualifiers. /// </summary> QualifierMask = 0xFFFFFF00 }; }
using System; namespace CefSharp { [Flags] public enum TransitionType : uint { /// <summary> /// Source is a link click or the JavaScript window.open function. This is /// also the default value for requests like sub-resource loads that are not navigations. /// </summary> LinkClicked = 0, /// <summary> /// Source is some other "explicit" navigation action such as creating a new /// browser or using the LoadURL function. This is also the default value /// for navigations where the actual type is unknown. /// </summary> Explicit = 1, /// <summary> /// Source is a subframe navigation. This is any content that is automatically /// loaded in a non-toplevel frame. For example, if a page consists of several /// frames containing ads, those ad URLs will have this transition type. /// The user may not even realize the content in these pages is a separate /// frame, so may not care about the URL. /// </summary> AutoSubFrame = 3, /// <summary> /// Source is a subframe navigation explicitly requested by the user that will /// generate new navigation entries in the back/forward list. These are /// probably more important than frames that were automatically loaded in /// the background because the user probably cares about the fact that this /// link was loaded. /// </summary> ManualSubFrame = 4, /// <summary> /// Source is a form submission by the user. NOTE: In some situations /// submitting a form does not result in this transition type. This can happen /// if the form uses a script to submit the contents. /// </summary> FormSubmit = 7, /// <summary> /// Source is a "reload" of the page via the Reload function or by re-visiting /// the same URL. NOTE: This is distinct from the concept of whether a /// particular load uses "reload semantics" (i.e. bypasses cached data). /// </summary> Reload = 8, /// <summary> /// General mask defining the bits used for the source values. /// </summary> SourceMask = 0xFF, /// <summary> /// Attempted to visit a URL but was blocked. /// </summary> Blocked = 0x00800000, /// <summary> /// Used the Forward or Back function to navigate among browsing history. /// </summary> ForwardBack = 0x01000000, /// <summary> /// The beginning of a navigation chain. /// </summary> ChainStart = 0x10000000, /// <summary> /// The last transition in a redirect chain. /// </summary> ChainEnd = 0x20000000, /// <summary> /// Redirects caused by JavaScript or a meta refresh tag on the page. /// </summary> CliendRedirect = 0x40000000, /// <summary> /// Redirects sent from the server by HTTP headers. /// </summary> ServerRedirect = 0x80000000, /// <summary> /// Used to test whether a transition involves a redirect. /// </summary> IsRedirect = 0xC0000000, /// <summary> /// General mask defining the bits used for the qualifiers. /// </summary> QualifierMask = 0xFFFFFF00 }; }
bsd-3-clause
C#
090ce84431543fac48da9c8e02260b8a43a4dcb1
Fix test failing when line endings change
exodrifter/unity-rumor
Compiler/Tests/Script.cs
Compiler/Tests/Script.cs
using Exodrifter.Rumor.Engine; using Exodrifter.Rumor.Parser; using NUnit.Framework; using System.Collections.Generic; namespace Exodrifter.Rumor.Compiler.Tests { using Rumor = Engine.Rumor; public static class Script { [Test] public static void ScriptOneSuccess() { var state = new ParserState("Alice: Hello world!", 4, 0); var result = Compiler.Script(state); Assert.AreEqual( new Dictionary<string, List<Node>> { { Rumor.MainIdentifier, new List<Node>() { new SetDialogNode("Alice", "Hello world!") } }, }, result ); Assert.AreEqual(19, state.Index); Assert.AreEqual(0, state.IndentIndex); } [Test] public static void ScriptMultipleSuccess() { var state = new ParserState( "Alice: Hello world!\n" + "Alice: How are you?\n" + "Alice: The weather seems nice today.\n" , 4, 0 ); var result = Compiler.Script(state); Assert.AreEqual( new Dictionary<string, List<Node>> { { Rumor.MainIdentifier, new List<Node>() { new SetDialogNode("Alice", "Hello world!") , new SetDialogNode("Alice", "How are you?") , new SetDialogNode("Alice", "The weather seems nice today.") } }, }, result ); Assert.AreEqual(76, state.Index); Assert.AreEqual(0, state.IndentIndex); } } }
using Exodrifter.Rumor.Engine; using Exodrifter.Rumor.Parser; using NUnit.Framework; using System.Collections.Generic; namespace Exodrifter.Rumor.Compiler.Tests { using Rumor = Engine.Rumor; public static class Script { [Test] public static void ScriptOneSuccess() { var state = new ParserState("Alice: Hello world!", 4, 0); var result = Compiler.Script(state); Assert.AreEqual( new Dictionary<string, List<Node>> { { Rumor.MainIdentifier, new List<Node>() { new SetDialogNode("Alice", "Hello world!") } }, }, result ); Assert.AreEqual(19, state.Index); Assert.AreEqual(0, state.IndentIndex); } [Test] public static void ScriptMultipleSuccess() { var state = new ParserState(@" Alice: Hello world! Alice: How are you? Alice: The weather seems nice today. " , 4, 0 ); var result = Compiler.Script(state); Assert.AreEqual( new Dictionary<string, List<Node>> { { Rumor.MainIdentifier, new List<Node>() { new SetDialogNode("Alice", "Hello world!") , new SetDialogNode("Alice", "How are you?") , new SetDialogNode("Alice", "The weather seems nice today.") } }, }, result ); Assert.AreEqual(92, state.Index); Assert.AreEqual(0, state.IndentIndex); } } }
mit
C#
9ab55277cc3f67a81553be8610675953bdf7820f
Move comment closer to pertaining region
ddpruitt/morelinq,fsateler/MoreLINQ,morelinq/MoreLINQ,fsateler/MoreLINQ,morelinq/MoreLINQ,ddpruitt/morelinq
MoreLinq/GenerateByIndex.cs
MoreLinq/GenerateByIndex.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2009 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Returns a sequence of values based on indexes. /// </summary> /// <remarks> /// The sequence is (practically) infinite /// - the index ranges from 0 to <c>int.MaxValue</c> inclusive. This function defers /// execution and streams the results. /// </remarks> /// <typeparam name="TResult">Type of result to generate</typeparam> /// <param name="generator">Generation function to apply to each index</param> /// <returns>A sequence </returns> public static IEnumerable<TResult> GenerateByIndex<TResult>(Func<int, TResult> generator) { if (generator == null) throw new ArgumentNullException(nameof(generator)); // Would just use Enumerable.Range(0, int.MaxValue).Select(generator) but that doesn't // include int.MaxValue. Picky, I know... return _(); IEnumerable<TResult> _() { // Looping over 0...int.MaxValue inclusive is a pain. Simplest is to go exclusive, // then go again for int.MaxValue. for (var i = 0; i < int.MaxValue; i++) yield return generator(i); yield return generator(int.MaxValue); } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2009 Jonathan Skeet. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Returns a sequence of values based on indexes. /// </summary> /// <remarks> /// The sequence is (practically) infinite /// - the index ranges from 0 to <c>int.MaxValue</c> inclusive. This function defers /// execution and streams the results. /// </remarks> /// <typeparam name="TResult">Type of result to generate</typeparam> /// <param name="generator">Generation function to apply to each index</param> /// <returns>A sequence </returns> public static IEnumerable<TResult> GenerateByIndex<TResult>(Func<int, TResult> generator) { // Would just use Enumerable.Range(0, int.MaxValue).Select(generator) but that doesn't // include int.MaxValue. Picky, I know... if (generator == null) throw new ArgumentNullException(nameof(generator)); return _(); IEnumerable<TResult> _() { // Looping over 0...int.MaxValue inclusive is a pain. Simplest is to go exclusive, // then go again for int.MaxValue. for (var i = 0; i < int.MaxValue; i++) yield return generator(i); yield return generator(int.MaxValue); } } } }
apache-2.0
C#
fbaeb36a4d2363bdf47c993b7fdb717829d43733
Add comment to IXamlWidgetRenderer interface for #722
charlenni/Mapsui,charlenni/Mapsui,pauldendulk/Mapsui
Mapsui.Rendering.Xaml/XamlWidgets/IXamlWidgetRenderer.cs
Mapsui.Rendering.Xaml/XamlWidgets/IXamlWidgetRenderer.cs
using System.Windows.Controls; using Mapsui.Widgets; namespace Mapsui.Rendering.Xaml.XamlWidgets { /// <summary> /// The IXamlWidgetRenderer interface is not public because xaml rendering will /// probably be removed on some point and we do not want users to go further /// in that direction. /// </summary> interface IXamlWidgetRenderer : IWidgetRenderer { void Draw(Canvas canvas, IReadOnlyViewport viewport, IWidget widget); } }
using System.Windows.Controls; using Mapsui.Widgets; namespace Mapsui.Rendering.Xaml.XamlWidgets { interface IXamlWidgetRenderer : IWidgetRenderer { void Draw(Canvas canvas, IReadOnlyViewport viewport, IWidget widget); } }
mit
C#
193bdb7912e8c76b66bb564dd136cfcc6bff5d9b
Fix compile error
Yonom/BotBits,EEJesse/BotBits,Tunous/BotBits
BotBits/Properties/AssemblyInfo.cs
BotBits/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BotBits.Core")] [assembly: AssemblyProduct("BotBits.Core")] [assembly: Guid("fbac626f-42ca-4413-ba36-1263bb636cbf")] [assembly: AssemblyDescription("BotBits is a framework to help bot makers make bots faster.")] [assembly: AssemblyCopyright("Copyright © Sepehr Farshid 2015")] [assembly: AssemblyTrademark("BotBits")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] //[assembly: InternalsVisibleTo("BotBits.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BotBits.Core")] [assembly: AssemblyProduct("BotBits.Core")] [assembly: Guid("fbac626f-42ca-4413-ba36-1263bb636cbf")] [assembly: AssemblyDescription("BotBits is a framework to help bot makers make bots faster.")] [assembly: AssemblyCopyright("Copyright © Sepehr Farshid 2015")] [assembly: AssemblyTrademark("BotBits")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("BotBits.Tests")]
mit
C#
12cd9cd47c686500bca3c0c3b2e64c3c0428ea7d
Change the indentation margin same as Solution Explorer
eriawan/roslyn,physhi/roslyn,mavasani/roslyn,dotnet/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,dotnet/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,wvdd007/roslyn,weltkante/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,sharwell/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,weltkante/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,physhi/roslyn,sharwell/roslyn,dotnet/roslyn,bartdesmet/roslyn,weltkante/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn
src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/TargetMenuItemViewModel.cs
src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/TargetMenuItemViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// View model used to show the MenuItem for inheritance target. /// </summary> internal class TargetMenuItemViewModel : InheritanceMenuItemViewModel { /// <summary> /// The margin for the default case. /// </summary> private static readonly Thickness s_defaultMargin = new Thickness(4, 1, 4, 1); /// <summary> /// The margin used when this target item needs to be indented when the target is shown with the header. /// e.g. /// 'I↓ Implemented members' /// Method 'Bar' /// 'I↑ Implementing members' /// Method 'Foo' /// It is 22 because the default left margin is 4, and we want to keep the same indentation margin same as solution explorer, which is 18. /// </summary> private static readonly Thickness s_indentMargin = new Thickness(22, 1, 4, 1); /// <summary> /// DefinitionItem used for navigation. /// </summary> public DefinitionItem DefinitionItem { get; } /// <summary> /// Margin for the image moniker. /// </summary> public Thickness Margin { get; } // Internal for testing purpose internal TargetMenuItemViewModel( string displayContent, ImageMoniker imageMoniker, string automationName, DefinitionItem definitionItem, Thickness margin) : base(displayContent, imageMoniker, automationName) { DefinitionItem = definitionItem; Margin = margin; } public static TargetMenuItemViewModel Create(InheritanceTargetItem target, bool indent) { var displayContent = target.DisplayName; var imageMoniker = target.Glyph.GetImageMoniker(); return new TargetMenuItemViewModel( displayContent, imageMoniker, displayContent, target.DefinitionItem, indent ? s_indentMargin : s_defaultMargin); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Windows; using Microsoft.CodeAnalysis.Editor.Wpf; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.InheritanceMargin; using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { /// <summary> /// View model used to show the MenuItem for inheritance target. /// </summary> internal class TargetMenuItemViewModel : InheritanceMenuItemViewModel { /// <summary> /// The margin for the default case. /// </summary> private static readonly Thickness s_defaultMargin = new Thickness(4, 1, 4, 1); /// <summary> /// The margin used when this target item needs to be indented when the target is shown with the header. /// e.g. /// 'I↓ Implemented members' /// Method 'Bar' /// 'I↑ Implementing members' /// Method 'Foo' /// It is 20 because the default left margin is 4, and the size of the image moniker(e.g. I↑) in the header is 16. /// </summary> private static readonly Thickness s_indentMargin = new Thickness(20, 1, 4, 1); /// <summary> /// DefinitionItem used for navigation. /// </summary> public DefinitionItem DefinitionItem { get; } /// <summary> /// Margin for the image moniker. /// </summary> public Thickness Margin { get; } // Internal for testing purpose internal TargetMenuItemViewModel( string displayContent, ImageMoniker imageMoniker, string automationName, DefinitionItem definitionItem, Thickness margin) : base(displayContent, imageMoniker, automationName) { DefinitionItem = definitionItem; Margin = margin; } public static TargetMenuItemViewModel Create(InheritanceTargetItem target, bool indent) { var displayContent = target.DisplayName; var imageMoniker = target.Glyph.GetImageMoniker(); return new TargetMenuItemViewModel( displayContent, imageMoniker, displayContent, target.DefinitionItem, indent ? s_indentMargin : s_defaultMargin); } } }
mit
C#
e9a04516b0e9aa08318d674297dc6daa8521b3d0
Update ShapeRenderer.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.Core/Renderers/ShapeRenderer.cs
src/Draw2D.Core/Renderers/ShapeRenderer.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Draw2D.Core.Shapes; using Draw2D.Core.Style; namespace Draw2D.Core.Renderers { public abstract class ShapeRenderer : ObservableObject { public abstract ISet<ShapeObject> Selected { get; set; } public abstract void InvalidateCache(DrawStyle style); public abstract void InvalidateCache(MatrixObject matrix); public abstract void InvalidateCache(ShapeObject shape, DrawStyle style, double dx, double dy); public abstract object PushMatrix(object dc, MatrixObject matrix); public abstract void PopMatrix(object dc, object state); public abstract void DrawLine(object dc, LineShape line, DrawStyle style, double dx, double dy); public abstract void DrawCubicBezier(object dc, CubicBezierShape cubicBezier, DrawStyle style, double dx, double dy); public abstract void DrawQuadraticBezier(object dc, QuadraticBezierShape quadraticBezier, DrawStyle style, double dx, double dy); public abstract void DrawPath(object dc, PathShape path, DrawStyle style, double dx, double dy); public abstract void DrawRectangle(object dc, RectangleShape rectangle, DrawStyle style, double dx, double dy); public abstract void DrawEllipse(object dc, EllipseShape ellipse, DrawStyle style, double dx, double dy); public abstract void DrawText(object dc, TextShape text, DrawStyle style, double dx, double dy); } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using Draw2D.Core.Style; namespace Draw2D.Core.Renderers { public abstract class ShapeRenderer : ObservableObject { public abstract ISet<ShapeObject> Selected { get; set; } public abstract void InvalidateCache(DrawStyle style); public abstract void InvalidateCache(MatrixObject matrix); public abstract void InvalidateCache(ShapeObject shape, DrawStyle style, double dx, double dy); public abstract object PushMatrix(object dc, MatrixObject matrix); public abstract void PopMatrix(object dc, object state); public abstract void DrawLine(object dc, IPoint start, IPoint point, DrawStyle style, double dx, double dy); public abstract void DrawCubicBezier(object dc, IPoint start, IPoint point1, IPoint point2, IPoint point3, DrawStyle style, double dx, double dy); public abstract void DrawQuadraticBezier(object dc, IPoint start, IPoint point1, IPoint point2, DrawStyle style, double dx, double dy); public abstract void DrawPath(object dc, IPath path, DrawStyle style, double dx, double dy); public abstract void DrawRectangle(object dc, IPoint tl, IPoint br, DrawStyle style, double dx, double dy); public abstract void DrawEllipse(object dc, IPoint tl, IPoint br, DrawStyle style, double dx, double dy); public abstract void DrawText(object dc, IPoint tl, IPoint br, string text, DrawStyle style, double dx, double dy); } }
mit
C#
4af4102b2b819a894a4d1e6574d99c6073c3b4bd
Update homepage URL
GetTabster/Tabster
Tabster/Forms/AboutDialog.cs
Tabster/Forms/AboutDialog.cs
#region using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; using Tabster.Properties; using Tabster.Utilities.Extensions; using Tabster.Utilities.Reflection; #endregion namespace Tabster.Forms { internal partial class AboutDialog : Form { public AboutDialog() { InitializeComponent(); lblVersion.Text = string.Format("Version {0}", new Version(Application.ProductVersion).ToShortString()); lblCopyright.Text = AssemblyUtilities.GetCopyrightString(Assembly.GetExecutingAssembly()); txtLicense.Text = Resources.ApplicationLicense; LoadPlugins(); } private void LoadPlugins() { foreach (var plugin in Program.PluginController) { if (plugin.GUID != Guid.Empty && Program.PluginController.IsEnabled(plugin.GUID)) { var lvi = new ListViewItem() { Text = plugin.Plugin.DisplayName ?? "N/A" }; lvi.SubItems.Add(plugin.Plugin.Version != null ? plugin.Plugin.Version.ToString() : "N/A"); lvi.SubItems.Add(plugin.Plugin.Author ?? "N/A"); lvi.SubItems.Add(Path.GetFileName(plugin.Assembly.Location)); listPlugins.Items.Add(lvi); } } if (listPlugins.Items.Count > 0) listPlugins.AutoResizeColumn(listPlugins.Columns.Count - 1, ColumnHeaderAutoResizeStyle.ColumnContent); } private void LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.fatcow.com"); } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.iconshock.com/"); } private void btnHomepage_Click(object sender, EventArgs e) { Process.Start("http://tabster.org"); } } }
#region using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Windows.Forms; using Tabster.Properties; using Tabster.Utilities.Extensions; using Tabster.Utilities.Reflection; #endregion namespace Tabster.Forms { internal partial class AboutDialog : Form { public AboutDialog() { InitializeComponent(); lblVersion.Text = string.Format("Version {0}", new Version(Application.ProductVersion).ToShortString()); lblCopyright.Text = AssemblyUtilities.GetCopyrightString(Assembly.GetExecutingAssembly()); txtLicense.Text = Resources.ApplicationLicense; LoadPlugins(); } private void LoadPlugins() { foreach (var plugin in Program.PluginController) { if (plugin.GUID != Guid.Empty && Program.PluginController.IsEnabled(plugin.GUID)) { var lvi = new ListViewItem() { Text = plugin.Plugin.DisplayName ?? "N/A" }; lvi.SubItems.Add(plugin.Plugin.Version != null ? plugin.Plugin.Version.ToString() : "N/A"); lvi.SubItems.Add(plugin.Plugin.Author ?? "N/A"); lvi.SubItems.Add(Path.GetFileName(plugin.Assembly.Location)); listPlugins.Items.Add(lvi); } } if (listPlugins.Items.Count > 0) listPlugins.AutoResizeColumn(listPlugins.Columns.Count - 1, ColumnHeaderAutoResizeStyle.ColumnContent); } private void LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.fatcow.com"); } private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.iconshock.com/"); } private void btnHomepage_Click(object sender, EventArgs e) { Process.Start("http://nateshoffner.com"); } } }
apache-2.0
C#
909e88cb112c59e5256f14771c675202b5a8c0f4
Create Label failing due to null Color & ExternalID being sent to API
MartynJones87/clubhouse.io.net
Clubhouse.io.net/Entities/Labels/ClubhouseCreateLabelParams.cs
Clubhouse.io.net/Entities/Labels/ClubhouseCreateLabelParams.cs
using Newtonsoft.Json; namespace Clubhouse.io.net.Entities.Labels { public class ClubhouseCreateLabelParams { [JsonProperty(PropertyName = "color", NullValueHandling = NullValueHandling.Ignore)] public string Color { get; set; } [JsonProperty(PropertyName = "external_id", NullValueHandling = NullValueHandling.Ignore)] public string ExternalID { get; set; } [JsonProperty(PropertyName = "name", Required = Required.Always)] public string Name { get; set; } } }
using Newtonsoft.Json; namespace Clubhouse.io.net.Entities.Labels { public class ClubhouseCreateLabelParams { [JsonProperty(PropertyName = "color")] public string Color { get; set; } [JsonProperty(PropertyName = "external_id")] public string ExternalID { get; set; } [JsonProperty(PropertyName = "name", Required = Required.Always)] public string Name { get; set; } } }
mit
C#
d912e132619f8c3f0819c81c344349b844ea6b0a
Remove HasErrors override as it is never called on background json symbols anymore.
PenguinF/sandra-three
Eutherion/Shared/Text/Json/JsonUnterminatedMultiLineComment.cs
Eutherion/Shared/Text/Json/JsonUnterminatedMultiLineComment.cs
#region License /********************************************************************************* * JsonUnterminatedMultiLineComment.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; namespace Eutherion.Text.Json { public sealed class JsonUnterminatedMultiLineComment : JsonSymbol { /// <summary> /// Creates a <see cref="JsonErrorInfo"/> for unterminated multiline comments. /// </summary> /// <param name="start"> /// The start position of the unterminated comment. /// </param> /// <param name="length"> /// The length of the unterminated comment. /// </param> public static JsonErrorInfo CreateError(int start, int length) => new JsonErrorInfo(JsonErrorCode.UnterminatedMultiLineComment, start, length); public override int Length { get; } public override bool IsBackground => true; public override IEnumerable<JsonErrorInfo> GetErrors(int start) => new SingleElementEnumerable<JsonErrorInfo>(CreateError(start, Length)); public JsonUnterminatedMultiLineComment(int length) { if (length <= 1) throw new ArgumentOutOfRangeException(nameof(length)); Length = length; } public override void Accept(JsonSymbolVisitor visitor) => visitor.VisitUnterminatedMultiLineComment(this); public override TResult Accept<TResult>(JsonSymbolVisitor<TResult> visitor) => visitor.VisitUnterminatedMultiLineComment(this); public override TResult Accept<T, TResult>(JsonSymbolVisitor<T, TResult> visitor, T arg) => visitor.VisitUnterminatedMultiLineComment(this, arg); } }
#region License /********************************************************************************* * JsonUnterminatedMultiLineComment.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; namespace Eutherion.Text.Json { public sealed class JsonUnterminatedMultiLineComment : JsonSymbol { /// <summary> /// Creates a <see cref="JsonErrorInfo"/> for unterminated multiline comments. /// </summary> /// <param name="start"> /// The start position of the unterminated comment. /// </param> /// <param name="length"> /// The length of the unterminated comment. /// </param> public static JsonErrorInfo CreateError(int start, int length) => new JsonErrorInfo(JsonErrorCode.UnterminatedMultiLineComment, start, length); public override int Length { get; } public override bool IsBackground => true; public override bool HasErrors => true; public override IEnumerable<JsonErrorInfo> GetErrors(int start) => new SingleElementEnumerable<JsonErrorInfo>(CreateError(start, Length)); public JsonUnterminatedMultiLineComment(int length) { if (length <= 1) throw new ArgumentOutOfRangeException(nameof(length)); Length = length; } public override void Accept(JsonSymbolVisitor visitor) => visitor.VisitUnterminatedMultiLineComment(this); public override TResult Accept<TResult>(JsonSymbolVisitor<TResult> visitor) => visitor.VisitUnterminatedMultiLineComment(this); public override TResult Accept<T, TResult>(JsonSymbolVisitor<T, TResult> visitor, T arg) => visitor.VisitUnterminatedMultiLineComment(this, arg); } }
apache-2.0
C#
97e131a795de8d37402a9f0d60f5e31a9c9b3714
Add a values method
ngallagher/simplexml,ngallagher/simplexml,ngallagher/simplexml
collections/Map.cs
collections/Map.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFramework.Xml { public abstract class Map<K, V> { public abstract int Count { get; } public abstract bool Empty { get; } public abstract K[] Keys { get; } public abstract V[] Values { get; } public abstract V this[K key] { get; set; } public abstract V Get(K key); public abstract V Remove(K key); public abstract V Put(K key, V value); public abstract bool Contains(K key); public abstract void Clear(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFramework.Xml { public abstract class Map<K, V> { public abstract int Count { get; } public abstract bool Empty { get; } public abstract K[] Keys { get; } public abstract K[] Values { get; } public abstract V this[K key] { get; set; } public abstract V Get(K key); public abstract V Remove(K key); public abstract V Put(K key, V value); public abstract bool Contains(K key); public abstract void Clear(); } }
apache-2.0
C#
44e473577913e5a3e5c84c46c2411afadfb41734
Update AntimalwareScanResult.cs
tiksn/TIKSN-Framework
TIKSN.Core/Security/Antimalware/AntimalwareScanResult.cs
TIKSN.Core/Security/Antimalware/AntimalwareScanResult.cs
namespace TIKSN.Security.Antimalware { public enum AntimalwareScanResult { Safe, Unsafe, Unknown } }
namespace TIKSN.Security.Antimalware { public enum AntimalwareScanResult { Safe, Unsafe, Unknown } }
mit
C#
eac8b325566a5e1af207f79778a616a052f61584
Fix unescape code for EmulatedFolderHierachy (failed for more than one escaped character)
Mikescher/AlephNote
Source/AlephNote.PluginInterface/Objects/HierarchyEmulationConfig.cs
Source/AlephNote.PluginInterface/Objects/HierarchyEmulationConfig.cs
using System.Collections.Generic; using System.Text; namespace AlephNote.PluginInterface.Util { public class HierarchyEmulationConfig { public readonly bool EmulateSubfolders; public readonly string SeperatorString; public readonly char EscapeChar; public HierarchyEmulationConfig(bool enabled, string seperator, char escape) { EmulateSubfolders = enabled; SeperatorString = seperator; EscapeChar = escape; } public string EscapeStringForRemote(string str) { if (EscapeChar.ToString() == SeperatorString) { return str.Replace(EscapeChar.ToString(), EscapeChar + "" + EscapeChar); } else { str = str.Replace(EscapeChar.ToString(), EscapeChar + "" + EscapeChar); str = str.Replace(SeperatorString, EscapeChar + SeperatorString); return str; } } public string EscapeStringListForRemote(IEnumerable<string> list) { var b = new StringBuilder(); bool first = true; foreach (var elem in list) { if (!first) b.Append(SeperatorString); first = false; b.Append(EscapeStringForRemote(elem)); } return b.ToString(); } public IEnumerable<string> UnescapeStringFromRemote(string str) { var b = new StringBuilder(); var escape = false; for (int i = 0; i < str.Length; i++) { if (escape) { b.Append(str[i]); escape = false; continue; } else { if (str[i] == EscapeChar) { if (EscapeChar.ToString() == SeperatorString && i+1 < str.Length && !str.Substring(i+1).StartsWith(SeperatorString)) { // special case: EscapeChar == SeparatorChar // We handle "somehing\\something" as an escaped '\' // And "somehing\something" as Seperator i += SeperatorString.Length - 1; yield return b.ToString(); b.Clear(); escape = false; continue; } else { escape = true; continue; } } else { if (str[i] == SeperatorString[0] && str.Substring(i).StartsWith(SeperatorString)) { i += SeperatorString.Length - 1; yield return b.ToString(); b.Clear(); escape = false; continue; } else { b.Append(str[i]); continue; } } } } yield return b.ToString(); yield break; } } }
using System.Collections.Generic; using System.Text; namespace AlephNote.PluginInterface.Util { public class HierarchyEmulationConfig { public readonly bool EmulateSubfolders; public readonly string SeperatorString; public readonly char EscapeChar; public HierarchyEmulationConfig(bool enabled, string seperator, char escape) { EmulateSubfolders = enabled; SeperatorString = seperator; EscapeChar = escape; } public string EscapeStringForRemote(string str) { if (EscapeChar.ToString() == SeperatorString) { return str.Replace(EscapeChar.ToString(), EscapeChar + "" + EscapeChar); } else { str = str.Replace(EscapeChar.ToString(), EscapeChar + "" + EscapeChar); str = str.Replace(SeperatorString, EscapeChar + SeperatorString); return str; } } public string EscapeStringListForRemote(IEnumerable<string> list) { var b = new StringBuilder(); bool first = true; foreach (var elem in list) { if (!first) b.Append(SeperatorString); first = false; b.Append(EscapeStringForRemote(elem)); } return b.ToString(); } public IEnumerable<string> UnescapeStringFromRemote(string str) { var b = new StringBuilder(); var escape = false; for (int i = 0; i < str.Length; i++) { if (escape) { b.Append(str[i]); continue; } else { if (str[i] == EscapeChar) { if (EscapeChar.ToString() == SeperatorString && i+1 < str.Length && !str.Substring(i+1).StartsWith(SeperatorString)) { i += SeperatorString.Length - 1; yield return b.ToString(); b.Clear(); continue; } else { escape = true; continue; } } else { if (str[i] == SeperatorString[0] && str.Substring(i).StartsWith(SeperatorString)) { i += SeperatorString.Length - 1; yield return b.ToString(); b.Clear(); continue; } else { b.Append(str[i]); continue; } } } } yield return b.ToString(); yield break; } } }
mit
C#
d6e0e0ce7e1d6787b061af91bab802ac0c60e848
Update IPartialConfigurationValidator.cs
tiksn/TIKSN-Framework
TIKSN.Core/Configuration/Validator/IPartialConfigurationValidator.cs
TIKSN.Core/Configuration/Validator/IPartialConfigurationValidator.cs
namespace TIKSN.Configuration.Validator { public interface IPartialConfigurationValidator<in T> { void ValidateConfiguration(T instance); } }
namespace TIKSN.Configuration.Validator { public interface IPartialConfigurationValidator<in T> { void ValidateConfiguration(T instance); } }
mit
C#
519eccc0126fc901725e1f2e72e3c168056ab724
Add convenience ctor to Span
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
Ooui/Span.cs
Ooui/Span.cs
using System; namespace Ooui { public class Span : Element { public Span () : base ("span") { } public Span (string text) : this () { Text = text; } } }
using System; namespace Ooui { public class Span : Element { public Span () : base ("span") { } } }
mit
C#
93e369d0942cb42df4fb092543091295daa17481
Add DocumentDb connection to main kotori config
kotorihq/kotori-core
KotoriCore/Configuration/Kotori.cs
KotoriCore/Configuration/Kotori.cs
using System.Collections.Generic; namespace KotoriCore.Configuration { /// <summary> /// Kotori main configuration. /// </summary> public class Kotori { /// <summary> /// Gets or sets the instance. /// </summary> /// <value>The instance.</value> public string Instance { get; set; } /// <summary> /// GEts or sets the version of kotori server. /// </summary> /// <value>The version.</value> public string Version { get; set; } /// <summary> /// Gets or sets the master keys. /// </summary> /// <value>The master keys.</value> public IEnumerable<MasterKey> MasterKeys { get; set; } /// <summary> /// Gets or sets the document db connection string. /// </summary> /// <value>The document db.</value> public DocumentDb DocumentDb { get; set; } } }
using System.Collections.Generic; namespace KotoriCore.Configuration { /// <summary> /// Kotori main configuration. /// </summary> public class Kotori { /// <summary> /// Gets or sets the instance. /// </summary> /// <value>The instance.</value> public string Instance { get; set; } /// <summary> /// GEts or sets the version of kotori server. /// </summary> /// <value>The version.</value> public string Version { get; set; } /// <summary> /// Gets or sets the master keys. /// </summary> /// <value>The master keys.</value> public IEnumerable<MasterKey> MasterKeys { get; set; } } }
mit
C#
c29dc262d1ebe25fc8021ae1972180d1df85353c
Simplify implementation of IsNullOrWhiteSpace
glorylee/FluentValidation,IRlyDontKnow/FluentValidation,deluxetiky/FluentValidation,ruisebastiao/FluentValidation,cecilphillip/FluentValidation,mgmoody42/FluentValidation,robv8r/FluentValidation,GDoronin/FluentValidation,regisbsb/FluentValidation,olcayseker/FluentValidation
src/FluentValidation/Validators/NotEmptyValidator.cs
src/FluentValidation/Validators/NotEmptyValidator.cs
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://fluentvalidation.codeplex.com #endregion namespace FluentValidation.Validators { using System.Collections; using Resources; using System.Linq; public class NotEmptyValidator : PropertyValidator, INotEmptyValidator { readonly object defaultValueForType; public NotEmptyValidator(object defaultValueForType) : base(() => Messages.notempty_error) { this.defaultValueForType = defaultValueForType; } protected override bool IsValid(PropertyValidatorContext context) { if (context.PropertyValue == null || IsInvalidString(context.PropertyValue) || IsEmptyCollection(context.PropertyValue) || Equals(context.PropertyValue, defaultValueForType)) { return false; } return true; } bool IsEmptyCollection(object propertyValue) { var collection = propertyValue as IEnumerable; return collection != null && !collection.Cast<object>().Any(); } bool IsInvalidString(object value) { if (value is string) { return string.IsNullOrWhiteSpace(value as string); } return false; } } public interface INotEmptyValidator : IPropertyValidator { } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://fluentvalidation.codeplex.com #endregion namespace FluentValidation.Validators { using System.Collections; using Resources; using System.Linq; public class NotEmptyValidator : PropertyValidator, INotEmptyValidator { readonly object defaultValueForType; public NotEmptyValidator(object defaultValueForType) : base(() => Messages.notempty_error) { this.defaultValueForType = defaultValueForType; } protected override bool IsValid(PropertyValidatorContext context) { if (context.PropertyValue == null || IsInvalidString(context.PropertyValue) || IsEmptyCollection(context.PropertyValue) || Equals(context.PropertyValue, defaultValueForType)) { return false; } return true; } bool IsEmptyCollection(object propertyValue) { var collection = propertyValue as IEnumerable; return collection != null && !collection.Cast<object>().Any(); } bool IsInvalidString(object value) { if (value is string) { return IsNullOrWhiteSpace(value as string); } return false; } bool IsNullOrWhiteSpace(string value) { if (value != null) { for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { return false; } } } return true; } } public interface INotEmptyValidator : IPropertyValidator { } }
apache-2.0
C#
20d162d6128aece4e670d0ba08bfd75108a2c5b2
Update tests.
andygjp/EntityFramework-Reverse-POCO-Code-First-Generator,davidsk/EntityFramework-Reverse-POCO-Code-First-Generator,sjh37/efreversepoco
Tester/TableValuedFunctionTests.cs
Tester/TableValuedFunctionTests.cs
using System.Linq; using NUnit.Framework; namespace Tester { [TestFixture] public class TableValuedFunctionTests { [Test] public void Standard_test() { // Arrange var db = new TestDatabaseStandard.TestDbContext(); // Act var data = db.CsvToInt("123,456", "").ToList(); // Assert Assert.AreEqual(2, data.Count); Assert.AreEqual(123, data[0].IntValue); Assert.AreEqual(456, data[1].IntValue); } [Test] public void Standard_FunctionCanBeCalledWithinQueryThroughInterfaceReference() { // Arrange var db = (TestDatabaseStandard.ITestDbContext)new TestDatabaseStandard.TestDbContext(); // Act var data = (from f in db.Stafford_Foos let i = db.CsvToInt("123,456", "") select new {f, i}).ToList().SelectMany(d => d.i).ToList(); // Assert Assert.AreEqual(4, data.Count); } [Test] public void DataAnnotation_test() { // Arrange var db = new TestDatabaseDataAnnotation.TestDbContext(); // Act var data = db.CsvToInt("123,456", "").ToList(); // Assert Assert.AreEqual(2, data.Count); Assert.AreEqual(123, data[0].IntValue); Assert.AreEqual(456, data[1].IntValue); } [Test] public void DataAnnotation_FunctionCanBeCalledWithinQueryThroughInterfaceReference() { // Arrange var db = (TestDatabaseDataAnnotation.ITestDbContext)new TestDatabaseDataAnnotation.TestDbContext(); // Act var data = (from f in db.Stafford_Foos let i = db.CsvToInt("123,456", "") select new { f, i }).ToList().SelectMany(d => d.i).ToList(); // Assert Assert.AreEqual(4, data.Count); } } }
using System.Linq; using NUnit.Framework; namespace Tester { [TestFixture] public class TableValuedFunctionTests { [Test] public void Standard_test() { // Arrange var db = new TestDatabaseStandard.TestDbContext(); // Act var data = db.CsvToInt("123,456", "").ToList(); // Assert Assert.AreEqual(2, data.Count); Assert.AreEqual(123, data[0].IntValue); Assert.AreEqual(456, data[1].IntValue); } [Test] public void Standard_FunctionCanBeCalledWithinQueryThroughInterfaceReference() { // Arrange var db = (TestDatabaseStandard.ITestDbContext)new TestDatabaseStandard.TestDbContext(); // Act var data = (from f in db.Stafford_Foos let i = db.CsvToInt("123,456", "") select i).SelectMany(i => i).ToList(); // Assert Assert.AreEqual(2, data.Count); Assert.AreEqual(123, data[0].IntValue); Assert.AreEqual(456, data[1].IntValue); } [Test] public void DataAnnotation_test() { // Arrange var db = new TestDatabaseDataAnnotation.TestDbContext(); // Act var data = db.CsvToInt("123,456", "").ToList(); // Assert Assert.AreEqual(2, data.Count); Assert.AreEqual(123, data[0].IntValue); Assert.AreEqual(456, data[1].IntValue); } [Test] public void DataAnnotation_FunctionCanBeCalledWithinQueryThroughInterfaceReference() { // Arrange var db = (TestDatabaseDataAnnotation.ITestDbContext)new TestDatabaseDataAnnotation.TestDbContext(); // Act var data = (from f in db.Stafford_Foos let i = db.CsvToInt("123,456", "") select i).SelectMany(i => i).ToList(); // Assert Assert.AreEqual(2, data.Count); Assert.AreEqual(123, data[0].IntValue); Assert.AreEqual(456, data[1].IntValue); } } }
apache-2.0
C#
b04555654a7e4dcedadc74b30f597c474108a1ba
Update _Layout.cshtml
aurelia/cli,aurelia/cli
lib/resources/content/javascriptservices/Views/Shared/_Layout.cshtml
lib/resources/content/javascriptservices/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewData["Title"] - Aurelia</title> <link rel="stylesheet" asp-append-version="true" asp-href-include="~/dist/css/*.css"/> </head> <body> @RenderBody() @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewData["Title"] - Aurelia</title> </head> <body> @RenderBody() @RenderSection("scripts", required: false) </body> </html>
mit
C#
79353be905d0e8147be2f86175e7b441b7e17a92
Increase the sleep time when polling for diagnostic integration tests. (#894)
benwulfe/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,chrisdunelm/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,googleapis/google-cloud-dotnet,chrisdunelm/gcloud-dotnet,iantalarico/google-cloud-dotnet,iantalarico/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,benwulfe/google-cloud-dotnet,googleapis/google-cloud-dotnet,evildour/google-cloud-dotnet,jskeet/google-cloud-dotnet,evildour/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,evildour/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet
apis/Google.Cloud.Diagnostics.Common/Google.Cloud.Diagnostics.Common.IntegrationTests/BaseEntryPolling.cs
apis/Google.Cloud.Diagnostics.Common/Google.Cloud.Diagnostics.Common.IntegrationTests/BaseEntryPolling.cs
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Google.Cloud.Diagnostics.Common.IntegrationTests { /// <summary> /// Abstract class with functions to poll for a list of types. /// </summary> internal abstract class BaseEntryPolling<T> { /// <summary>Total time to spend sleeping when looking for entries.</summary> private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(10); /// <summary>Time to sleep between checks for entries.</summary> private static readonly TimeSpan _sleepInterval = TimeSpan.FromSeconds(5); /// <summary> /// Polls for entries of type <see cref="T"/>. Will continue to poll until /// there are at least the minimum number of entries or the polling times out. /// </summary> /// <param name="minEntries">The minimum number of entries needed.</param> /// <param name="getEntries">Function that will return a <see cref="IEnumerable{T}"/></param> /// <returns>The entries or an empty list if not enough entries are found or polling times out.</returns> protected IEnumerable<T> GetEntries(int minEntries, Func<IEnumerable<T>> getEntries) { TimeSpan totalSleepTime = TimeSpan.Zero; while (totalSleepTime < _timeout) { TimeSpan sleepTime = minEntries > 0 ? _sleepInterval : _timeout; totalSleepTime += sleepTime; Thread.Sleep(sleepTime); IEnumerable<T> entries = getEntries(); if (minEntries == 0 || entries.Count() >= minEntries) { return entries; } } return new List<T>(); } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Google.Cloud.Diagnostics.Common.IntegrationTests { /// <summary> /// Abstract class with functions to poll for a list of types. /// </summary> internal abstract class BaseEntryPolling<T> { /// <summary>Total time to spend sleeping when looking for entries.</summary> private static readonly TimeSpan _timeout = TimeSpan.FromSeconds(10); /// <summary>Time to sleep between checks for entries.</summary> private static readonly TimeSpan _sleepInterval = TimeSpan.FromSeconds(2); /// <summary> /// Polls for entries of type <see cref="T"/>. Will continue to poll until /// there are at least the minimum number of entries or the polling times out. /// </summary> /// <param name="minEntries">The minimum number of entries needed.</param> /// <param name="getEntries">Function that will return a <see cref="IEnumerable{T}"/></param> /// <returns>The entries or an empty list if not enough entries are found or polling times out.</returns> protected IEnumerable<T> GetEntries(int minEntries, Func<IEnumerable<T>> getEntries) { TimeSpan totalSleepTime = TimeSpan.Zero; while (totalSleepTime < _timeout) { TimeSpan sleepTime = minEntries > 0 ? _sleepInterval : _timeout; totalSleepTime += sleepTime; Thread.Sleep(sleepTime); IEnumerable<T> entries = getEntries(); if (minEntries == 0 || entries.Count() >= minEntries) { return entries; } } return new List<T>(); } } }
apache-2.0
C#
8d412de750da8df3da62afcd138b08232e44fa32
Change because lqr support was added to the Linux and macOS build.
dlemstra/Magick.NET,dlemstra/Magick.NET
tests/Magick.NET.Tests/Shared/MagickNETTests/TheDelegatesProperty.cs
tests/Magick.NET.Tests/Shared/MagickNETTests/TheDelegatesProperty.cs
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using ImageMagick; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Magick.NET.Tests { public partial class MagickNETTests { [TestClass] public class TheDelegatesProperty { [TestMethod] public void ShouldReturnAllDelegates() { var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment #if WINDOWS_BUILD Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates); #else Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms lqr openexr png raw tiff webp xml zlib", delegates); #endif } } } }
// Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using ImageMagick; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Magick.NET.Tests { public partial class MagickNETTests { [TestClass] public class TheDelegatesProperty { [TestMethod] public void ShouldReturnAllDelegates() { var delegates = MagickNET.Delegates; // Cannot detect difference between macOS and Linux build at the moment #if WINDOWS_BUILD Assert.AreEqual("cairo flif freetype gslib heic jng jp2 jpeg lcms lqr openexr pangocairo png ps raw rsvg tiff webp xml zlib", delegates); #else Assert.AreEqual("fontconfig freetype heic jng jp2 jpeg lcms openexr png raw tiff webp xml zlib", delegates); #endif } } } }
apache-2.0
C#
f9e12f2adece463f7bfe00120818f1198d9b7b75
Remove debug code
Remi-Tech/compass-core
Compass.CoreServer/Controllers/SubscribeController.cs
Compass.CoreServer/Controllers/SubscribeController.cs
using System.Threading.Tasks; using Compass.Domain.Models; using Compass.Domain.Services.Subscription; using Microsoft.AspNetCore.Mvc; namespace Compass.CoreServer.Controllers { [Produces("application/json")] public class SubscribeController : Controller { private readonly ISubscriptionService _subscriptionService; public SubscribeController( ISubscriptionService subscriptionService ) { _subscriptionService = subscriptionService; } [HttpPost("subscribe")] public async Task<ServiceSubscription> Subscribe([FromBody]ServiceSubscription serviceSubscription) { return await _subscriptionService.SubscribeAsync(serviceSubscription); } } }
using System.Threading.Tasks; using Compass.Domain.Models; using Compass.Domain.Services.Subscription; using Microsoft.AspNetCore.Mvc; namespace Compass.CoreServer.Controllers { [Produces("application/json")] public class SubscribeController : Controller { private readonly ISubscriptionService _subscriptionService; public SubscribeController( ISubscriptionService subscriptionService ) { _subscriptionService = subscriptionService; } [HttpPost("subscribe")] public async Task<ServiceSubscription> Subscribe([FromBody]ServiceSubscription serviceSubscription) { return new ServiceSubscription(); return await _subscriptionService.SubscribeAsync(serviceSubscription); } } }
apache-2.0
C#
8a1acd93921ad3f2fd4e6a62e497ed26461ed640
Remove comment
nickbabcock/Farmhash.Sharp,nickbabcock/Farmhash.Sharp,nickbabcock/Farmhash.Sharp,nickbabcock/Farmhash.Sharp
Farmhash.Sharp.Benchmarks/HashBenchmark32.cs
Farmhash.Sharp.Benchmarks/HashBenchmark32.cs
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using System.Security.Cryptography; using System.Text; #if !CORE using System.Data.HashFunction; using xxHashSharp; #endif namespace Farmhash.Sharp.Benchmarks { [Config(typeof(Config))] public class HashBenchmark32 { private byte[] data; private string dataStr; private static readonly MD5 md5 = MD5.Create(); [Setup] public void SetupData() { dataStr = new string('.', PayloadLength); data = Encoding.ASCII.GetBytes(dataStr); } [Params(4, 11, 25, 100, 1000, 10000)] public int PayloadLength { get; set; } [Benchmark] public uint FarmHash() => Farmhash.Hash32(data, data.Length); [Benchmark] public byte[] Md5() => md5.ComputeHash(data); [Benchmark] public int StringHashCode() => dataStr.GetHashCode(); [Benchmark] public uint SparrowXXHash() => SparrowHashing.XXHash32.Calculate(data, data.Length); #if !CORE private static readonly System.Data.HashFunction.CityHash hcity = new System.Data.HashFunction.CityHash(32); private static readonly SpookyHashV2 Spooky = new SpookyHashV2(32); [Benchmark] public uint XXHash() => xxHash.CalculateHash(data); [Benchmark] public uint CityHashNet() => CityHash.CityHash.CityHash32(dataStr); [Benchmark] public byte[] HFCityHash() => hcity.ComputeHash(data); [Benchmark] public byte[] SpookyHash() => Spooky.ComputeHash(data); [Benchmark] public unsafe uint Spookily() { fixed (byte* buffer = data) { return SpookilySharp.SpookyHash.Hash32(buffer, data.Length, 0); } } #endif } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Jobs; using System.Security.Cryptography; using System.Text; #if !CORE using System.Data.HashFunction; using xxHashSharp; #endif namespace Farmhash.Sharp.Benchmarks { //#if CORE // [CoreJob] //#elif MONO // [MonoJob] //#else // [ClrJob] // [LegacyJitX86Job, LegacyJitX64Job, RyuJitX64Job] //#endif [Config(typeof(Config))] public class HashBenchmark32 { private byte[] data; private string dataStr; private static readonly MD5 md5 = MD5.Create(); [Setup] public void SetupData() { dataStr = new string('.', PayloadLength); data = Encoding.ASCII.GetBytes(dataStr); } [Params(4, 11, 25, 100, 1000, 10000)] public int PayloadLength { get; set; } [Benchmark] public uint FarmHash() => Farmhash.Hash32(data, data.Length); [Benchmark] public byte[] Md5() => md5.ComputeHash(data); [Benchmark] public int StringHashCode() => dataStr.GetHashCode(); [Benchmark] public uint SparrowXXHash() => SparrowHashing.XXHash32.Calculate(data, data.Length); #if !CORE private static readonly System.Data.HashFunction.CityHash hcity = new System.Data.HashFunction.CityHash(32); private static readonly SpookyHashV2 Spooky = new SpookyHashV2(32); [Benchmark] public uint XXHash() => xxHash.CalculateHash(data); [Benchmark] public uint CityHashNet() => CityHash.CityHash.CityHash32(dataStr); [Benchmark] public byte[] HFCityHash() => hcity.ComputeHash(data); [Benchmark] public byte[] SpookyHash() => Spooky.ComputeHash(data); [Benchmark] public unsafe uint Spookily() { fixed (byte* buffer = data) { return SpookilySharp.SpookyHash.Hash32(buffer, data.Length, 0); } } #endif } }
mit
C#
97a4d00d0fe6b8d550a5c31dd2abea5694433243
Update AdjacencyMatrix.cs
nabaird/Unity-Pathfinding-
Horizontal%20Movement/PathingNodes/AdjacencyMatrix.cs
Horizontal%20Movement/PathingNodes/AdjacencyMatrix.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class AdjacencyMatrix : MonoBehaviour { public class vertex { public GameObject node; public float weight; public vertex(GameObject n, float w) { node = n; weight = w; } } public List<vertex> aMatrix; public GameObject[] allNodes; public List<GameObject> test; public int index; public void GenerateMatrix() { allNodes = GameObject.Find("Nodes").GetComponent<AllNodes>().NodeList; aMatrix = new List<vertex>(); foreach (GameObject node in allNodes) { float distance = Vector3.Distance(node.transform.position, transform.position);//the weight is the distance in unity between nodes if (node != this) { RaycastHit hit;//We use raycasting to see which nodes within view of other nodes if (Physics.Raycast(transform.position, Vector3.Normalize(node.transform.position - transform.position), out hit)) { if (hit.collider == node.GetComponent<Collider>()) { aMatrix.Add(new vertex(node, distance)); } } } } test = new List<GameObject>(); foreach (vertex v in aMatrix) { test.Add(v.node); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class AdjacencyMatrix : MonoBehaviour { public class vertex { public GameObject node; public float weight; public vertex(GameObject n, float w) { node = n; weight = w; } } public List<vertex> aMatrix; public GameObject[] allNodes; public List<GameObject> test; public int index; public void GenerateMatrix() { allNodes = GameObject.Find("Nodes").GetComponent<AllNodes>().NodeList; aMatrix = new List<vertex>(); foreach (GameObject node in allNodes) { float distance = Vector3.Distance(node.transform.position, transform.position);//the weight is the distance in unity between nodes if (node != this) { RaycastHit hit;//We use raycasting to see which nodes within view of other nodes if (Physics.Raycast(transform.position, Vector3.Normalize(node.transform.position - transform.position), out hit)) { if (hit.collider == node.GetComponent<Collider>()) { aMatrix.Add(new vertex(node, distance)); } } } } test = new List<GameObject>(); foreach (vertex v in aMatrix) { test.Add(v.node); } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
ce9c323d5d134f6cb7ff9fb0d8cff6e4a3eaef73
Enable jsonCamelCase option
gregmac/NServiceMVC.Examples.Todomvc,gregmac/NServiceMVC.Examples.Todomvc
NServiceMVC.Examples.Todomvc/App_Start/NServiceMVC.cs
NServiceMVC.Examples.Todomvc/App_Start/NServiceMVC.cs
using System.Web.Mvc; using System.Web.Routing; using System.Reflection; using NServiceMVC; [assembly: WebActivator.PreApplicationStartMethod(typeof(NServiceMVC.Examples.Todomvc.App_Start.NServiceMVCActivator), "Start")] namespace NServiceMVC.Examples.Todomvc.App_Start { public static class NServiceMVCActivator { public static void Start() { NServiceMVC.Initialize(config => { // Register all controllers in this project (Remember, controllers must extend NServiceMVC.ServiceController!) config.RegisterControllerAssembly(Assembly.GetExecutingAssembly()); // Register all models in the Models namespace of this project: config.RegisterModelAssembly(Assembly.GetExecutingAssembly(), "NServiceMVC.Examples.Todomvc.Models"); // expose metadata at ~/metadata config.Metadata("metadata"); config.JsonCamelCase = true; }); } } }
using System.Web.Mvc; using System.Web.Routing; using System.Reflection; using NServiceMVC; [assembly: WebActivator.PreApplicationStartMethod(typeof(NServiceMVC.Examples.Todomvc.App_Start.NServiceMVCActivator), "Start")] namespace NServiceMVC.Examples.Todomvc.App_Start { public static class NServiceMVCActivator { public static void Start() { NServiceMVC.Initialize(config => { // Register all controllers in this project (Remember, controllers must extend NServiceMVC.ServiceController!) config.RegisterControllerAssembly(Assembly.GetExecutingAssembly()); // Register all models in the Models namespace of this project: config.RegisterModelAssembly(Assembly.GetExecutingAssembly(), "NServiceMVC.Examples.Todomvc.Models"); // expose metadata at ~/metadata config.Metadata("metadata"); }); } } }
mit
C#
5a9de9d039042c6d56e3700b43932cf164f240c3
Fix mono bug in the FontHelper class
chrisvire/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,ermshiperete/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,JohnThomson/libpalaso,chrisvire/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,marksvc/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,marksvc/libpalaso,hatton/libpalaso,ddaspit/libpalaso,marksvc/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,JohnThomson/libpalaso,hatton/libpalaso,hatton/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso
PalasoUIWindowsForms.Tests/FontTests/FontHelperTests.cs
PalasoUIWindowsForms.Tests/FontTests/FontHelperTests.cs
using System; using System.Drawing; using System.Linq; using NUnit.Framework; using Palaso.UI.WindowsForms; namespace PalasoUIWindowsForms.Tests.FontTests { [TestFixture] public class FontHelperTests { [Test] public void MakeFont_FontName_ValidFont() { using (var sourceFont = SystemFonts.DefaultFont) { using (var returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name)) { Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name); } } } [Test] public void MakeFont_FontNameAndStyle_ValidFont() { // use Times New Roman foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman")) { using (var sourceFont = new Font(family, 10f, FontStyle.Regular)) { using (var returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold)) { Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name); Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold); } } break; } } } }
using System; using System.Drawing; using NUnit.Framework; using Palaso.UI.WindowsForms; namespace PalasoUIWindowsForms.Tests.FontTests { [TestFixture] public class FontHelperTests { [SetUp] public void SetUp() { // setup code goes here } [TearDown] public void TearDown() { // tear down code goes here } [Test] public void MakeFont_FontName_ValidFont() { Font sourceFont = SystemFonts.DefaultFont; Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name); Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name); } } }
mit
C#
0ce53bd396a8914e58f3fdea23af703187f03b08
Implement the MoveNodesAsync method.
AlexGhiondea/SmugMug.NET
src/SmugMugModel.v2/Types/Entities/Node/Node.manual.cs
src/SmugMugModel.v2/Types/Entities/Node/Node.manual.cs
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using SmugMug.v2.Authentication; using System.Collections.Generic; using System.Linq; using SmugMug.v2.Utility; namespace SmugMug.v2.Types { public partial class NodeEntity : SmugMugEntity { public async Task<AlbumEntity> Considered_Fixup_album___() { // /album/(*) return await album___(string.Empty); } public async Task<FolderEntity> GetFolderByIdAsync() { // /folder/id/(*) return await folderid___(NodeID); } public async Task<ImageEntity> GetHighlightImageAsync() { // /highlight/node/(*) return await highlightnode___(NodeID); } public async Task<NodeEntity[]> GetChildrenAsync() { // /node/(*)!children return await node____children(NodeID); } public async Task<GrantEntity[]> GetGrantsAsync() { // /node/(*)!grants return await node____grants(NodeID); } public async Task MoveNodesAsync(IEnumerable<NodeEntity> nodes, bool asyncMove, bool autoRename = true) { var nodeUris = nodes.Select(node => node.Uri).ToArray(); var postProperties = new List<KeyValuePair<string, object>>(); postProperties.Add(new KeyValuePair<string, object>("Async", asyncMove)); postProperties.Add(new KeyValuePair<string, object>("AutoRename", autoRename)); postProperties.Add(new KeyValuePair<string, object>("MoveUris", nodeUris)); var payload = JsonHelpers.GetPayloadAsJson(postProperties); string requestUri = string.Format("{0}/node/{1}!movenodes", SmugMug.v2.Constants.Addresses.SmugMugApi, NodeID); await PostRequestAsync(requestUri, payload); } public async Task<NodeEntity> GetParentAsync() { // /node/(*)!parent return await node____parent(NodeID); } public async Task<NodeEntity[]> GetParents() { // /node/(*)!parents return await node____parents(NodeID); } //public async Task<UserEntity> Fixup_user___() //{ // // /user/(*) // return await user___(string.Empty); //} } }
// Copyright (c) Alex Ghiondea. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using SmugMug.v2.Authentication; namespace SmugMug.v2.Types { public partial class NodeEntity : SmugMugEntity { public async Task<AlbumEntity> Considered_Fixup_album___() { // /album/(*) return await album___(string.Empty); } public async Task<FolderEntity> GetFolderByIdAsync() { // /folder/id/(*) return await folderid___(NodeID); } public async Task<ImageEntity> GetHighlightImageAsync() { // /highlight/node/(*) return await highlightnode___(NodeID); } public async Task<NodeEntity[]> GetChildrenAsync() { // /node/(*)!children return await node____children(NodeID); } public async Task<GrantEntity[]> GetGrantsAsync() { // /node/(*)!grants return await node____grants(NodeID); } public async Task RequiresPost_Fixup_node____movenodes() { // /node/(*)!movenodes await node____movenodes(string.Empty); } public async Task<NodeEntity> GetParentAsync() { // /node/(*)!parent return await node____parent(NodeID); } public async Task<NodeEntity[]> GetParents() { // /node/(*)!parents return await node____parents(NodeID); } //public async Task<UserEntity> Fixup_user___() //{ // // /user/(*) // return await user___(string.Empty); //} } }
mit
C#
9ffd3a2a1b9f1b70b6e7f97f788d5f0fd5a572a2
Update FormulaParser.cs
Excel-DNA/IntelliSense
Source/ExcelDna.IntelliSense/UIMonitor/FormulaParser.cs
Source/ExcelDna.IntelliSense/UIMonitor/FormulaParser.cs
using System; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; namespace ExcelDna.IntelliSense { static class FormulaParser { // Set from IntelliSenseDisplay.Initialize public static char ListSeparator = ','; // TODO: What's the Unicode situation? public static string forbiddenNameCharacters = @"\ /\-:;!@\#\$%\^&\*\(\)\+=,<>\[\]{}|'\"""; public static string functionNameRegex = "[" + forbiddenNameCharacters + "](?<functionName>[^" + forbiddenNameCharacters + "]*)$"; public static string functionNameGroupName = "functionName"; internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex) { Debug.Assert(formulaPrefix != null); if (formulaPrefix.Count(c => c == '\"') % 2 != 0) { formulaPrefix = string.Concat(formulaPrefix, '\"'); } formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty); while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)")) { formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty); } int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal); if (lastOpeningParenthesis > -1) { var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), functionNameRegex); if (match.Success) { functionName = match.Groups[functionNameGroupName].Value; currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator); return true; } } functionName = null; currentArgIndex = -1; return false; } } }
using System; using System.Diagnostics; using System.Linq; using System.Text.RegularExpressions; namespace ExcelDna.IntelliSense { static class FormulaParser { // Set from IntelliSenseDisplay.Initialize public static char ListSeparator = ','; // TODO: What's the Unicode situation? public static string forbiddenNameCharacters = @"\ /\-:;!@\#\$%\^&\*\(\)\+=,<>\[\]{}|'\"""; public static string functionNameRegex = "[" + forbiddenNameCharacters + "](?<functionName>[^" + forbiddenNameCharacters + "]*)$"; public static string functionNameGroupName = "functionName"; internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex) { Debug.Assert(formulaPrefix != null); formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty); while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)")) { formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty); } int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal); if (lastOpeningParenthesis > -1) { var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), functionNameRegex); if (match.Success) { functionName = match.Groups[functionNameGroupName].Value; currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator); return true; } } functionName = null; currentArgIndex = -1; return false; } } }
mit
C#
d040870607b98846bd782e958041474f75dac5c9
add some delay to async void calls to give the disk time to catchup
RoninWest/Ronin.ML
Ronin.ML.Classifier.Test/TestClassifierDataInMongoDB.cs
Ronin.ML.Classifier.Test/TestClassifierDataInMongoDB.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ronin.ML.Classifier.Test { public class TestClassifierDataInMongoDB<F, C> : ClassifierDataInMongoDB<F, C> { public TestClassifierDataInMongoDB() : base("mongodb://localhost/test_" + DateTime.UtcNow.Ticks) { } public override void IncrementCategory(C cat) { base.IncrementCategory(cat); Thread.Sleep(3); //give time for the FS to catch up } public override void IncrementFeature(F feat, C cat) { base.IncrementFeature(feat, cat); Thread.Sleep(3); //give time for the FS to catch up } public override void RemoveCategory(C cat) { base.RemoveCategory(cat); Thread.Sleep(20); //give time for the FS to catch up } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ronin.ML.Classifier.Test { public class TestClassifierDataInMongoDB<F, C> : ClassifierDataInMongoDB<F, C> { public TestClassifierDataInMongoDB() : base("mongodb://localhost/test_" + DateTime.UtcNow.Ticks) { } } }
agpl-3.0
C#
79f82f52eb67f8ab3b137cb381cd4a35d39fa87f
Remove caching from ImmutableSortedSet.Builder.DebuggerProxy
the-dwyer/corefx,axelheer/corefx,nchikanov/corefx,tijoytom/corefx,gkhanna79/corefx,tijoytom/corefx,Ermiar/corefx,tijoytom/corefx,jlin177/corefx,rubo/corefx,mazong1123/corefx,billwert/corefx,the-dwyer/corefx,stone-li/corefx,rubo/corefx,richlander/corefx,jlin177/corefx,gkhanna79/corefx,twsouthwick/corefx,nchikanov/corefx,DnlHarvey/corefx,mmitche/corefx,dotnet-bot/corefx,Jiayili1/corefx,axelheer/corefx,dotnet-bot/corefx,ericstj/corefx,alexperovich/corefx,JosephTremoulet/corefx,ViktorHofer/corefx,the-dwyer/corefx,yizhang82/corefx,Jiayili1/corefx,billwert/corefx,ptoonen/corefx,mazong1123/corefx,krytarowski/corefx,ericstj/corefx,parjong/corefx,ravimeda/corefx,stone-li/corefx,gkhanna79/corefx,shimingsg/corefx,mmitche/corefx,nbarbettini/corefx,krytarowski/corefx,ravimeda/corefx,fgreinacher/corefx,billwert/corefx,ericstj/corefx,zhenlan/corefx,dotnet-bot/corefx,DnlHarvey/corefx,parjong/corefx,mmitche/corefx,twsouthwick/corefx,cydhaselton/corefx,gkhanna79/corefx,zhenlan/corefx,zhenlan/corefx,mazong1123/corefx,ptoonen/corefx,BrennanConroy/corefx,ViktorHofer/corefx,parjong/corefx,cydhaselton/corefx,the-dwyer/corefx,tijoytom/corefx,axelheer/corefx,richlander/corefx,jlin177/corefx,krk/corefx,nchikanov/corefx,mmitche/corefx,krk/corefx,MaggieTsang/corefx,BrennanConroy/corefx,jlin177/corefx,alexperovich/corefx,krk/corefx,JosephTremoulet/corefx,ravimeda/corefx,gkhanna79/corefx,JosephTremoulet/corefx,fgreinacher/corefx,krytarowski/corefx,ptoonen/corefx,nbarbettini/corefx,seanshpark/corefx,wtgodbe/corefx,ViktorHofer/corefx,zhenlan/corefx,shimingsg/corefx,the-dwyer/corefx,Jiayili1/corefx,nbarbettini/corefx,shimingsg/corefx,ViktorHofer/corefx,Ermiar/corefx,zhenlan/corefx,ericstj/corefx,axelheer/corefx,ViktorHofer/corefx,seanshpark/corefx,yizhang82/corefx,stone-li/corefx,cydhaselton/corefx,mazong1123/corefx,BrennanConroy/corefx,billwert/corefx,ViktorHofer/corefx,wtgodbe/corefx,krytarowski/corefx,stone-li/corefx,Ermiar/corefx,ptoonen/corefx,the-dwyer/corefx,nchikanov/corefx,mazong1123/corefx,krk/corefx,krytarowski/corefx,krk/corefx,MaggieTsang/corefx,ericstj/corefx,twsouthwick/corefx,ravimeda/corefx,stone-li/corefx,nbarbettini/corefx,DnlHarvey/corefx,DnlHarvey/corefx,richlander/corefx,fgreinacher/corefx,wtgodbe/corefx,krk/corefx,JosephTremoulet/corefx,ravimeda/corefx,mmitche/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,MaggieTsang/corefx,MaggieTsang/corefx,wtgodbe/corefx,mazong1123/corefx,zhenlan/corefx,MaggieTsang/corefx,jlin177/corefx,DnlHarvey/corefx,yizhang82/corefx,DnlHarvey/corefx,axelheer/corefx,the-dwyer/corefx,twsouthwick/corefx,billwert/corefx,Jiayili1/corefx,rubo/corefx,dotnet-bot/corefx,jlin177/corefx,shimingsg/corefx,twsouthwick/corefx,cydhaselton/corefx,nchikanov/corefx,stone-li/corefx,alexperovich/corefx,alexperovich/corefx,dotnet-bot/corefx,ptoonen/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,MaggieTsang/corefx,Ermiar/corefx,seanshpark/corefx,nchikanov/corefx,shimingsg/corefx,ravimeda/corefx,JosephTremoulet/corefx,tijoytom/corefx,nbarbettini/corefx,wtgodbe/corefx,yizhang82/corefx,shimingsg/corefx,ericstj/corefx,Jiayili1/corefx,rubo/corefx,fgreinacher/corefx,yizhang82/corefx,MaggieTsang/corefx,ptoonen/corefx,krk/corefx,richlander/corefx,cydhaselton/corefx,gkhanna79/corefx,parjong/corefx,Jiayili1/corefx,seanshpark/corefx,mmitche/corefx,nbarbettini/corefx,rubo/corefx,mmitche/corefx,nchikanov/corefx,tijoytom/corefx,Ermiar/corefx,ViktorHofer/corefx,cydhaselton/corefx,parjong/corefx,zhenlan/corefx,tijoytom/corefx,ravimeda/corefx,seanshpark/corefx,shimingsg/corefx,cydhaselton/corefx,dotnet-bot/corefx,parjong/corefx,seanshpark/corefx,richlander/corefx,wtgodbe/corefx,Jiayili1/corefx,richlander/corefx,wtgodbe/corefx,Ermiar/corefx,seanshpark/corefx,ericstj/corefx,ptoonen/corefx,nbarbettini/corefx,billwert/corefx,billwert/corefx,krytarowski/corefx,Ermiar/corefx,krytarowski/corefx,jlin177/corefx,stone-li/corefx,alexperovich/corefx,yizhang82/corefx,gkhanna79/corefx,axelheer/corefx,yizhang82/corefx,richlander/corefx,alexperovich/corefx,twsouthwick/corefx,alexperovich/corefx,twsouthwick/corefx,mazong1123/corefx,parjong/corefx
src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.DebuggerProxy.cs
src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.DebuggerProxy.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Collections.Immutable { /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableSortedSetBuilderDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedSet<T>.Builder _set; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSetBuilderDebuggerProxy{T}"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public ImmutableSortedSetBuilderDebuggerProxy(ImmutableSortedSet<T>.Builder builder) { Requires.NotNull(builder, nameof(builder)); _set = builder; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { return _set.ToArray(_set.Count); ; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Collections.Immutable { /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableSortedSetBuilderDebuggerProxy<T> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedSet<T>.Builder _set; /// <summary> /// The simple view of the collection. /// </summary> private T[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSetBuilderDebuggerProxy{T}"/> class. /// </summary> /// <param name="builder">The collection to display in the debugger</param> public ImmutableSortedSetBuilderDebuggerProxy(ImmutableSortedSet<T>.Builder builder) { Requires.NotNull(builder, nameof(builder)); _set = builder; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Contents { get { if (_contents == null) { _contents = _set.ToArray(_set.Count); } return _contents; } } } }
mit
C#
cd8edb7db83d96fe39daa293b3e0b95c80742e83
Standardize the AssemblyInfo
Jericho/CakeMail.RestClient
Source/CakeMail.RestClient/Properties/AssemblyInfo.cs
Source/CakeMail.RestClient/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Make it easy to distinguish Debug and Release builds; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("DDCD8C73-3E02-45CC-958F-1E0383D6EB91")]
using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CakeMail.RestClient")] [assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Jeremie Desautels")] [assembly: AssemblyProduct("CakeMail.RestClient")] [assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")]
mit
C#
cdaff8b6b895c0fdfd916b15d9a0a389f5f44af5
Update base exception documentation.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Exceptions/TraktException.cs
Source/Lib/TraktApiSharp/Exceptions/TraktException.cs
namespace TraktApiSharp.Exceptions { using System; using System.Net; /// <summary> /// Base class for all TraktApiSharp exceptions.<para /> /// Can contain additional information like the response's status code, the request's url, a reason phrase of the server, /// the request body, if it was a post or put request and the actual response content. /// </summary> public class TraktException : Exception { public TraktException(string message) : base(message) { } public TraktException(string message, Exception innerException) : base(message, innerException) { } /// <summary>Returns the response's status code.</summary> public HttpStatusCode StatusCode { get; internal set; } /// <summary>Gets or sets the request's url.</summary> public string RequestUrl { get; set; } /// <summary>Gets or sets the request body.</summary> public string RequestBody { get; set; } /// <summary>Gets or sets the response content.</summary> public string Response { get; set; } /// <summary>Gets or sets the server reason phrase.</summary> public string ServerReasonPhrase { get; set; } } }
namespace TraktApiSharp.Exceptions { using System; using System.Net; /// <summary> /// Base class for all TraktApiSharp exceptions.<para /> /// Can contain additional information like the response's status code, the request's url, a reason phrase of the server, /// the request body, if it was a post or put request and the actual response content. /// </summary> public class TraktException : Exception { public TraktException(string message) : base(message) { } public TraktException(string message, Exception innerException) : base(message, innerException) { } public HttpStatusCode StatusCode { get; internal set; } /// <summary>Gets or sets the request's url.</summary> public string RequestUrl { get; set; } /// <summary>Gets or sets the request body.</summary> public string RequestBody { get; set; } /// <summary>Gets or sets the response content.</summary> public string Response { get; set; } /// <summary>Gets or sets the server reason phrase.</summary> public string ServerReasonPhrase { get; set; } } }
mit
C#
1233fd30da3263d173e97d0b7b2c3c427e1a096f
Rename CreateResourceKey
JohanLarsson/SkinBox
SkinBox.Controls/Keys.cs
SkinBox.Controls/Keys.cs
using System.Windows.Input; namespace SkinBox.Controls { using System.Runtime.CompilerServices; using System.Windows; public static class Keys { public static ResourceKey BackgroundBrushKey { get; } = CreateResourceKey(); public static ResourceKey CustomControlTemplateKey { get; } = CreateResourceKey(); public static ResourceKey BlueSkinKey { get; } = CreateResourceKey(); public static ICommand SetBlueSkinCommand { get; } = new ChangeSkinCommand(BlueSkinKey); public static ResourceKey YellowSkinKey { get; } = CreateResourceKey(); public static ICommand SetYellowSkinCommand { get; } = new ChangeSkinCommand(YellowSkinKey); private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null) { return new ComponentResourceKey(typeof(Keys), caller); ; } } }
using System.Windows.Input; namespace SkinBox.Controls { using System.Runtime.CompilerServices; using System.Windows; public static class Keys { public static ResourceKey BackgroundBrushKey { get; } = Get(); public static ResourceKey CustomControlTemplateKey { get; } = Get(); public static ResourceKey BlueSkinKey { get; } = Get(); public static ICommand SetBlueSkinCommand { get; } = new ChangeSkinCommand(BlueSkinKey); public static ResourceKey YellowSkinKey { get; } = Get(); public static ICommand SetYellowSkinCommand { get; } = new ChangeSkinCommand(YellowSkinKey); private static ComponentResourceKey Get([CallerMemberName] string caller = null) { return new ComponentResourceKey(typeof(Keys), caller); ; } } }
mit
C#
c08e5bf06497979ea0f3387a282cc4d2ad90cf9d
Fix typo with AuthorizationCodeRequestBase (#437)
auth0/auth0.net,auth0/auth0.net
src/Auth0.AuthenticationApi/Models/AuthorizationCodeRequestBase.cs
src/Auth0.AuthenticationApi/Models/AuthorizationCodeRequestBase.cs
namespace Auth0.AuthenticationApi.Models { /// <summary> /// Base class for all types of Authorization Code requests. /// </summary> public abstract class AuthorizationCodeRequestBase { /// <summary> /// Authorization code to be exchanged. /// </summary> public string Code { get; set; } /// <summary> /// Client ID of the application. /// </summary> public string ClientId { get; set; } /// <summary> /// What <see cref="JwtSignatureAlgorithm"/> is used to verify the signature /// of Id Tokens. /// </summary> public JwtSignatureAlgorithm SigningAlgorithm { get; set; } /// <summary> /// Redirect URI passed during the login process. /// </summary> public string RedirectUri { get; set; } /// <summary> /// Client secret of the application for Id Token verification. /// </summary> /// <remarks> /// Optional except when using <see cref="AuthorizationCodeRequestBase"/>. /// </remarks> public string ClientSecret { get; set; } } }
namespace Auth0.AuthenticationApi.Models { /// <summary> /// Base class for all types of Authorization Code requests. /// </summary> public abstract class AuthorizationCodeRequestBase { /// <summary> /// Authorization code to be exchanged. /// </summary> public string Code { get; set; } /// <summary> /// Client ID of the application. /// </summary> public string ClientId { get; set; } /// <summary> /// What <see cref="JwtSignatureAlgorithm"/> is used to verify the signature /// of Id Tokens. /// </summary> public JwtSignatureAlgorithm SigningAlgorithm { get; set; } /// <summary> /// Rredirect URI passed during the login process. /// </summary> public string RedirectUri { get; set; } /// <summary> /// Client secret of the application for Id Token verification. /// </summary> /// <remarks> /// Optional except when using <see cref="AuthorizationCodeRequestBase"/>. /// </remarks> public string ClientSecret { get; set; } } }
mit
C#
d46fd7dfe176ff043d8b7881e0304529430a14c0
Fix bug in CompilationCSharpDiagnostic
riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy
src/DotvvmAcademy.Validation.CSharp/CompilationCSharpDiagnostic.cs
src/DotvvmAcademy.Validation.CSharp/CompilationCSharpDiagnostic.cs
using Microsoft.CodeAnalysis; namespace DotvvmAcademy.Validation.CSharp { public class CompilationCSharpDiagnostic : IValidationDiagnostic { public CompilationCSharpDiagnostic(Diagnostic diagnostic, CSharpSourceCode source) { Diagnostic = diagnostic; Source = source; Message = diagnostic.GetMessage(); Severity = diagnostic.Severity.ToValidationSeverity(); } public Diagnostic Diagnostic { get; } public int End => Diagnostic.Location.SourceSpan.End; public string Message { get; } public ValidationSeverity Severity { get; } public int Start => Diagnostic.Location.SourceSpan.Start; public CSharpSourceCode Source { get; } ISourceCode IValidationDiagnostic.Source => Source; object IValidationDiagnostic.UnderlyingObject => Diagnostic; } }
using Microsoft.CodeAnalysis; namespace DotvvmAcademy.Validation.CSharp { public class CompilationCSharpDiagnostic : IValidationDiagnostic { public CompilationCSharpDiagnostic(Diagnostic diagnostic, CSharpSourceCode source) { Diagnostic = diagnostic; Source = source; Message = diagnostic.GetMessage(); Severity = diagnostic.Severity.ToValidationSeverity(); } public Diagnostic Diagnostic { get; } public int End => Diagnostic.Location.SourceSpan.Start; public string Message { get; } public ValidationSeverity Severity { get; } public int Start => Diagnostic.Location.SourceSpan.End; public CSharpSourceCode Source { get; } ISourceCode IValidationDiagnostic.Source => Source; object IValidationDiagnostic.UnderlyingObject => Diagnostic; } }
apache-2.0
C#
223541cf6a7f30c3dbec8a975f3a842f8a0f7f0f
Fix comment grammar (#31326)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Http/Authentication.Abstractions/src/IAuthenticationHandler.cs
src/Http/Authentication.Abstractions/src/IAuthenticationHandler.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Created per request to handle authentication for a particular scheme. /// </summary> public interface IAuthenticationHandler { /// <summary> /// Initialize the authentication handler. The handler should initialize anything it needs from the request and scheme as part of this method. /// </summary> /// <param name="scheme">The <see cref="AuthenticationScheme"/> scheme.</param> /// <param name="context">The <see cref="HttpContext"/> context.</param> Task InitializeAsync(AuthenticationScheme scheme, HttpContext context); /// <summary> /// Authenticate the current request. /// </summary> /// <returns>The <see cref="AuthenticateResult"/> result.</returns> Task<AuthenticateResult> AuthenticateAsync(); /// <summary> /// Challenge the current request. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/> that contains the extra meta-data arriving with the authentication.</param> Task ChallengeAsync(AuthenticationProperties? properties); /// <summary> /// Forbid the current request. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/> that contains the extra meta-data arriving with the authentication.</param> Task ForbidAsync(AuthenticationProperties? properties); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Created per request to handle authentication for to a particular scheme. /// </summary> public interface IAuthenticationHandler { /// <summary> /// Initialize the authentication handler. The handler should initialize anything it needs from the request and scheme as part of this method. /// </summary> /// <param name="scheme">The <see cref="AuthenticationScheme"/> scheme.</param> /// <param name="context">The <see cref="HttpContext"/> context.</param> Task InitializeAsync(AuthenticationScheme scheme, HttpContext context); /// <summary> /// Authenticate the current request. /// </summary> /// <returns>The <see cref="AuthenticateResult"/> result.</returns> Task<AuthenticateResult> AuthenticateAsync(); /// <summary> /// Challenge the current request. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/> that contains the extra meta-data arriving with the authentication.</param> Task ChallengeAsync(AuthenticationProperties? properties); /// <summary> /// Forbid the current request. /// </summary> /// <param name="properties">The <see cref="AuthenticationProperties"/> that contains the extra meta-data arriving with the authentication.</param> Task ForbidAsync(AuthenticationProperties? properties); } }
apache-2.0
C#
318e8075ca22f98f54dcb20ea06a8e8d06b4d139
Bump version
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
configuration/SharedAssemblyInfo.cs
configuration/SharedAssemblyInfo.cs
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-rc1")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-beta10")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
mit
C#
e098dbf01b900378b92ca8ba20d05d5bb25d9b59
Refactor to GetOverrideTargetName()
corngood/omnisharp-server,OmniSharp/omnisharp-server,svermeulen/omnisharp-server,mispencer/OmniSharpServer,x335/omnisharp-server,corngood/omnisharp-server,syl20bnr/omnisharp-server,syl20bnr/omnisharp-server,x335/omnisharp-server
OmniSharp/AutoComplete/Overrides/GetOverrideTargetsResponse.cs
OmniSharp/AutoComplete/Overrides/GetOverrideTargetsResponse.cs
using System; using System.Collections.Generic; using ICSharpCode.NRefactory.CSharp.Refactoring; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.CSharp.TypeSystem; using ICSharpCode.NRefactory.TypeSystem; using OmniSharp.AutoComplete.Overrides; namespace OmniSharp.AutoComplete.Overrides { public class GetOverrideTargetsResponse { public GetOverrideTargetsResponse() {} public GetOverrideTargetsResponse ( IMember m , CSharpTypeResolveContext resolveContext) { if (resolveContext == null) throw new ArgumentNullException("resolveContext"); if (m == null) throw new ArgumentNullException("m"); this.OverrideTargetName = GetOverrideTargetName(m, resolveContext); } /// <summary> /// A human readable signature of the member that is to be /// overridden. /// </summary> public string OverrideTargetName {get; set;} public static string GetOverrideTargetName (IMember m, CSharpTypeResolveContext resolveContext) { var builder = new TypeSystemAstBuilder (new CSharpResolver(resolveContext)); return builder.ConvertEntity(m).GetText() // Builder automatically adds a trailing newline .TrimEnd(Environment.NewLine.ToCharArray()); } } }
using System; using System.Collections.Generic; using ICSharpCode.NRefactory.CSharp.Refactoring; using ICSharpCode.NRefactory.CSharp.Resolver; using ICSharpCode.NRefactory.CSharp.TypeSystem; using ICSharpCode.NRefactory.TypeSystem; using OmniSharp.AutoComplete.Overrides; namespace OmniSharp.AutoComplete.Overrides { public class GetOverrideTargetsResponse { public GetOverrideTargetsResponse() {} public GetOverrideTargetsResponse ( IMember m , CSharpTypeResolveContext resolveContext) { if (resolveContext == null) throw new ArgumentNullException("resolveContext"); if (m == null) throw new ArgumentNullException("m"); var builder = new TypeSystemAstBuilder (new CSharpResolver(resolveContext)); this.OverrideTargetName = builder.ConvertEntity(m).GetText() // Builder automatically adds a trailing newline .TrimEnd(Environment.NewLine.ToCharArray()); } /// <summary> /// A human readable signature of the member that is to be /// overridden. /// </summary> public string OverrideTargetName {get; set;} } }
mit
C#
87f7c7e6915757752a6b978cbf5ca859bc03368f
Implement scoreboard-specific time formatting
peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu
osu.Game/Overlays/BeatmapSet/Scores/ScoreboardTime.cs
osu.Game/Overlays/BeatmapSet/Scores/ScoreboardTime.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using Humanizer; using osu.Game.Graphics; using osu.Game.Resources.Localisation.Web; namespace osu.Game.Overlays.BeatmapSet.Scores { public class ScoreboardTime : DrawableDate { public ScoreboardTime(DateTimeOffset date, float textSize = OsuFont.DEFAULT_FONT_SIZE, bool italic = true) : base(date, textSize, italic) { } protected override string Format() { var now = DateTime.Now; var difference = now - Date; // web uses momentjs's custom locales to format the date for the purposes of the scoreboard. // this is intended to be a best-effort, more legible approximation of that. // compare: // * https://github.com/ppy/osu-web/blob/a8f5a68fb435cb19a4faa4c7c4bce08c4f096933/resources/assets/lib/scoreboard-time.tsx // * https://momentjs.com/docs/#/customization/ (reference for the customisation format) // TODO: support localisation (probably via `CommonStrings.CountHours()` etc.) // requires pluralisable string support framework-side if (difference.TotalHours < 1) return CommonStrings.TimeNow.ToString(); if (difference.TotalDays < 1) return "hr".ToQuantity((int)difference.TotalHours); // this is where this gets more complicated because of how the calendar works. // since there's no `TotalMonths` / `TotalYears`, we have to iteratively add months/years // and test against cutoff dates to determine how many months/years to show. if (Date > now.AddMonths(-1)) return difference.TotalDays < 2 ? "1dy" : $"{(int)difference.TotalDays}dys"; for (int months = 1; months <= 11; ++months) { if (Date > now.AddMonths(-(months + 1))) return months == 1 ? "1mo" : $"{months}mos"; } int years = 1; while (Date <= now.AddYears(-(years + 1))) years += 1; return years == 1 ? "1yr" : $"{years}yrs"; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Graphics; namespace osu.Game.Overlays.BeatmapSet.Scores { public class ScoreboardTime : DrawableDate { public ScoreboardTime(DateTimeOffset date, float textSize = OsuFont.DEFAULT_FONT_SIZE, bool italic = true) : base(date, textSize, italic) { } protected override string Format() { return base.Format(); } } }
mit
C#
ce2e4cf47d4edcb357630d0f8db8732cf16e6ad8
Add some default values for StitchConfiguration
Whiteknight/CrossStitch,Whiteknight/CrossStitch
Src/CrossStitch.Core/Modules/Stitches/StitchesConfiguration.cs
Src/CrossStitch.Core/Modules/Stitches/StitchesConfiguration.cs
using CrossStitch.Core.Configuration; namespace CrossStitch.Core.Modules.Stitches { public class StitchesConfiguration : IModuleConfiguration { public static StitchesConfiguration GetDefault() { return ConfigurationLoader.GetConfiguration<StitchesConfiguration>("stitches.json"); } public string DataBasePath { get; set; } public string AppLibraryBasePath { get; set; } public string RunningAppBasePath { get; set; } public void ValidateAndSetDefaults() { if (string.IsNullOrEmpty(DataBasePath)) DataBasePath = ".\\StitchData"; if (string.IsNullOrEmpty(AppLibraryBasePath)) AppLibraryBasePath = ".\\StitchLibrary"; if (string.IsNullOrEmpty(RunningAppBasePath)) RunningAppBasePath = ".\\RunningStitches"; } } }
using CrossStitch.Core.Configuration; namespace CrossStitch.Core.Modules.Stitches { public class StitchesConfiguration : IModuleConfiguration { public static StitchesConfiguration GetDefault() { return ConfigurationLoader.GetConfiguration<StitchesConfiguration>("stitches.json"); } public string DataBasePath { get; set; } public string AppLibraryBasePath { get; set; } public string RunningAppBasePath { get; set; } public void ValidateAndSetDefaults() { } } }
apache-2.0
C#
df1a3db785e11281b6e4ea23c1ae7a14deb11036
Remove unexpected whitespace
jlewin/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl
Tests/MatterControl.AutomationTests/HardwareLevelingUITests.cs
Tests/MatterControl.AutomationTests/HardwareLevelingUITests.cs
using System.Threading; using System.Threading.Tasks; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain, Apartment(ApartmentState.STA)] public class HardwareLevelingUITests { [Test] public async Task HasHardwareLevelingHidesLevelingSettings() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.WaitForFirstDraw(); // Add printer that has hardware leveling testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsFalse(testRunner.WaitForName("print_leveling_solution Row", .5), "Print leveling should not exist for an Airwolf HD"); // Add printer that does not have hardware leveling testRunner.AddAndSelectPrinter("3D Factory", "MendelMax 1.5"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsTrue(testRunner.WaitForName("print_leveling_solution Row"), "Print leveling should exist for a 3D Factory MendelMax"); return Task.CompletedTask; }, overrideHeight: 800); } [Test, Category("Emulator")] public async Task SoftwareLevelingRequiredCorrectWorkflow() { await MatterControlUtilities.RunTest((testRunner) => { // make a jump start printer using (var emulator = testRunner.LaunchAndConnectToPrinterEmulator("JumpStart", "V1", runSlow: false)) { // make sure it is showing the correct button Assert.IsFalse(testRunner.WaitForName("PrintPopupMenu", .5), "Start Print should not be visible if PrintLeveling is required"); Assert.IsTrue(testRunner.WaitForName("Finish Setup Button"), "Finish Setup should be visible if PrintLeveling is required"); testRunner.Complete9StepLeveling(); // make sure the button has changed to start print Assert.IsTrue(testRunner.WaitForName("PrintPopupMenu"), "Start Print should be visible after leveling the printer"); Assert.IsFalse(testRunner.WaitForName("Finish Setup Button", .5), "Finish Setup should not be visible after leveling the printer"); // reset to defaults and make sure print leveling is cleared testRunner.SwitchToSliceSettings(); testRunner.ClickByName("Printer Overflow Menu"); testRunner.ClickByName("Reset to Defaults Menu Item"); testRunner.ClickByName("Yes Button"); // make sure it is showing the correct button Assert.IsTrue(!testRunner.WaitForName("PrintPopupMenu"), "Start Print should be visible after reset to Defaults"); Assert.IsTrue(testRunner.WaitForName("Finish Setup Button"), "Finish Setup should not be visible after reset to Defaults"); } return Task.CompletedTask; }); } } }
using System.Linq; using System.Threading; using System.Threading.Tasks; using MatterHackers.Agg.UI; using MatterHackers.GuiAutomation; using MatterHackers.MatterControl.SlicerConfiguration; using NUnit.Framework; namespace MatterHackers.MatterControl.Tests.Automation { [TestFixture, Category("MatterControl.UI.Automation"), RunInApplicationDomain, Apartment(ApartmentState.STA)] public class HardwareLevelingUITests { [Test] public async Task HasHardwareLevelingHidesLevelingSettings() { await MatterControlUtilities.RunTest((testRunner) => { testRunner.WaitForFirstDraw(); // Add printer that has hardware leveling testRunner.AddAndSelectPrinter("Airwolf 3D", "HD"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsFalse(testRunner.WaitForName("print_leveling_solution Row", .5), "Print leveling should not exist for an Airwolf HD"); // Add printer that does not have hardware leveling testRunner.AddAndSelectPrinter("3D Factory", "MendelMax 1.5"); testRunner.SwitchToPrinterSettings(); testRunner.ClickByName("Features Tab"); testRunner.ClickByName("Slice Settings Overflow Menu"); testRunner.ClickByName("Expand All Menu Item"); Assert.IsTrue(testRunner.WaitForName("print_leveling_solution Row"), "Print leveling should exist for a 3D Factory MendelMax"); return Task.CompletedTask; }, overrideHeight: 800); } [Test, Category("Emulator")] public async Task SoftwareLevelingRequiredCorrectWorkflow() { await MatterControlUtilities.RunTest((testRunner) => { // make a jump start printer using (var emulator = testRunner.LaunchAndConnectToPrinterEmulator("JumpStart", "V1", runSlow: false)) { // make sure it is showing the correct button Assert.IsFalse(testRunner.WaitForName("PrintPopupMenu", .5), "Start Print should not be visible if PrintLeveling is required"); Assert.IsTrue(testRunner.WaitForName("Finish Setup Button"), "Finish Setup should be visible if PrintLeveling is required"); testRunner.Complete9StepLeveling(); // make sure the button has changed to start print Assert.IsTrue(testRunner.WaitForName("PrintPopupMenu"), "Start Print should be visible after leveling the printer"); Assert.IsFalse(testRunner.WaitForName("Finish Setup Button", .5), "Finish Setup should not be visible after leveling the printer"); // reset to defaults and make sure print leveling is cleared testRunner.SwitchToSliceSettings(); testRunner.ClickByName("Printer Overflow Menu"); testRunner.ClickByName("Reset to Defaults Menu Item"); testRunner.ClickByName("Yes Button"); // make sure it is showing the correct button Assert.IsTrue(!testRunner.WaitForName("PrintPopupMenu"), "Start Print should be visible after reset to Defaults"); Assert.IsTrue(testRunner.WaitForName("Finish Setup Button"), "Finish Setup should not be visible after reset to Defaults"); } return Task.CompletedTask; }); } } }
bsd-2-clause
C#
4215499a9c9d61a03013278bf8bebd3bc491d112
Remove unused setting PluralizeResourceTypeNames from JsonApiConfiguration
huysentruitw/simple-json-api
src/SimpleJsonApi/Configuration/JsonApiConfiguration.cs
src/SimpleJsonApi/Configuration/JsonApiConfiguration.cs
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace SimpleJsonApi.Configuration { public sealed class JsonApiConfiguration { public const string JsonApiMediaType = "application/vnd.api+json"; public JsonApiConfiguration() { SerializerSettings.Converters.Add(new IsoDateTimeConverter()); SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); } public string MediaType { get; set; } = JsonApiMediaType; public ResourceConfiguration ResourceConfiguration { get; set; } public JsonSerializerSettings SerializerSettings { get; } = new JsonSerializerSettings(); internal void Validate() { if (string.IsNullOrEmpty(MediaType)) throw new ArgumentNullException(nameof(MediaType)); if (ResourceConfiguration == null) throw new ArgumentNullException(nameof(ResourceConfiguration)); } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace SimpleJsonApi.Configuration { public sealed class JsonApiConfiguration { public const string JsonApiMediaType = "application/vnd.api+json"; public JsonApiConfiguration() { SerializerSettings.Converters.Add(new IsoDateTimeConverter()); SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); } public string MediaType { get; set; } = JsonApiMediaType; public ResourceConfiguration ResourceConfiguration { get; set; } public bool PluralizeResourceTypeNames { get; set; } = true; public JsonSerializerSettings SerializerSettings { get; } = new JsonSerializerSettings(); internal void Validate() { if (string.IsNullOrEmpty(MediaType)) throw new ArgumentNullException(nameof(MediaType)); if (ResourceConfiguration == null) throw new ArgumentNullException(nameof(ResourceConfiguration)); } } }
apache-2.0
C#
0bf1e337b8294a55f24fb625b080de190631a70e
Correct ToString failure
canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor
src/SyncTrayzor/SyncThing/Api/LocalIndexUpdatedEvent.cs
src/SyncTrayzor/SyncThing/Api/LocalIndexUpdatedEvent.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncTrayzor.SyncThing.Api { public class LocalIndexUpdatedEventData { [JsonProperty("flags")] public string Flags { get; set; } [JsonProperty("modified")] public DateTime Modified { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("folder")] public string Folder { get; set; } [JsonProperty("size")] public long Size { get; set; } } public class LocalIndexUpdatedEvent : Event { [JsonProperty("data")] public LocalIndexUpdatedEventData Data { get; set; } public override void Visit(IEventVisitor visitor) { visitor.Accept(this); } public override string ToString() { return String.Format("<LocalIndexUpdated ID={0} Time={1} Flags={2} Modified={3} Name={4} Folder={5} Size={6}>", this.Id, this.Time, this.Data.Flags, this.Data.Modified, this.Data.Name, this.Data.Folder, this.Data.Size); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SyncTrayzor.SyncThing.Api { public class LocalIndexUpdatedEventData { [JsonProperty("flags")] public string Flags { get; set; } [JsonProperty("modified")] public DateTime Modified { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("folder")] public string Folder { get; set; } [JsonProperty("size")] public long Size { get; set; } } public class LocalIndexUpdatedEvent : Event { [JsonProperty("data")] public LocalIndexUpdatedEventData Data { get; set; } public override void Visit(IEventVisitor visitor) { visitor.Accept(this); } public override string ToString() { return String.Format("<LocalIndexUpdated ID={0} Time={1} Flags={2} Modified={3} Name={4} Folder={5} Size={5}>", this.Id, this.Time, this.Data.Flags, this.Data.Modified, this.Data.Name, this.Data.Folder, this.Data.Size); } } }
mit
C#
e30ae8cc3dbe4e59ae999a870c99c7cda9898f77
Fix typo (#1559)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.Extensions.Hosting.Abstractions/IHostLifetime.cs
src/Microsoft.Extensions.Hosting.Abstractions/IHostLifetime.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.Extensions.Hosting { public interface IHostLifetime { /// <summary> /// Called at the start of <see cref="IHost.StartAsync(CancellationToken)"/> which will wait until it's complete before /// continuing. This can be used to delay startup until signaled by an external event. /// </summary> Task WaitForStartAsync(CancellationToken cancellationToken); /// <summary> /// Called from <see cref="IHost.StopAsync(CancellationToken)"/> to indicate that the host as stopped and clean up resources. /// </summary> /// <param name="cancellationToken">Used to indicate when stop should no longer be graceful.</param> /// <returns></returns> Task StopAsync(CancellationToken cancellationToken); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using System.Threading.Tasks; namespace Microsoft.Extensions.Hosting { public interface IHostLifetime { /// <summary> /// Called at the start of <see cref="IHost.StartAsync(CancellationToken)"/> which will wait until it's compete before /// continuing. This can be used to delay startup until signaled by an external event. /// </summary> Task WaitForStartAsync(CancellationToken cancellationToken); /// <summary> /// Called from <see cref="IHost.StopAsync(CancellationToken)"/> to indicate that the host as stopped and clean up resources. /// </summary> /// <param name="cancellationToken">Used to indicate when stop should no longer be graceful.</param> /// <returns></returns> Task StopAsync(CancellationToken cancellationToken); } }
apache-2.0
C#
f04c137e1d1cec7995fa5bba439e0871fe70c741
Edit MenuItem name
kiyoaki/AssetBundleSample,kiyoaki/AssetBundleSample
Assets/AssetBundleBuilder/Editor/AssetBundleClientSettingsEditor.cs
Assets/AssetBundleBuilder/Editor/AssetBundleClientSettingsEditor.cs
using UnityEditor; [CustomEditor(typeof(AssetBundleClientSettings))] public class AssetBundleClientSettingsEditor : SettingsEditorBase<AssetBundleClientSettings> { protected const string SettingsFileName = "AssetBundleClientSettings"; [MenuItem("AssetBundles/Show Settings")] public static void ShowSettings() { var settingsInstance = Load(SettingsFileName) ?? CreateNewAsset(SettingsFileName); if (settingsInstance != null) { Selection.activeObject = settingsInstance; } } }
using UnityEditor; [CustomEditor(typeof(AssetBundleClientSettings))] public class AssetBundleClientSettingsEditor : SettingsEditorBase<AssetBundleClientSettings> { protected const string SettingsFileName = "AssetBundleClientSettings"; [MenuItem("AssetBundles/Show AssetBundleClientSettings")] public static void ShowSettings() { var settingsInstance = Load(SettingsFileName) ?? CreateNewAsset(SettingsFileName); if (settingsInstance != null) { Selection.activeObject = settingsInstance; } } }
mit
C#
82c402d42289faedc5ef3509b16bb77490cb744c
Clean up LessThanorEqualToValidator tests
cecilphillip/FluentValidation,roend83/FluentValidation,regisbsb/FluentValidation,glorylee/FluentValidation,olcayseker/FluentValidation,deluxetiky/FluentValidation,robv8r/FluentValidation,GDoronin/FluentValidation,ruisebastiao/FluentValidation,pacificIT/FluentValidation,roend83/FluentValidation,IRlyDontKnow/FluentValidation,mgmoody42/FluentValidation
src/FluentValidation.Tests/LessThanOrEqualToValidatorTester.cs
src/FluentValidation.Tests/LessThanOrEqualToValidatorTester.cs
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Tests { using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Threading; using Internal; using NUnit.Framework; using Validators; [TestFixture] public class LessThanOrEqualToValidatorTester { private TestValidator validator; private const int value = 1; [SetUp] public void Setup() { validator = new TestValidator(v => v.RuleFor(x => x.Id).LessThanOrEqualTo(value)); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } [Test] public void Should_fail_when_greater_than_input() { var result = validator.Validate(new Person{Id=2}); result.IsValid.ShouldBeFalse(); } [Test] public void Should_succeed_when_less_than_input() { var result = validator.Validate(new Person{Id=0}); result.IsValid.ShouldBeTrue(); } [Test] public void Should_succeed_when_equal_to_input() { var result = validator.Validate(new Person{Id=value}); result.IsValid.ShouldBeTrue(); } [Test] public void Should_set_default_error_when_validation_fails() { var result = validator.Validate(new Person{Id=2}); result.Errors.Single().ErrorMessage.ShouldEqual("'Id' must be less than or equal to '1'."); } [Test] public void Comparison_type() { new LessThanOrEqualValidator(value).Comparison.ShouldEqual(Comparison.LessThanOrEqual); } [Test] public void Validates_with_property() { validator = new TestValidator(v => v.RuleFor(x => x.Id).LessThanOrEqualTo(x => x.AnotherInt)); var result = validator.Validate(new Person {Id = 1, AnotherInt = 0}); result.IsValid.ShouldBeFalse(); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation.Tests { using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Threading; using Internal; using NUnit.Framework; using Validators; [TestFixture] public class LessThanOrEqualToValidatorTester { private LessThanOrEqualValidator validator; private const int value = 1; [SetUp] public void Setup() { validator = new LessThanOrEqualValidator(value); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } [Test] public void Should_fail_when_greater_than_input() { var result = validator.Validate(new PropertyValidatorContext(null, null, x => 2)); result.IsValid().ShouldBeFalse(); } [Test] public void Should_succeed_when_less_than_input() { var result = validator.Validate(new PropertyValidatorContext(null, null, x => 0)); result.IsValid().ShouldBeTrue(); } [Test] public void Should_succeed_when_equal_to_input() { var result = validator.Validate(new PropertyValidatorContext(null, null, x => value)); result.IsValid().ShouldBeTrue(); } [Test] public void Should_set_default_error_when_validation_fails() { var result = validator.Validate(new PropertyValidatorContext("Discount", null, x => 2)); result.Single().ErrorMessage.ShouldEqual("'Discount' must be less than or equal to '1'."); } [Test] public void Comparison_type() { validator.Comparison.ShouldEqual(Comparison.LessThanOrEqual); } [Test] public void Validates_with_property() { validator = CreateValidator(x => x.Id); var result = validator.Validate(new PropertyValidatorContext(null, new Person { Id = 1 }, x => 2)); result.IsValid().ShouldBeFalse(); } private LessThanOrEqualValidator CreateValidator<T>(Expression<PropertySelector<Person, T>> expression) { PropertySelector selector = x => expression.Compile()((Person)x); return new LessThanOrEqualValidator(selector, expression.GetMember()); } } }
apache-2.0
C#
53b718e842665b0142125f007c681a5b8ca1e3a2
Add reference to System.Configuration
SkillsFundingAgency/das-referencedata,SkillsFundingAgency/das-referencedata
src/SFA.DAS.ReferenceData.Infrastructure/Caching/RedisCache.cs
src/SFA.DAS.ReferenceData.Infrastructure/Caching/RedisCache.cs
using System; using System.Configuration; using System.Threading.Tasks; using Microsoft.Azure; using Newtonsoft.Json; using SFA.DAS.ReferenceData.Domain.Interfaces.Caching; using StackExchange.Redis; namespace SFA.DAS.ReferenceData.Infrastructure.Caching { public class RedisCache : ICache { private readonly IDatabase _cache; public RedisCache() { var connectionMultiplexer = ConnectionMultiplexer.Connect(ConfigurationManager.Appsettings["RedisConnectionString"]); _cache = connectionMultiplexer.GetDatabase(); } public async Task<bool> ExistsAsync(string key) { return await _cache.KeyExistsAsync(key); } public async Task<T> GetCustomValueAsync<T>(string key) { var redisValue = await _cache.StringGetAsync(key); return JsonConvert.DeserializeObject<T>(redisValue); } public async Task SetCustomValueAsync<T>(string key, T customType, int secondsInCache = 300) { if (!await _cache.KeyExistsAsync(key)) { var _lock = new TaskSynchronizationScope(); await _lock.RunAsync(async () => { if (!await _cache.KeyExistsAsync(key)) { await _cache.StringSetAsync(key, JsonConvert.SerializeObject(customType), TimeSpan.FromSeconds(secondsInCache)); } }); } } } }
using System; using System.Threading.Tasks; using Microsoft.Azure; using Newtonsoft.Json; using SFA.DAS.ReferenceData.Domain.Interfaces.Caching; using StackExchange.Redis; namespace SFA.DAS.ReferenceData.Infrastructure.Caching { public class RedisCache : ICache { private readonly IDatabase _cache; public RedisCache() { var connectionMultiplexer = ConnectionMultiplexer.Connect(ConfigurationManager.Appsettings["RedisConnectionString"]); _cache = connectionMultiplexer.GetDatabase(); } public async Task<bool> ExistsAsync(string key) { return await _cache.KeyExistsAsync(key); } public async Task<T> GetCustomValueAsync<T>(string key) { var redisValue = await _cache.StringGetAsync(key); return JsonConvert.DeserializeObject<T>(redisValue); } public async Task SetCustomValueAsync<T>(string key, T customType, int secondsInCache = 300) { if (!await _cache.KeyExistsAsync(key)) { var _lock = new TaskSynchronizationScope(); await _lock.RunAsync(async () => { if (!await _cache.KeyExistsAsync(key)) { await _cache.StringSetAsync(key, JsonConvert.SerializeObject(customType), TimeSpan.FromSeconds(secondsInCache)); } }); } } } }
mit
C#
53d09684f0cf3b52cc736caeed6e80012e54d51a
Modify versions.
nuitsjp/Xamarin.Forms.GoogleMaps.Bindings
Soruce/Xamarin.Forms.GoogleMaps.Bindings/Properties/AssemblyInfo.cs
Soruce/Xamarin.Forms.GoogleMaps.Bindings/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Xamarin.Forms.GoogleMaps.Bindings")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xamarin.Forms.GoogleMaps.Bindings")] [assembly: AssemblyCopyright("Copyright (C) 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("ja")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
using System.Resources; using System.Reflection; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("Xamarin.Forms.GoogleMaps.Bindings")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Xamarin.Forms.GoogleMaps.Bindings")] [assembly: AssemblyCopyright("Copyright (C) 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("ja")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // リビジョン // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
e50df97b1092eac24210f3f86fed53249cfa41fc
Increase test wait times (appveyor be slow)
peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new TestAudioCollectionManager(); var threadExecutionFinished = new ManualResetEventSlim(); var updateLoopStarted = new ManualResetEventSlim(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a separate thread start processing the queue var thread = new Thread(() => { while (!manager.IsDisposed) { manager.Update(); updateLoopStarted.Set(); } threadExecutionFinished.Set(); }); thread.Start(); Assert.IsTrue(updateLoopStarted.Wait(10000)); Assert.DoesNotThrow(() => manager.Dispose()); Assert.IsTrue(threadExecutionFinished.Wait(10000)); } private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent> { public new bool IsDisposed => base.IsDisposed; } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new TestAudioCollectionManager(); var threadExecutionFinished = new ManualResetEventSlim(); var updateLoopStarted = new ManualResetEventSlim(); // add a huge amount of items to the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a separate thread start processing the queue var thread = new Thread(() => { while (!manager.IsDisposed) { manager.Update(); updateLoopStarted.Set(); } threadExecutionFinished.Set(); }); thread.Start(); Assert.IsTrue(updateLoopStarted.Wait(1000)); Assert.DoesNotThrow(() => manager.Dispose()); Assert.IsTrue(threadExecutionFinished.Wait(1000)); } private class TestAudioCollectionManager : AudioCollectionManager<AdjustableAudioComponent> { public new bool IsDisposed => base.IsDisposed; } private class TestingAdjustableAudioComponent : AdjustableAudioComponent { } } }
mit
C#
e0e19ad63e20fed8b611547f9d864c867cd7d54e
Fix 7437 - Load test binary from random temp location to avoid locking conflicts that may result in test failure
shmao/corefx,alexperovich/corefx,seanshpark/corefx,BrennanConroy/corefx,billwert/corefx,MaggieTsang/corefx,manu-silicon/corefx,twsouthwick/corefx,ellismg/corefx,manu-silicon/corefx,gkhanna79/corefx,nbarbettini/corefx,manu-silicon/corefx,Petermarcu/corefx,parjong/corefx,weltkante/corefx,cydhaselton/corefx,ericstj/corefx,ravimeda/corefx,YoupHulsebos/corefx,shimingsg/corefx,marksmeltzer/corefx,ericstj/corefx,dhoehna/corefx,elijah6/corefx,rjxby/corefx,seanshpark/corefx,richlander/corefx,ptoonen/corefx,stephenmichaelf/corefx,adamralph/corefx,the-dwyer/corefx,ViktorHofer/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,weltkante/corefx,Ermiar/corefx,rubo/corefx,YoupHulsebos/corefx,krk/corefx,dhoehna/corefx,stephenmichaelf/corefx,billwert/corefx,yizhang82/corefx,krytarowski/corefx,Jiayili1/corefx,fgreinacher/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,tijoytom/corefx,dsplaisted/corefx,nchikanov/corefx,yizhang82/corefx,wtgodbe/corefx,ptoonen/corefx,gkhanna79/corefx,ptoonen/corefx,jlin177/corefx,BrennanConroy/corefx,dhoehna/corefx,wtgodbe/corefx,axelheer/corefx,krytarowski/corefx,rubo/corefx,nbarbettini/corefx,axelheer/corefx,richlander/corefx,twsouthwick/corefx,ellismg/corefx,Chrisboh/corefx,rahku/corefx,jhendrixMSFT/corefx,MaggieTsang/corefx,iamjasonp/corefx,nchikanov/corefx,tijoytom/corefx,yizhang82/corefx,seanshpark/corefx,Ermiar/corefx,lggomez/corefx,rahku/corefx,jlin177/corefx,twsouthwick/corefx,nchikanov/corefx,jhendrixMSFT/corefx,Priya91/corefx-1,ptoonen/corefx,shimingsg/corefx,khdang/corefx,mmitche/corefx,tijoytom/corefx,marksmeltzer/corefx,dotnet-bot/corefx,fgreinacher/corefx,stephenmichaelf/corefx,krytarowski/corefx,mazong1123/corefx,richlander/corefx,lggomez/corefx,gkhanna79/corefx,wtgodbe/corefx,rjxby/corefx,krytarowski/corefx,gkhanna79/corefx,jlin177/corefx,axelheer/corefx,yizhang82/corefx,rubo/corefx,rahku/corefx,rjxby/corefx,marksmeltzer/corefx,dotnet-bot/corefx,Petermarcu/corefx,marksmeltzer/corefx,ViktorHofer/corefx,Priya91/corefx-1,elijah6/corefx,parjong/corefx,nbarbettini/corefx,cydhaselton/corefx,Ermiar/corefx,yizhang82/corefx,alphonsekurian/corefx,twsouthwick/corefx,iamjasonp/corefx,elijah6/corefx,seanshpark/corefx,ptoonen/corefx,gkhanna79/corefx,gkhanna79/corefx,ericstj/corefx,elijah6/corefx,Chrisboh/corefx,zhenlan/corefx,cydhaselton/corefx,Petermarcu/corefx,lggomez/corefx,krk/corefx,ravimeda/corefx,JosephTremoulet/corefx,seanshpark/corefx,jhendrixMSFT/corefx,the-dwyer/corefx,lggomez/corefx,shmao/corefx,krytarowski/corefx,manu-silicon/corefx,Priya91/corefx-1,adamralph/corefx,dotnet-bot/corefx,stone-li/corefx,DnlHarvey/corefx,dhoehna/corefx,rahku/corefx,mazong1123/corefx,shimingsg/corefx,jlin177/corefx,Petermarcu/corefx,dsplaisted/corefx,khdang/corefx,jhendrixMSFT/corefx,mmitche/corefx,the-dwyer/corefx,gkhanna79/corefx,nbarbettini/corefx,iamjasonp/corefx,krk/corefx,twsouthwick/corefx,nchikanov/corefx,parjong/corefx,mmitche/corefx,ravimeda/corefx,Jiayili1/corefx,jlin177/corefx,seanshpark/corefx,ellismg/corefx,Petermarcu/corefx,Ermiar/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,YoupHulsebos/corefx,parjong/corefx,nbarbettini/corefx,stone-li/corefx,alexperovich/corefx,weltkante/corefx,shimingsg/corefx,nchikanov/corefx,weltkante/corefx,Priya91/corefx-1,Jiayili1/corefx,axelheer/corefx,mmitche/corefx,ellismg/corefx,krk/corefx,zhenlan/corefx,parjong/corefx,seanshpark/corefx,shimingsg/corefx,rahku/corefx,richlander/corefx,shmao/corefx,iamjasonp/corefx,yizhang82/corefx,stone-li/corefx,richlander/corefx,ellismg/corefx,lggomez/corefx,alphonsekurian/corefx,ericstj/corefx,nchikanov/corefx,JosephTremoulet/corefx,wtgodbe/corefx,shmao/corefx,the-dwyer/corefx,nbarbettini/corefx,zhenlan/corefx,billwert/corefx,khdang/corefx,alphonsekurian/corefx,manu-silicon/corefx,ViktorHofer/corefx,alphonsekurian/corefx,alphonsekurian/corefx,ViktorHofer/corefx,ptoonen/corefx,mmitche/corefx,weltkante/corefx,tijoytom/corefx,alexperovich/corefx,jhendrixMSFT/corefx,Chrisboh/corefx,manu-silicon/corefx,alphonsekurian/corefx,axelheer/corefx,mazong1123/corefx,ViktorHofer/corefx,cydhaselton/corefx,ravimeda/corefx,MaggieTsang/corefx,krk/corefx,rubo/corefx,parjong/corefx,mazong1123/corefx,shmao/corefx,mmitche/corefx,Ermiar/corefx,elijah6/corefx,zhenlan/corefx,manu-silicon/corefx,axelheer/corefx,YoupHulsebos/corefx,ravimeda/corefx,nchikanov/corefx,twsouthwick/corefx,MaggieTsang/corefx,Priya91/corefx-1,stephenmichaelf/corefx,adamralph/corefx,alexperovich/corefx,YoupHulsebos/corefx,wtgodbe/corefx,JosephTremoulet/corefx,cydhaselton/corefx,ravimeda/corefx,mazong1123/corefx,zhenlan/corefx,Chrisboh/corefx,rjxby/corefx,dsplaisted/corefx,rahku/corefx,marksmeltzer/corefx,alexperovich/corefx,Priya91/corefx-1,elijah6/corefx,khdang/corefx,zhenlan/corefx,krk/corefx,MaggieTsang/corefx,fgreinacher/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,richlander/corefx,rubo/corefx,DnlHarvey/corefx,DnlHarvey/corefx,iamjasonp/corefx,twsouthwick/corefx,stephenmichaelf/corefx,rjxby/corefx,stone-li/corefx,tijoytom/corefx,Jiayili1/corefx,richlander/corefx,dhoehna/corefx,tijoytom/corefx,MaggieTsang/corefx,khdang/corefx,zhenlan/corefx,mazong1123/corefx,jlin177/corefx,billwert/corefx,stone-li/corefx,Ermiar/corefx,marksmeltzer/corefx,rjxby/corefx,dhoehna/corefx,ViktorHofer/corefx,lggomez/corefx,mazong1123/corefx,Chrisboh/corefx,Chrisboh/corefx,jhendrixMSFT/corefx,krytarowski/corefx,stone-li/corefx,nbarbettini/corefx,alexperovich/corefx,mmitche/corefx,shmao/corefx,wtgodbe/corefx,jlin177/corefx,weltkante/corefx,shimingsg/corefx,weltkante/corefx,dhoehna/corefx,fgreinacher/corefx,marksmeltzer/corefx,DnlHarvey/corefx,krytarowski/corefx,dotnet-bot/corefx,billwert/corefx,MaggieTsang/corefx,YoupHulsebos/corefx,alexperovich/corefx,ericstj/corefx,elijah6/corefx,stone-li/corefx,shmao/corefx,shimingsg/corefx,rahku/corefx,tijoytom/corefx,Jiayili1/corefx,Jiayili1/corefx,ptoonen/corefx,billwert/corefx,stephenmichaelf/corefx,cydhaselton/corefx,parjong/corefx,rjxby/corefx,ericstj/corefx,the-dwyer/corefx,ellismg/corefx,iamjasonp/corefx,ericstj/corefx,Jiayili1/corefx,cydhaselton/corefx,alphonsekurian/corefx,Petermarcu/corefx,Ermiar/corefx,lggomez/corefx,the-dwyer/corefx,iamjasonp/corefx,the-dwyer/corefx,jhendrixMSFT/corefx,DnlHarvey/corefx,Petermarcu/corefx,wtgodbe/corefx,DnlHarvey/corefx,billwert/corefx,ravimeda/corefx,ViktorHofer/corefx,yizhang82/corefx,YoupHulsebos/corefx,JosephTremoulet/corefx,khdang/corefx,krk/corefx
src/System.Runtime.Loader/tests/ResourceAssemblyLoadContext.cs
src/System.Runtime.Loader/tests/ResourceAssemblyLoadContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection; namespace System.Runtime.Loader.Tests { public enum LoadBy { Path, Stream } public class ResourceAssemblyLoadContext : AssemblyLoadContext { public LoadBy LoadBy { get; set; } public ResourceAssemblyLoadContext() { LoadBy = LoadBy.Path; } // A custom load context which only loads a given assembly if it is an embedded resource. protected override Assembly Load(AssemblyName assemblyName) { string assembly = assemblyName.Name + ".dll"; var currentAsm = typeof(ResourceAssemblyLoadContext).GetTypeInfo().Assembly; var asmStream = currentAsm.GetManifestResourceStream("System.Runtime.Loader.Tests." + assembly); if (asmStream == null) { return null; } if (LoadBy == LoadBy.Path) { // corerun blindly adds all the assemblies (including test assemblies) in the current directory to the TPA list. // Custom Load Contexts cannot be used to load an assembly in the TPA list. // Hence using this hack - where the user test assembly "System.Runtime.Loader.TestAssembly" is added as an embedded resource. // This custom load context will extract that resource and store it at the %temp% path at runtime. // This prevents the corerun from adding the test assembly to the TPA list. // Once loaded it is not possible to unload the assembly, therefore it cannot be deleted. var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); // Create the folder since it will not exist already Directory.CreateDirectory(tempPath); string path = Path.Combine(tempPath, assembly); using (FileStream output = File.OpenWrite(path)) { asmStream.CopyTo(output); } return LoadFromAssemblyPath(path); } else if (LoadBy == LoadBy.Stream) { return LoadFromStream(asmStream); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection; namespace System.Runtime.Loader.Tests { public enum LoadBy { Path, Stream } public class ResourceAssemblyLoadContext : AssemblyLoadContext { public LoadBy LoadBy { get; set; } public ResourceAssemblyLoadContext() { LoadBy = LoadBy.Path; } // A custom load context which only loads a given assembly if it is an embedded resource. protected override Assembly Load(AssemblyName assemblyName) { string assembly = assemblyName.Name + ".dll"; var currentAsm = typeof(ResourceAssemblyLoadContext).GetTypeInfo().Assembly; var asmStream = currentAsm.GetManifestResourceStream("System.Runtime.Loader.Tests." + assembly); if (asmStream == null) { return null; } if (LoadBy == LoadBy.Path) { // corerun blindly adds all the assemblies (including test assemblies) in the current directory to the TPA list. // Custom Load Contexts cannot be used to load an assembly in the TPA list. // Hence using this hack - where the user test assembly "System.Runtime.Loader.TestAssembly" is added as an embedded resource. // This custom load context will extract that resource and store it at the %temp% path at runtime. // This prevents the corerun from adding the test assembly to the TPA list. // Once loaded it is not possible to unload the assembly, therefore it cannot be deleted. string path = Path.Combine(Path.GetTempPath(), assembly); using (FileStream output = File.OpenWrite(path)) { asmStream.CopyTo(output); } return LoadFromAssemblyPath(path); } else if (LoadBy == LoadBy.Stream) { return LoadFromStream(asmStream); } return null; } } }
mit
C#
dd7d6523ff531e5c09e63f087444e73b3c3ae2a1
Use sprite.textureRect instead of calculating yourself
JuhaKiili/RagePixel2
Assets/RagePixel2/Editor/RagePixelUtility.cs
Assets/RagePixel2/Editor/RagePixelUtility.cs
using UnityEditor; using UnityEngine; using System.Collections; public static class RagePixelUtility { public static Vector2 UVToPixel(Vector2 uv, Sprite sprite) { return new Vector2(uv.x * sprite.texture.width, uv.y * sprite.texture.height); } public static Vector2 LocalToUV(Vector3 localPosition, Sprite sprite) { Vector2 localNormalizedPosition = new Vector2( Mathf.Clamp01((localPosition.x - sprite.bounds.min.x) / sprite.bounds.size.x), Mathf.Clamp01((localPosition.y - sprite.bounds.min.y) / sprite.bounds.size.y) ); Vector3 textureUV = new Vector2( localNormalizedPosition.x * (sprite.rect.width / sprite.texture.width) + sprite.textureRect.xMin, localNormalizedPosition.y * (sprite.rect.height / sprite.texture.height) + sprite.textureRect.yMin ); return textureUV; } public static Vector3 LocalToWorld(Vector3 localPosition, Transform transform) { return transform.TransformPoint(localPosition); } public static Vector3 ScreenToLocal(Vector2 screenPosition, Transform transform) { return transform.InverseTransformPoint(ScreenToWorld(screenPosition, transform)); } public static Vector3 ScreenToWorld(Vector2 screenPosition, Transform transform) { Ray mouseRay = HandleUtility.GUIPointToWorldRay(screenPosition); float dist; new Plane(transform.forward, Vector3.zero).Raycast(mouseRay, out dist); return mouseRay.GetPoint(dist); } public static Vector2 WorldToScreen(Vector3 worldPosition, Transform transform) { return HandleUtility.WorldToGUIPoint(worldPosition); } public static void DrawDebugPoint(Vector3 point) { Handles.color = Color.red; float size = HandleUtility.GetHandleSize(point) * 0.1f; Handles.DrawLine(point + Vector3.up * size, point + Vector3.down * size); Handles.DrawLine(point + Vector3.left * size, point + Vector3.right * size); Handles.DrawLine(point + Vector3.forward * size, point + Vector3.back * size); } }
using UnityEditor; using UnityEngine; using System.Collections; public static class RagePixelUtility { public static Vector2 UVToPixel(Vector2 uv, Sprite sprite) { return new Vector2(uv.x * sprite.texture.width, uv.y * sprite.texture.height); } public static Vector2 LocalToUV(Vector3 localPosition, Sprite sprite) { Rect spriteUVRect = SpriteUV(sprite); Vector2 localNormalizedPosition = new Vector2( Mathf.Clamp01((localPosition.x - sprite.bounds.min.x) / sprite.bounds.size.x), Mathf.Clamp01((localPosition.y - sprite.bounds.min.y) / sprite.bounds.size.y) ); Vector3 textureUV = new Vector2( localNormalizedPosition.x * (sprite.rect.width / sprite.texture.width) + spriteUVRect.xMin, localNormalizedPosition.y * (sprite.rect.height / sprite.texture.height) + spriteUVRect.yMin ); return textureUV; } public static Rect SpriteUV (Sprite sprite) { return new Rect ( sprite.rect.xMin / sprite.texture.width, sprite.rect.yMin / sprite.texture.height, sprite.rect.width / sprite.texture.width, sprite.rect.height / sprite.texture.height ); } public static Vector3 LocalToWorld(Vector3 localPosition, Transform transform) { return transform.TransformPoint(localPosition); } public static Vector3 ScreenToLocal(Vector2 screenPosition, Transform transform) { return transform.InverseTransformPoint(ScreenToWorld(screenPosition, transform)); } public static Vector3 ScreenToWorld(Vector2 screenPosition, Transform transform) { Ray mouseRay = HandleUtility.GUIPointToWorldRay(screenPosition); float dist; new Plane(transform.forward, Vector3.zero).Raycast(mouseRay, out dist); return mouseRay.GetPoint(dist); } public static Vector2 WorldToScreen(Vector3 worldPosition, Transform transform) { return HandleUtility.WorldToGUIPoint(worldPosition); } public static void DrawDebugPoint(Vector3 point) { Handles.color = Color.red; float size = HandleUtility.GetHandleSize(point) * 0.1f; Handles.DrawLine(point + Vector3.up * size, point + Vector3.down * size); Handles.DrawLine(point + Vector3.left * size, point + Vector3.right * size); Handles.DrawLine(point + Vector3.forward * size, point + Vector3.back * size); } }
mit
C#