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
7280f77a02621decb74bd0c08e84cc79de2ad35e
Trim whitespace
UselessToucan/osu,peppy/osu-new,DrabWeb/osu,smoogipoo/osu,johnneijzen/osu,2yangk23/osu,Frontear/osuKyzer,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,2yangk23/osu,naoey/osu,ppy/osu,DrabWeb/osu,EVAST9919/osu,johnneijzen/osu,naoey/osu,smoogipooo/osu,Nabile-Rahmani/osu,naoey/osu,EVAST9919/osu,Drezi126/osu,DrabWeb/osu,NeoAdonis/osu,UselessToucan/osu,ZLima12/osu
osu.Game/Beatmaps/BeatmapSetOnlineInfo.cs
osu.Game/Beatmaps/BeatmapSetOnlineInfo.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; namespace osu.Game.Beatmaps { /// <summary> /// Beatmap set info retrieved for previewing locally without having the set downloaded. /// </summary> public class BeatmapSetOnlineInfo { /// <summary> /// The date this beatmap set was submitted to the online listing. /// </summary> public DateTimeOffset Submitted { get; set; } /// <summary> /// The date this beatmap set was ranked. /// </summary> public DateTimeOffset? Ranked { get; set; } /// <summary> /// The date this beatmap set was last updated. /// </summary> public DateTimeOffset? LastUpdated { get; set; } /// <summary> /// Whether or not this beatmap set has a background video. /// </summary> public bool HasVideo { get; set; } /// <summary> /// The different sizes of cover art for this beatmap set. /// </summary> public BeatmapSetOnlineCovers Covers { get; set; } /// <summary> /// A small sample clip of this beatmap set's song. /// </summary> public string Preview { get; set; } /// <summary> /// The beats per minute of this beatmap set's song. /// </summary> public double BPM { get; set; } /// <summary> /// The amount of plays this beatmap set has. /// </summary> public int PlayCount { get; set; } /// <summary> /// The amount of people who have favourited this beatmap set. /// </summary> public int FavouriteCount { get; set; } } public class BeatmapSetOnlineCovers { public string CoverLowRes { get; set; } public string Cover { get; set; } public string CardLowRes { get; set; } public string Card { get; set; } public string ListLowRes { get; set; } public string List { get; set; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; namespace osu.Game.Beatmaps { /// <summary> /// Beatmap set info retrieved for previewing locally without having the set downloaded. /// </summary> public class BeatmapSetOnlineInfo { /// <summary> /// The date this beatmap set was submitted to the online listing. /// </summary> public DateTimeOffset Submitted { get; set; } /// <summary> /// The date this beatmap set was ranked. /// </summary> public DateTimeOffset? Ranked { get; set; } /// <summary> /// The date this beatmap set was last updated. /// </summary> public DateTimeOffset? LastUpdated { get; set; } /// <summary> /// Whether or not this beatmap set has a background video. /// </summary> public bool HasVideo { get; set; } /// <summary> /// The different sizes of cover art for this beatmap set. /// </summary> public BeatmapSetOnlineCovers Covers { get; set; } /// <summary> /// A small sample clip of this beatmap set's song. /// </summary> public string Preview { get; set; } /// <summary> /// The beats per minute of this beatmap set's song. /// </summary> public double BPM { get; set; } /// <summary> /// The amount of plays this beatmap set has. /// </summary> public int PlayCount { get; set; } /// <summary> /// The amount of people who have favourited this beatmap set. /// </summary> public int FavouriteCount { get; set; } } public class BeatmapSetOnlineCovers { public string CoverLowRes { get; set; } public string Cover { get; set; } public string CardLowRes { get; set; } public string Card { get; set; } public string ListLowRes { get; set; } public string List { get; set; } } }
mit
C#
43adae3d9799f966e267a142ed5e0f877d4f6002
Change OnDeserialized to OnDeserializing
yas-mnkornym/TaihaToolkit
source/TaihaToolkit.Core/NotificationObjectWithPropertyBag.cs
source/TaihaToolkit.Core/NotificationObjectWithPropertyBag.cs
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace Studiotaiha.Toolkit { [DataContract] public class NotificationObjectWithPropertyBag : NotificationObject { [IgnoreDataMember] protected IDictionary<string, object> PropertyBag { get; private set; } = new Dictionary<string, object>(); public NotificationObjectWithPropertyBag(IDispatcher dispatcher = null) : base(dispatcher) { } [OnDeserializing] void OnDeserializingForNotificationObjectWithPropertyBag(StreamingContext context) { PropertyBag = new Dictionary<string, object>(); } /// <summary> /// Set a value to the property bag. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be set.</param> /// <param name="actBeforeChange">Action object that will be invoked before the value is changed</param> /// <param name="actAfterChange">Action object that will be invoked before the value is changed</param> /// <param name="propertyName">Name of the property</param> /// <returns>True if the value is changed.</returns> protected virtual bool SetValue<T>( T value, Action<T, T> actBeforeChange = null, Action<T, T> actAfterChange = null, [CallerMemberName]string propertyName = null) { if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } object oldValueObject; PropertyBag.TryGetValue(propertyName, out oldValueObject); var oldValue = oldValueObject is T ? (T)oldValueObject : default(T); var isChanged = value == null ? oldValueObject != null : !value.Equals(oldValue); if (isChanged) { actBeforeChange?.Invoke(oldValue, value); PropertyBag[propertyName] = value; actAfterChange?.Invoke(oldValue, value); RaisePropertyChanged(propertyName); } return isChanged; } /// <summary> /// Gets a value from the property bag. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="defaultValue">Default value to be returned the proeprty is not stored in the bag</param> /// <param name="propertyName">Name of the property</param> /// <returns>The value or default value.</returns> protected virtual T GetValue<T>( T defaultValue = default(T), [CallerMemberName]string propertyName = null) { if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } object oldValueObject; PropertyBag.TryGetValue(propertyName, out oldValueObject); return oldValueObject is T ? (T)oldValueObject : defaultValue; } } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; namespace Studiotaiha.Toolkit { [DataContract] public class NotificationObjectWithPropertyBag : NotificationObject { [IgnoreDataMember] protected IDictionary<string, object> PropertyBag { get; private set; } = new Dictionary<string, object>(); public NotificationObjectWithPropertyBag(IDispatcher dispatcher = null) : base(dispatcher) { } [OnDeserialized] void OnDeserialized(StreamingContext context) { PropertyBag = new Dictionary<string, object>(); } /// <summary> /// Set a value to the property bag. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be set.</param> /// <param name="actBeforeChange">Action object that will be invoked before the value is changed</param> /// <param name="actAfterChange">Action object that will be invoked before the value is changed</param> /// <param name="propertyName">Name of the property</param> /// <returns>True if the value is changed.</returns> protected virtual bool SetValue<T>( T value, Action<T, T> actBeforeChange = null, Action<T, T> actAfterChange = null, [CallerMemberName]string propertyName = null) { if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } object oldValueObject; PropertyBag.TryGetValue(propertyName, out oldValueObject); var oldValue = oldValueObject is T ? (T)oldValueObject : default(T); var isChanged = value == null ? oldValueObject != null : !value.Equals(oldValue); if (isChanged) { actBeforeChange?.Invoke(oldValue, value); PropertyBag[propertyName] = value; actAfterChange?.Invoke(oldValue, value); RaisePropertyChanged(propertyName); } return isChanged; } /// <summary> /// Gets a value from the property bag. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="defaultValue">Default value to be returned the proeprty is not stored in the bag</param> /// <param name="propertyName">Name of the property</param> /// <returns>The value or default value.</returns> protected virtual T GetValue<T>( T defaultValue = default(T), [CallerMemberName]string propertyName = null) { if (propertyName == null) { throw new ArgumentNullException(nameof(propertyName)); } object oldValueObject; PropertyBag.TryGetValue(propertyName, out oldValueObject); return oldValueObject is T ? (T)oldValueObject : defaultValue; } } }
mit
C#
cafd23313af54a0951be322fca2296a7291bfcab
Validate collider type in NearInteractionGrabbable (#5211)
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity
Assets/MixedRealityToolkit.Services/InputSystem/NearInteractionGrabbable.cs
Assets/MixedRealityToolkit.Services/InputSystem/NearInteractionGrabbable.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Add a NearInteractionGrabbable component to any GameObject that has a collidable /// on it in order to make that collidable near grabbable. /// /// Any IMixedRealityNearPointer will then dispatch pointer events /// to the closest near grabbable objects. /// /// Additionally, the near pointer will send focus enter and exit events when the /// decorated object is the closest object to the near pointer /// </summary> public class NearInteractionGrabbable : MonoBehaviour { [Tooltip("Check to show a tether from the position where object was grabbed to the hand when manipulating. Useful for things like bounding boxes where resizing/rotating might be constrained.")] public bool ShowTetherWhenManipulating = false; void OnEnable() { // As of https://docs.unity3d.com/ScriptReference/Physics.ClosestPoint.html // ClosestPoint call will only work on specific types of colliders. // Using incorrect type of collider will emit warning from FocusProvider, // but grab behavior will be broken at this point. // Emit exception on initialization, when we know grab interaction is used // on this object to make an error clearly visible. var collider = gameObject.GetComponent<Collider>(); if((collider as BoxCollider) == null && (collider as CapsuleCollider) == null && (collider as SphereCollider) == null && ((collider as MeshCollider) == null || (collider as MeshCollider).convex == false)) { Debug.LogException(new UnityException("NearInteractionGrabbable requires a " + "BoxCollider, SphereCollider, CapsuleCollider or a convex MeshCollider on an object. " + "Otherwise grab interaction will not work correctly.")); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Add a NearInteractionGrabbable component to any GameObject that has a collidable /// on it in order to make that collidable near grabbable. /// /// Any IMixedRealityNearPointer will then dispatch pointer events /// to the closest near grabbable objects. /// /// Additionally, the near pointer will send focus enter and exit events when the /// decorated object is the closest object to the near pointer /// </summary> public class NearInteractionGrabbable : MonoBehaviour { [Tooltip("Check to show a tether from the position where object was grabbed to the hand when manipulating. Useful for things like bounding boxes where resizing/rotating might be constrained.")] public bool ShowTetherWhenManipulating = false; } }
mit
C#
600d0798678a35880f512fb6162e23170f3a88ab
Remove contract count check for protobuf
modulexcite/lokad-cqrs
Framework/Lokad.Cqrs.Azure/Core.Serialization/DataSerializerWithProtoBuf.cs
Framework/Lokad.Cqrs.Azure/Core.Serialization/DataSerializerWithProtoBuf.cs
#region (c) 2010-2011 Lokad CQRS - New BSD License // Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com) // This code is released as Open Source under the terms of the New BSD Licence // Homepage: http://lokad.github.com/lokad-cqrs/ #endregion using System; using System.Collections.Generic; using ProtoBuf.Meta; namespace Lokad.Cqrs.Core.Serialization { public class DataSerializerWithProtoBuf : AbstractDataSerializer { public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes) { } protected override Formatter PrepareFormatter(Type type) { var name = ContractEvil.GetContractReference(type); var formatter = RuntimeTypeModel.Default.CreateFormatter(type); return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o)); } } }
#region (c) 2010-2011 Lokad CQRS - New BSD License // Copyright (c) Lokad SAS 2010-2011 (http://www.lokad.com) // This code is released as Open Source under the terms of the New BSD Licence // Homepage: http://lokad.github.com/lokad-cqrs/ #endregion using System; using System.Collections.Generic; using ProtoBuf.Meta; namespace Lokad.Cqrs.Core.Serialization { public class DataSerializerWithProtoBuf : AbstractDataSerializer { public DataSerializerWithProtoBuf(ICollection<Type> knownTypes) : base(knownTypes) { if (knownTypes.Count == 0) throw new InvalidOperationException( "ProtoBuf requires some known types to serialize. Have you forgot to supply them?"); } protected override Formatter PrepareFormatter(Type type) { var name = ContractEvil.GetContractReference(type); var formatter = RuntimeTypeModel.Default.CreateFormatter(type); return new Formatter(name, formatter.Deserialize, (o, stream) => formatter.Serialize(stream,o)); } } }
bsd-3-clause
C#
0824a3c637fa8510144fae3b8c63f3c27e043ca5
fix OperationException
yezorat/BtrieveWrapper,yezorat/BtrieveWrapper,gomafutofu/BtrieveWrapper,gomafutofu/BtrieveWrapper
BtrieveWrapper/OperationException.cs
BtrieveWrapper/OperationException.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Xml.Serialization; namespace BtrieveWrapper { [Serializable] public class OperationException : Exception { static readonly string _statusDefinitionPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".StatusCollection.xml"; static readonly Dictionary<short, string> _dictionary = new Dictionary<short, string>(); static string GetMessage(Operation operationType, short statusCode){ var result = new StringBuilder("Status code "); result.Append(statusCode); result.Append(" ("); result.Append(operationType); result.Append(") : "); if (_dictionary.ContainsKey(statusCode)) { result.Append(_dictionary[statusCode]); } else { result.Append("This code is undefined."); } return result.ToString(); } static OperationException() { try { StatusDefinition statusDefinition; using (var stream = new FileStream(_statusDefinitionPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var serializer = new XmlSerializer(typeof(StatusDefinition)); statusDefinition = (StatusDefinition)serializer.Deserialize(stream); } foreach (var status in statusDefinition.StatusCollection) { _dictionary[status.Code] = status.Message; } } catch { } } internal OperationException(Operation operation, short statusCode, Exception innerException = null) : base(null, innerException) { this.Operation = operation; this.StatusCode = statusCode; } public Operation Operation { get; private set; } public short StatusCode { get; private set; } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } public override string Message { get { return GetMessage( } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Xml.Serialization; namespace BtrieveWrapper { [Serializable] public class OperationException : Exception { static readonly string _statusDefinitionPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".StatusCollection.xml"; static readonly Dictionary<short, string> _dictionary = new Dictionary<short, string>(); static string GetMessage(Operation operationType, short statusCode){ var result = new StringBuilder("Status code "); result.Append(statusCode); result.Append(" ("); result.Append(operationType); result.Append(") : "); if (_dictionary.ContainsKey(statusCode)) { result.Append(_dictionary[statusCode]); } else { result.Append("This code is undefined."); } return result.ToString(); } static OperationException() { try { StatusDefinition statusDefinition; using (var stream = new FileStream(_statusDefinitionPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var serializer = new XmlSerializer(typeof(StatusDefinition)); statusDefinition = (StatusDefinition)serializer.Deserialize(stream); } foreach (var status in statusDefinition.StatusCollection) { _dictionary[status.Code] = status.Message; } } catch { } } internal OperationException(Operation operationType, short statusCode, Exception innerException = null) : base(GetMessage(operationType, statusCode), innerException) { this.StatusCode = statusCode; } public short StatusCode { get; private set; } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } }
mit
C#
8820260648cad4c4db6c994e96a53461f32cbf9e
Comment realign
connellw/Firestorm
src/Firestorm.Endpoints.Formatting/Json/JsonCreationConverter.cs
src/Firestorm.Endpoints.Formatting/Json/JsonCreationConverter.cs
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Firestorm.Endpoints.Formatting.Json { /// <remarks> /// Taken from http://stackoverflow.com/a/12641541/369247 and abstracted to <see cref="JsonGenericReadOnlyConverterBase{T}"/>. /// </remarks> public abstract class JsonCreationConverter<T> : JsonGenericReadOnlyConverterBase<T> { /// <summary> /// Create an instance of objectType, based properties in the JSON object /// </summary> /// <param name="objectType">type of object expected</param> /// <param name="jObject">contents of JSON object that will be deserialized</param> /// <returns></returns> protected abstract T Create(Type objectType, JObject jObject); protected override T ReadFromJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return default(T); JObject jObject = JObject.Load(reader); T target = Create(objectType, jObject); serializer.Populate(jObject.CreateReader(), target); return target; } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Firestorm.Endpoints.Formatting.Json { /// <remarks> /// Taken from http://stackoverflow.com/a/12641541/369247 and abstracted to <see cref="JsonGenericReadOnlyConverterBase{T}"/>. /// </remarks> public abstract class JsonCreationConverter<T> : JsonGenericReadOnlyConverterBase<T> { /// <summary> /// Create an instance of objectType, based properties in the JSON object /// </summary> /// <param name="objectType">type of object expected</param> /// <param name="jObject">contents of JSON object that will be /// deserialized</param> /// <returns></returns> protected abstract T Create(Type objectType, JObject jObject); protected override T ReadFromJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) return default(T); JObject jObject = JObject.Load(reader); T target = Create(objectType, jObject); serializer.Populate(jObject.CreateReader(), target); return target; } } }
mit
C#
a1dd141d265c26f3f3095c6a66b06054d9a0a71f
tweak in logic
justinlhudson/Impromptu
C#/Impromptu/Utilities/Extensions.cs
C#/Impromptu/Utilities/Extensions.cs
using System; using System.Linq; using System.Collections.Concurrent; using System.Collections.Generic; namespace Impromptu.Utilities { public static class Extensions { #region Public Static Methods /// <summary> /// Change type cast /// </summary> /// <param name="item">item to change</param> /// <typeparam name="T">change type to</typeparam> /// <remarks>Result of wanted to do dynamic cast to type of object</remarks> public static T Cast<T>(this object item) { return (T)Convert.ChangeType(item, typeof(T)); } public static double NextDouble(this Random random, double min, double max) { return min + (random.NextDouble() * (max - min)); } public static byte[] ToByteArray(this string value) { var encoding = new System.Text.UTF8Encoding(); return value != null ? encoding.GetBytes(value) : null; } public static List<T> ToList<T>(this ConcurrentBag<T> bag) { var result = new List<T>(); foreach(var item in bag) result.Add(item); return result.ToList(); } public static DateTime UTCToLocal(this DateTime utc) { var localTime = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local); return localTime; } public static int CompareTo(this DateTime dateTime1, DateTime dateTime2, int epsilon) { var t1 = dateTime1; var t2 = dateTime2; var result = 0; if(System.Math.Abs(System.Math.Abs((t1 - t2).TotalMilliseconds)) < epsilon) result = -1; else if(System.Math.Abs(System.Math.Abs((t1 - t2).TotalMilliseconds)) > epsilon) result = 1; return result; } public static DateTime Closest(this DateTime[] datetimes, DateTime nearest) { return datetimes.OrderBy(t => System.Math.Abs((t - nearest).Ticks)).FirstOrDefault(); } #endregion } }
using System; using System.Linq; using System.Collections.Concurrent; using System.Collections.Generic; namespace Impromptu.Utilities { public static class Extensions { #region Public Static Methods /// <summary> /// Change type cast /// </summary> /// <param name="item">item to change</param> /// <typeparam name="T">change type to</typeparam> /// <remarks>Result of wanted to do dynamic cast to type of object</remarks> public static T Cast<T>(this object item) { return (T)Convert.ChangeType(item, typeof(T)); } public static double NextDouble(this Random random, double min, double max) { return min + (random.NextDouble() * (max - min)); } public static byte[] ToByteArray(this string value) { var encoding = new System.Text.UTF8Encoding(); return value != null ? encoding.GetBytes(value) : null; } public static List<T> ToList<T>(this ConcurrentBag<T> bag) { var result = new List<T>(); foreach(var item in bag.ToArray()) result.Add(item); return result.ToList(); } public static DateTime UTCToLocal(this DateTime utc) { var localTime = TimeZoneInfo.ConvertTimeFromUtc(utc, TimeZoneInfo.Local); return localTime; } public static int CompareTo(this DateTime dateTime1, DateTime dateTime2, int epsilon) { var t1 = dateTime1; var t2 = dateTime2; var result = 0; if(System.Math.Abs(System.Math.Abs((t1 - t2).TotalMilliseconds)) < epsilon) result = -1; else if(System.Math.Abs(System.Math.Abs((t1 - t2).TotalMilliseconds)) > epsilon) result = 1; return result; } public static DateTime Closest(this DateTime[] datetimes, DateTime nearest) { return datetimes.OrderBy(t => System.Math.Abs((t - nearest).Ticks)).FirstOrDefault(); } #endregion } }
mit
C#
9fe0a40b6300528b1606837998be070966791de1
Update src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs
marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS
src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs
src/Umbraco.Web.Common/AspNetCore/AspNetCoreBackOfficeInfo.cs
using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Routing; using static Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Web.Common.AspNetCore { public class AspNetCoreBackOfficeInfo : IBackOfficeInfo { private readonly IOptionsMonitor<GlobalSettings> _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private string _getAbsoluteUrl; public AspNetCoreBackOfficeInfo(IOptionsMonitor<GlobalSettings> globalSettings, IHostingEnvironment hostingEnviroment) { _globalSettings = globalSettings; _hostingEnvironment = hostingEnviroment; } public string GetAbsoluteUrl { get { if (_getAbsoluteUrl is null) { if(_hostingEnvironment.ApplicationMainUrl is null) { return ""; } _getAbsoluteUrl = WebPath.Combine(_hostingEnvironment.ApplicationMainUrl.ToString(), _globalSettings.CurrentValue.UmbracoPath.TrimStart(CharArrays.TildeForwardSlash)); } return _getAbsoluteUrl; } } } }
using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Routing; using static Umbraco.Cms.Core.Constants; namespace Umbraco.Cms.Web.Common.AspNetCore { public class AspNetCoreBackOfficeInfo : IBackOfficeInfo { private readonly IOptionsMonitor<GlobalSettings> _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private string _getAbsoluteUrl; public AspNetCoreBackOfficeInfo(IOptionsMonitor<GlobalSettings> globalSettings, IHostingEnvironment hostingEnviroment) { _globalSettings = globalSettings; _hostingEnvironment = hostingEnviroment; //GetAbsoluteUrl= WebPath.Combine(hostingEnviroment.ApplicationMainUrl.ToString(), globalSettings.CurrentValue.UmbracoPath.TrimStart(CharArrays.TildeForwardSlash)); } public string GetAbsoluteUrl { get { if (_getAbsoluteUrl is null) { if(_hostingEnvironment.ApplicationMainUrl is null) { return ""; } _getAbsoluteUrl = WebPath.Combine(_hostingEnvironment.ApplicationMainUrl.ToString(), _globalSettings.CurrentValue.UmbracoPath.TrimStart(CharArrays.TildeForwardSlash)); } return _getAbsoluteUrl; } } } }
mit
C#
13f921e7630c05f0f62b69882d6d1c5587a06f37
Remove unnecessary whitespace.
boumenot/Grobid.NET
src/Grobid.PdfToXml/TokenBlock.cs
src/Grobid.PdfToXml/TokenBlock.cs
using System; using System.Linq; using iTextSharp.text; namespace Grobid.PdfToXml { public class TokenBlock { public static readonly TokenBlock Empty = new TokenBlock { IsEmpty = true }; public int Angle { get; set; } public float Base { get; set; } public Rectangle BoundingRectangle { get; set; } public string FontColor { get; set; } public FontFlags FontFlags { get; set; } public FontName FontName { get; set; } public float FontSize { get; set; } public float Height { get; set; } public bool IsEmpty { get; set; } public int Rotation { get; set; } public string Text { get; set; } public float Width { get; set; } public float X { get; set; } public float Y { get; set; } public bool IsBold => this.FontName.IsBold || this.FontFlags.HasFlag(FontFlags.Bold); public bool IsItalic => this.FontName.IsItalic || this.FontFlags.HasFlag(FontFlags.Italic); public bool IsSymbolic => this.FontFlags.HasFlag(FontFlags.Symbolic); public static TokenBlock Merge(TokenBlock[] tokenBlocks) { var mergedTokenBlock = tokenBlocks[0]; mergedTokenBlock.Text = String.Join(String.Empty, tokenBlocks.Select(x => x.Text)).Normalize(); mergedTokenBlock.BoundingRectangle = new Rectangle( tokenBlocks.First().BoundingRectangle.Left, tokenBlocks.First().BoundingRectangle.Bottom, tokenBlocks.Last().BoundingRectangle.Right, tokenBlocks.Last().BoundingRectangle.Top); mergedTokenBlock.Width = mergedTokenBlock.BoundingRectangle.Width; return mergedTokenBlock; } } }
using System; using System.Linq; using iTextSharp.text; namespace Grobid.PdfToXml { public class TokenBlock { public static readonly TokenBlock Empty = new TokenBlock { IsEmpty = true }; public int Angle { get; set; } public float Base { get; set; } public Rectangle BoundingRectangle { get; set; } public string FontColor { get; set; } public FontFlags FontFlags { get; set; } public FontName FontName { get; set; } public float FontSize { get; set; } public float Height { get; set; } public bool IsEmpty { get; set; } public int Rotation { get; set; } public string Text { get; set; } public float Width { get; set; } public float X { get; set; } public float Y { get; set; } public bool IsBold => this.FontName.IsBold || this.FontFlags.HasFlag(FontFlags.Bold); public bool IsItalic => this.FontName.IsItalic || this.FontFlags.HasFlag(FontFlags.Italic); public bool IsSymbolic => this.FontFlags.HasFlag(FontFlags.Symbolic); public static TokenBlock Merge(TokenBlock[] tokenBlocks) { var mergedTokenBlock = tokenBlocks[0]; mergedTokenBlock.Text = String.Join(String.Empty, tokenBlocks.Select(x => x.Text)).Normalize(); mergedTokenBlock.BoundingRectangle = new Rectangle( tokenBlocks.First().BoundingRectangle.Left, tokenBlocks.First().BoundingRectangle.Bottom, tokenBlocks.Last().BoundingRectangle.Right, tokenBlocks.Last().BoundingRectangle.Top); mergedTokenBlock.Width = mergedTokenBlock.BoundingRectangle.Width; return mergedTokenBlock; } } }
apache-2.0
C#
35918d8fff5efe69069497fa31d2c574d6217bac
Remove private qualifier on version regexes
hammerandchisel/Squirrel.Windows,jochenvangasse/Squirrel.Windows,hammerandchisel/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,NeilSorensen/Squirrel.Windows,bowencode/Squirrel.Windows,akrisiun/Squirrel.Windows,jochenvangasse/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,hammerandchisel/Squirrel.Windows,sickboy/Squirrel.Windows,kenbailey/Squirrel.Windows,punker76/Squirrel.Windows,JonMartinTx/AS400Report,BloomBooks/Squirrel.Windows,bowencode/Squirrel.Windows,1gurucoder/Squirrel.Windows,Squirrel/Squirrel.Windows,kenbailey/Squirrel.Windows,punker76/Squirrel.Windows,BloomBooks/Squirrel.Windows,NeilSorensen/Squirrel.Windows,sickboy/Squirrel.Windows,JonMartinTx/AS400Report,jbeshir/Squirrel.Windows,jbeshir/Squirrel.Windows,punker76/Squirrel.Windows,NeilSorensen/Squirrel.Windows,kenbailey/Squirrel.Windows,1gurucoder/Squirrel.Windows,JonMartinTx/AS400Report,bowencode/Squirrel.Windows,1gurucoder/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,jochenvangasse/Squirrel.Windows,BloomBooks/Squirrel.Windows,Squirrel/Squirrel.Windows,Squirrel/Squirrel.Windows,sickboy/Squirrel.Windows,jbeshir/Squirrel.Windows
src/Squirrel/ReleaseExtensions.cs
src/Squirrel/ReleaseExtensions.cs
using NuGet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Squirrel { public static class VersionExtensions { static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled); static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled); public static SemanticVersion ToSemanticVersion(this IReleasePackage package) { return package.InputPackageFile.ToSemanticVersion(); } public static SemanticVersion ToSemanticVersion(this string fileName) { var name = _suffixRegex.Replace(fileName, ""); var version = _versionRegex.Match(name).Value; return new SemanticVersion(version); } } }
using NuGet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Squirrel { public static class VersionExtensions { private static readonly Regex _suffixRegex = new Regex(@"(-full|-delta)?\.nupkg$", RegexOptions.Compiled); private static readonly Regex _versionRegex = new Regex(@"\d+(\.\d+){0,3}(-[a-z][0-9a-z-]*)?$", RegexOptions.Compiled); public static SemanticVersion ToSemanticVersion(this IReleasePackage package) { return package.InputPackageFile.ToSemanticVersion(); } public static SemanticVersion ToSemanticVersion(this string fileName) { var name = _suffixRegex.Replace(fileName, ""); var version = _versionRegex.Match(name).Value; return new SemanticVersion(version); } } }
mit
C#
7802cd236eae7f8495584f006a83d163b7ebda55
Use settings in configuration file for EntryFolder
ollejacobsen/corebrowser,ollejacobsen/corebrowser
src/CoreBrowser/Startup.cs
src/CoreBrowser/Startup.cs
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using CoreBrowser.Services; namespace CoreBrowser { public class Startup { private IHostingEnvironment _hostingEnv; public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); _hostingEnv = env; } public IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Custom service var conf = new FileSystemConfiguration(_hostingEnv.WebRootPath, Configuration["SharpBrowser:RootFolderInWWWRoot"]) .AddExcludedFileNames("web.config") .Build(); services.AddInstance<IFileSystemService>(new FileSystemService(conf)); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/CoreBrowser/Error"); } app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "error", template: "corebrowser/error", defaults: new {controller = "CoreBrowser", action = "Error"}); routes.MapRoute( name: "default", template: "{*url}", defaults: new { controller = "CoreBrowser", action = "Index" }); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using CoreBrowser.Services; namespace CoreBrowser { public class Startup { private IHostingEnvironment _hostingEnv; public Startup(IHostingEnvironment env) { // Set up configuration sources. var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddEnvironmentVariables(); Configuration = builder.Build(); _hostingEnv = env; } public IConfigurationRoot Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //Custom service var conf = new FileSystemConfiguration(_hostingEnv.WebRootPath, "files") .AddExcludedFileNames("web.config").Build(); services.AddInstance<IFileSystemService>(new FileSystemService(conf)); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/CoreBrowser/Error"); } app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "error", template: "corebrowser/error", defaults: new {controller = "CoreBrowser", action = "Error"}); routes.MapRoute( name: "default", template: "{*url}", defaults: new { controller = "CoreBrowser", action = "Index" }); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
mit
C#
96997bdf26a5301db908b349557d6f5065b545e4
Add some ConfigureAwaits
Kingloo/GB-Live
src/Gui/MainWindow.xaml.cs
src/Gui/MainWindow.xaml.cs
using System.Globalization; using System.Windows; using System.Windows.Input; using System.Windows.Markup; using GBLive.Common; namespace GBLive.Gui { public partial class MainWindow : Window { private readonly ILog _logger; private readonly IMainWindowViewModel viewModel; public MainWindow(ILog logger, IMainWindowViewModel vm) { InitializeComponent(); Loaded += Window_Loaded; KeyDown += Window_KeyDown; Closing += Window_Closing; _logger = logger; Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag); viewModel = vm; DataContext = viewModel; } private async void Window_Loaded(object sender, RoutedEventArgs e) { await viewModel.UpdateAsync().ConfigureAwait(true); viewModel.StartTimer(); } private async void Window_KeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Escape: Close(); break; case Key.F5: { _logger.Message("pressed F5, update started", Severity.Debug); await viewModel.UpdateAsync().ConfigureAwait(true); _logger.Message("update finished", Severity.Debug); break; } default: break; } } private void ItemsControl_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { viewModel.OpenHomePage(); } } private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { viewModel.OpenChatPage(); } } private void Window_Closing(object? sender, System.ComponentModel.CancelEventArgs e) { Loaded -= Window_Loaded; KeyDown -= Window_KeyDown; Closing -= Window_Closing; } private void Image_Loaded(object sender, RoutedEventArgs e) { _logger.Message("image loaded", Severity.Debug); } private void Image_Unloaded(object sender, RoutedEventArgs e) { _logger.Message("image unloaded", Severity.Debug); } private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e) { _logger.Message("image failed", Severity.Debug); } } }
using System.Globalization; using System.Windows; using System.Windows.Input; using System.Windows.Markup; using GBLive.Common; namespace GBLive.Gui { public partial class MainWindow : Window { private readonly ILog _logger; private readonly IMainWindowViewModel viewModel; public MainWindow(ILog logger, IMainWindowViewModel vm) { InitializeComponent(); Loaded += Window_Loaded; KeyDown += Window_KeyDown; Closing += Window_Closing; _logger = logger; Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag); viewModel = vm; DataContext = viewModel; } private async void Window_Loaded(object sender, RoutedEventArgs e) { await viewModel.UpdateAsync(); viewModel.StartTimer(); } private async void Window_KeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Escape: Close(); break; case Key.F5: { _logger.Message("pressed F5, update started", Severity.Debug); await viewModel.UpdateAsync(); _logger.Message("update finished", Severity.Debug); break; } default: break; } } private void ItemsControl_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { viewModel.OpenHomePage(); } } private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { viewModel.OpenChatPage(); } } private void Window_Closing(object? sender, System.ComponentModel.CancelEventArgs e) { Loaded -= Window_Loaded; KeyDown -= Window_KeyDown; Closing -= Window_Closing; } private void Image_Loaded(object sender, RoutedEventArgs e) { _logger.Message("image loaded", Severity.Debug); } private void Image_Unloaded(object sender, RoutedEventArgs e) { _logger.Message("image unloaded", Severity.Debug); } private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e) { _logger.Message("image failed", Severity.Debug); } } }
unlicense
C#
f709cfcf873a28a914fbac66d566daf5d0786ed1
Use AppContext.BaseDirectory for application path
karolberezicki/EasySnippets
EasySnippets/Utils/StartUpManager.cs
EasySnippets/Utils/StartUpManager.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.Win32; namespace EasySnippets.Utils { [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")] public class StartUpManager { public static void AddApplicationToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); key?.SetValue(curAssembly.GetName().Name, AppContext.BaseDirectory); } public static void RemoveApplicationFromCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; if (!string.IsNullOrWhiteSpace(curAssemblyName)) { key?.DeleteValue(curAssemblyName, false); } } public static bool IsApplicationAddedToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString(); return currentValue?.Equals(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) ?? false; } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using Microsoft.Win32; namespace EasySnippets.Utils { [SuppressMessage("Interoperability", "CA1416:Validate platform compatibility", Justification = "Windows only app")] public class StartUpManager { public static void AddApplicationToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); key?.SetValue(curAssembly.GetName().Name, curAssembly.Location); } public static void RemoveApplicationFromCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; if (!string.IsNullOrWhiteSpace(curAssemblyName)) { key?.DeleteValue(curAssemblyName, false); } } public static bool IsApplicationAddedToCurrentUserStartup() { using var key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true); var curAssembly = Assembly.GetExecutingAssembly(); var currentValue = key?.GetValue(curAssembly.GetName().Name, null)?.ToString(); return currentValue?.Equals(curAssembly.Location, StringComparison.InvariantCultureIgnoreCase) ?? false; } } }
mit
C#
f0e3176bc8f6709270b9393ca88f710433ad6a71
Add develop branch
prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15
FineBot/FineBot.BotRunner/Program.cs
FineBot/FineBot.BotRunner/Program.cs
using System; using System.Configuration; using Castle.Windsor; using FineBot.BotRunner.DI; using FineBot.BotRunner.Responders.Interfaces; using MargieBot; namespace FineBot.BotRunner { public class Program { private static IWindsorContainer container; static void Main(string[] args) { container = BotRunnerBootstrapper.Init(); var fineBot = new Bot(); var fineBotResponders = container.ResolveAll<IFineBotResponder>(); foreach (IFineBotResponder responder in fineBotResponders) { fineBot.Responders.Add(responder); } fineBot.RespondsTo("hi").IfBotIsMentioned().With("Stop resisting citizen!"); fineBot.CreateResponder(x => !x.BotHasResponded, rc => "My responses are limited, you must ask the right question..."); var task = fineBot.Connect(ConfigurationManager.AppSettings["BotKey"]); Console.WriteLine(string.Format("{0}: Bot is runnning, type 'die' to make it die", DateTime.Now)); var secondCousinBot = new Bot(); var secondCousinResponders = container.ResolveAll<ISecondCousinResponder>(); foreach (ISecondCousinResponder responder in secondCousinResponders) { secondCousinBot.Responders.Add(responder); } var seconderTask = secondCousinBot.Connect(ConfigurationManager.AppSettings["SeconderBotKey"]); Console.WriteLine(string.Format("{0}: Finebot's second cousin is also also running. Some say he can't die.", DateTime.Now)); while(Console.ReadLine() != "die") { } container.Dispose(); } } }
using System; using System.Configuration; using Castle.Windsor; using FineBot.API.UsersApi; using FineBot.BotRunner.DI; using FineBot.BotRunner.Responders.Interfaces; using MargieBot; using MargieBot.Responders; namespace FineBot.BotRunner { public class Program { private static IWindsorContainer container; static void Main(string[] args) { container = BotRunnerBootstrapper.Init(); var fineBot = new Bot(); var fineBotResponders = container.ResolveAll<IFineBotResponder>(); foreach (IFineBotResponder responder in fineBotResponders) { fineBot.Responders.Add(responder); } fineBot.RespondsTo("hi").IfBotIsMentioned().With("Stop resisting citizen!"); fineBot.CreateResponder(x => !x.BotHasResponded, rc => "My responses are limited, you must ask the right question..."); var task = fineBot.Connect(ConfigurationManager.AppSettings["BotKey"]); Console.WriteLine(String.Format("{0}: Bot is runnning, type 'die' to make it die", DateTime.Now)); var secondCousinBot = new Bot(); var secondCousinResponders = container.ResolveAll<ISecondCousinResponder>(); foreach (ISecondCousinResponder responder in secondCousinResponders) { secondCousinBot.Responders.Add(responder); } var seconderTask = secondCousinBot.Connect(ConfigurationManager.AppSettings["SeconderBotKey"]); Console.WriteLine(String.Format("{0}: Finebot's second cousin is also also running. Some say he can't die.", DateTime.Now)); while(Console.ReadLine() != "die") { } container.Dispose(); } } }
mit
C#
7e0f9829bc2bca4fbc00528924f2ec6c9ccde02d
build fix.
flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core
Flubu.Tests/Context/TargetFluentInterfaceTests.cs
Flubu.Tests/Context/TargetFluentInterfaceTests.cs
using FlubuCore.Context; using FlubuCore.Context.FluentInterface; using FlubuCore.Context.FluentInterface.Interfaces; using FlubuCore.Context.FluentInterface.TaskExtensions; using FlubuCore.Infrastructure; using FlubuCore.Targeting; using Moq; using Xunit; namespace Flubu.Tests.Context { public class TargetFluentInterfaceTests { private readonly TargetFluentInterface _fluent; private readonly Mock<ITaskContextInternal> _context; private readonly Mock<ITarget> _target; public TargetFluentInterfaceTests() { _context = new Mock<ITaskContextInternal>(); _target = new Mock<ITarget>(); _fluent = new TargetFluentInterface(); _fluent.Target = _target.Object; _fluent.Context = _context.Object; _fluent.CoreTaskFluent = new CoreTaskFluentInterface(new LinuxTaskFluentInterface()); _fluent.TaskFluent = new TaskFluentInterface(new IisTaskFluentInterface(), new WebApiFluentInterface(), new HttpClientFactory()); _fluent.TaskExtensionsFluent = new TaskExtensionsFluentInterface(); } [Fact] public void DependsOnStringTest() { ITargetFluentInterface t = _fluent.DependsOn("target1"); Assert.NotNull(t); _target.Verify(i => i.DependsOn("target1"), Times.Once); } [Fact] public void DependsOnTargetTest() { Mock<ITarget> target1 = new Mock<ITarget>(); ITargetFluentInterface t = _fluent.DependsOn(target1.Object); Assert.NotNull(t); _target.Verify(i => i.DependsOn(target1.Object), Times.Once); } private void Test(ITaskContext context, string test) { var x = test; } } }
using FlubuCore.Context; using FlubuCore.Context.FluentInterface; using FlubuCore.Context.FluentInterface.Interfaces; using FlubuCore.Context.FluentInterface.TaskExtensions; using FlubuCore.Targeting; using Moq; using Xunit; namespace Flubu.Tests.Context { public class TargetFluentInterfaceTests { private readonly TargetFluentInterface _fluent; private readonly Mock<ITaskContextInternal> _context; private readonly Mock<ITarget> _target; public TargetFluentInterfaceTests() { _context = new Mock<ITaskContextInternal>(); _target = new Mock<ITarget>(); _fluent = new TargetFluentInterface(); _fluent.Target = _target.Object; _fluent.Context = _context.Object; _fluent.CoreTaskFluent = new CoreTaskFluentInterface(new LinuxTaskFluentInterface()); _fluent.TaskFluent = new TaskFluentInterface(new IisTaskFluentInterface(), new WebApiFluentInterface()); _fluent.TaskExtensionsFluent = new TaskExtensionsFluentInterface(); } [Fact] public void DependsOnStringTest() { ITargetFluentInterface t = _fluent.DependsOn("target1"); Assert.NotNull(t); _target.Verify(i => i.DependsOn("target1"), Times.Once); } [Fact] public void DependsOnTargetTest() { Mock<ITarget> target1 = new Mock<ITarget>(); ITargetFluentInterface t = _fluent.DependsOn(target1.Object); Assert.NotNull(t); _target.Verify(i => i.DependsOn(target1.Object), Times.Once); } private void Test(ITaskContext context, string test) { var x = test; } } }
bsd-2-clause
C#
4c0a8d65b48d2a4ed1dad3742d3f531c511659fe
Fix incorrect null check in ResponseInfo.cs for iOS.
googleads/googleads-mobile-unity,googleads/googleads-mobile-unity
source/plugin/Assets/GoogleMobileAds/Platforms/iOS/ResponseInfoClient.cs
source/plugin/Assets/GoogleMobileAds/Platforms/iOS/ResponseInfoClient.cs
#if UNITY_IOS // Copyright (C) 2020 Google, LLC // // 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 UnityEngine; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { internal class ResponseInfoClient : IResponseInfoClient { private IntPtr adFormat; private IntPtr iosResponseInfo; public ResponseInfoClient(ResponseInfoClientType type, IntPtr ptr) { if(type == ResponseInfoClientType.AdLoaded) { this.adFormat = adFormat; iosResponseInfo = Externs.GADUGetResponseInfo(ptr); } else if(type == ResponseInfoClientType.AdError) { iosResponseInfo = Externs.GADUGetAdErrorResponseInfo(ptr); } } public ResponseInfoClient(IntPtr adFormat, IntPtr iOSClient) { this.adFormat = adFormat; iosResponseInfo = iOSClient; } public string GetMediationAdapterClassName() { if (iosResponseInfo != IntPtr.Zero) { return Externs.GADUResponseInfoMediationAdapterClassName(iosResponseInfo); } return null; } public string GetResponseId() { if (iosResponseInfo != IntPtr.Zero) { return Externs.GADUResponseInfoResponseId(iosResponseInfo); } return null; } public override string ToString() { return Externs.GADUGetResponseInfoDescription(iosResponseInfo); } } } #endif
#if UNITY_IOS // Copyright (C) 2020 Google, LLC // // 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 UnityEngine; using GoogleMobileAds.Api; using GoogleMobileAds.Common; namespace GoogleMobileAds.iOS { internal class ResponseInfoClient : IResponseInfoClient { private IntPtr adFormat; private IntPtr iosResponseInfo; public ResponseInfoClient(ResponseInfoClientType type, IntPtr ptr) { if(type == ResponseInfoClientType.AdLoaded) { this.adFormat = adFormat; iosResponseInfo = Externs.GADUGetResponseInfo(ptr); } else if(type == ResponseInfoClientType.AdError) { iosResponseInfo = Externs.GADUGetAdErrorResponseInfo(ptr); } } public ResponseInfoClient(IntPtr adFormat, IntPtr iOSClient) { this.adFormat = adFormat; iosResponseInfo = iOSClient; } public string GetMediationAdapterClassName() { if (iosResponseInfo != null) { return Externs.GADUResponseInfoMediationAdapterClassName(iosResponseInfo); } return null; } public string GetResponseId() { if (iosResponseInfo != null) { return Externs.GADUResponseInfoResponseId(iosResponseInfo); } return null; } public override string ToString() { return Externs.GADUGetResponseInfoDescription(iosResponseInfo); } } } #endif
apache-2.0
C#
1d0cc99110cc5e0e7e8c06f2d0ef93db0b182ffe
Remove http from the value attribute.
SonOfSam/JabbR,clarktestkudu1029/test08jabbr,mogultest2/Project13171210,mogulTest1/Project13231113,meebey/JabbR,mogultest2/Project13231008,mogulTest1/Project13231205,clarktestkudu1029/test08jabbr,fuzeman/vox,ClarkL/1317on17jabbr,mogulTest1/ProjectfoIssue6,mogulTest1/Project91409,mogulTest1/Project13231205,ClarkL/1323on17jabbr-,18098924759/JabbR,ClarkL/new1317,mogulTest1/Project91101,mogulTest1/Project13171205,mogultest2/Project92109,borisyankov/JabbR,mogulTest1/Project13171009,MogulTestOrg2/JabbrApp,mogulTest1/Project90301,MogulTestOrg1008/Project13221008,mogultest2/Project92109,mogulTest1/ProjectJabbr01,MogulTestOrg9221/Project92108,Org1106/Project13221106,mogulTest1/ProjectfoIssue6,mogulTest1/Project91101,CrankyTRex/JabbRMirror,mogulTest1/MogulVerifyIssue5,mogultest2/Project92104,MogulTestOrg911/Project91104,meebey/JabbR,mogulTest1/Project91404,v-mohua/TestProject91001,yadyn/JabbR,ClarkL/test09jabbr,KuduApps/TestDeploy123,mogulTest1/Project91105,mogulTest1/Project13161127,mogulTest1/Project13231212,mogultest2/Project13171210,mogulTest1/MogulVerifyIssue5,mogulTest1/Project13171109,mogulTest1/Project13231106,mogultest2/Project13171008,ClarkL/new1317,CrankyTRex/JabbRMirror,mogulTest1/Project13171024,mogulTest1/ProjectVerify912,LookLikeAPro/JabbR,18098924759/JabbR,mogulTest1/Project90301,mogulTest1/Project13231213,ClarkL/new09,lukehoban/JabbR,KuduApps/TestDeploy123,Org1106/Project13221106,ClarkL/test09jabbr,yadyn/JabbR,lukehoban/JabbR,mzdv/JabbR,mogulTest1/Project13231106,JabbR/JabbR,mogulTest1/Project13231109,ajayanandgit/JabbR,huanglitest/JabbRTest2,mogultest2/Project13171008,test0925/test0925,mogulTest1/Project91105,yadyn/JabbR,aapttester/jack12051317,huanglitest/JabbRTest2,ClarkL/new09,MogulTestOrg/JabbrApp,LookLikeAPro/JabbR,mogultest2/Project13171010,mogulTest1/Project13161127,mogultest2/Project13231008,AAPT/jean0226case1322,kudutest/FaizJabbr,AAPT/jean0226case1322,mogulTest1/Project91409,test0925/test0925,fuzeman/vox,mogulTest1/Project13171106,mogultest2/Project92105,mogulTest1/Project13171024,MogulTestOrg/JabbrApp,M-Zuber/JabbR,mogulTest1/Project91404,timgranstrom/JabbR,LookLikeAPro/JabbR,mogulTest1/Project91009,mogultest2/Project92105,mogulTest1/Project13171106,MogulTestOrg914/Project91407,timgranstrom/JabbR,mogultest2/Project92104,MogulTestOrg2/JabbrApp,MogulTestOrg1008/Project13221008,Org1106/Project13221113,mogulTest1/Project13171109,ajayanandgit/JabbR,huanglitest/JabbRTest2,MogulTestOrg914/Project91407,e10/JabbR,mogulTest1/ProjectVerify912,MogulTestOrg911/Project91104,Createfor1322/jessica0122-1322,fuzeman/vox,e10/JabbR,JabbR/JabbR,MogulTestOrg9221/Project92108,mogulTest1/Project13231212,mogulTest1/Project13171113,mogulTest1/Project91009,M-Zuber/JabbR,mogulTest1/Project13231213,v-mohua/TestProject91001,meebey/JabbR,borisyankov/JabbR,Org1106/Project13221113,mogulTest1/Project13171113,mogulTest1/Project13171205,mogulTest1/Project13171009,SonOfSam/JabbR,lukehoban/JabbR,mogulTest1/Project13231109,mogulTest1/ProjectJabbr01,ClarkL/1317on17jabbr,kudutest/FaizJabbr,mogulTest1/Project13231113,mogultest2/Project13171010,CrankyTRex/JabbRMirror,borisyankov/JabbR,aapttester/jack12051317,Createfor1322/jessica0122-1322,mzdv/JabbR,ClarkL/1323on17jabbr-
JabbR/ContentProviders/MixcloudContentProvider.cs
JabbR/ContentProviders/MixcloudContentProvider.cs
using System; using System.Collections.Generic; using JabbR.ContentProviders.Core; namespace JabbR.ContentProviders { public class MixcloudContentProvider : EmbedContentProvider { public override string MediaFormatString { get { return "<object width=\"100%\" height=\"120\"><param name=\"movie\" value=\"//www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed={0}&embed_uuid=06c5d381-1643-407d-80e7-2812382408e9&stylecolor=1e2671&embed_type=widget_standard\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"wmode\" value=\"opaque\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"//www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed={0}&embed_uuid=06c5d381-1643-407d-80e7-2812382408e9&stylecolor=1e2671&embed_type=widget_standard\" type=\"application/x-shockwave-flash\" wmode=\"opaque\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"100%\" height=\"120\"></embed></object>"; } } public override IEnumerable<string> Domains { get { yield return "http://www.mixcloud.com/"; } } protected override IList<string> ExtractParameters(Uri responseUri) { return new List<string>() { responseUri.AbsoluteUri }; } } }
using System; using System.Collections.Generic; using JabbR.ContentProviders.Core; namespace JabbR.ContentProviders { public class MixcloudContentProvider : EmbedContentProvider { public override string MediaFormatString { get { return "<object width=\"100%\" height=\"120\"><param name=\"movie\" value=\"http://www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed={0}&embed_uuid=06c5d381-1643-407d-80e7-2812382408e9&stylecolor=1e2671&embed_type=widget_standard\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"wmode\" value=\"opaque\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"//www.mixcloud.com/media/swf/player/mixcloudLoader.swf?feed={0}&embed_uuid=06c5d381-1643-407d-80e7-2812382408e9&stylecolor=1e2671&embed_type=widget_standard\" type=\"application/x-shockwave-flash\" wmode=\"opaque\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"100%\" height=\"120\"></embed></object>"; } } public override IEnumerable<string> Domains { get { yield return "http://www.mixcloud.com/"; } } protected override IList<string> ExtractParameters(Uri responseUri) { return new List<string>() { responseUri.AbsoluteUri }; } } }
mit
C#
68f6d8fc8d61f47a981532b7ba559affcfccdd0b
Test for #1315: Ensure it works multiple inheritance levels deep.
autofac/Autofac
test/Autofac.Specification.Test/Registration/OpenGenericTests.cs
test/Autofac.Specification.Test/Registration/OpenGenericTests.cs
// Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Autofac.Test.Scenarios.Graph1.GenericConstraints; namespace Autofac.Specification.Test.Registration; public class OpenGenericTests { private interface IImplementedInterface<T> { } [Fact] public void AsImplementedInterfacesOnOpenGeneric() { var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(SelfComponent<>)).AsImplementedInterfaces(); var context = builder.Build(); context.Resolve<IImplementedInterface<object>>(); } [Fact] public void AsSelfOnOpenGeneric() { var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(SelfComponent<>)).AsSelf(); var context = builder.Build(); context.Resolve<SelfComponent<object>>(); } [Fact] public void ResolveWithMultipleCandidatesLimitedByGenericConstraintsShouldSucceed() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType<A>().As<IA>(); containerBuilder.RegisterGeneric(typeof(Unrelated<>)).As(typeof(IB<>)); containerBuilder.RegisterType<Required>().As<IB<ClassWithParameterlessButNotPublicConstructor>>(); var container = containerBuilder.Build(); var resolved = container.Resolve<IA>(); Assert.NotNull(resolved); } // Issue #1315: Class services fail to resolve if the names on the type // arguments are changed. [Fact] public void ResolveClassWithRenamedTypeArguments() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterGeneric(typeof(DerivedRepository<,>)).As(typeof(BaseRepository<,>)); var container = containerBuilder.Build(); var resolved = container.Resolve<BaseRepository<string, int>>(); Assert.IsType<DerivedRepository<int, string>>(resolved); } // Issue #1315: Class services fail to resolve if the names on the type // arguments are changed. We should be able to handle a deep inheritance chain. [Fact] public void ResolveClassTwoLevelsDownWithRenamedTypeArguments() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterGeneric(typeof(TwoLevelsDerivedRepository<,>)).As(typeof(BaseRepository<,>)); var container = containerBuilder.Build(); var resolved = container.Resolve<BaseRepository<string, int>>(); Assert.IsType<TwoLevelsDerivedRepository<int, string>>(resolved); } private class SelfComponent<T> : IImplementedInterface<T> { } private class BaseRepository<T1, T2> { } // Issue #1315: Class services fail to resolve if the names on the type // arguments are changed. private class DerivedRepository<TSecond, TFirst> : BaseRepository<TFirst, TSecond> { } private class TwoLevelsDerivedRepository<TA, TB> : DerivedRepository<TA, TB> { } }
// Copyright (c) Autofac Project. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Autofac.Test.Scenarios.Graph1.GenericConstraints; namespace Autofac.Specification.Test.Registration; public class OpenGenericTests { private interface IImplementedInterface<T> { } [Fact] public void AsImplementedInterfacesOnOpenGeneric() { var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(SelfComponent<>)).AsImplementedInterfaces(); var context = builder.Build(); context.Resolve<IImplementedInterface<object>>(); } [Fact] public void AsSelfOnOpenGeneric() { var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(SelfComponent<>)).AsSelf(); var context = builder.Build(); context.Resolve<SelfComponent<object>>(); } [Fact] public void ResolveWithMultipleCandidatesLimitedByGenericConstraintsShouldSucceed() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterType<A>().As<IA>(); containerBuilder.RegisterGeneric(typeof(Unrelated<>)).As(typeof(IB<>)); containerBuilder.RegisterType<Required>().As<IB<ClassWithParameterlessButNotPublicConstructor>>(); var container = containerBuilder.Build(); var resolved = container.Resolve<IA>(); Assert.NotNull(resolved); } // Issue #1315: Class services fail to resolve if the names on the type // arguments are changed. [Fact] public void ResolveClassWithRenamedTypeArguments() { var containerBuilder = new ContainerBuilder(); containerBuilder.RegisterGeneric(typeof(DerivedRepository<,>)).As(typeof(BaseRepository<,>)); var container = containerBuilder.Build(); var resolved = container.Resolve<BaseRepository<string, int>>(); Assert.IsType<DerivedRepository<int, string>>(resolved); } private class SelfComponent<T> : IImplementedInterface<T> { } private class BaseRepository<T1, T2> { } // Issue #1315: Class services fail to resolve if the names on the type // arguments are changed. private class DerivedRepository<TSecond, TFirst> : BaseRepository<TFirst, TSecond> { } }
mit
C#
b34dd3b8121d0c702e6595602decc9a6e6b43118
Remove options order test cases
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultOrderTest.cs
test/Microsoft.AspNet.Mvc.FunctionalTests/DefaultOrderTest.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; using System.Net; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.ActionConstraints; using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.ApiExplorer; using Microsoft.AspNet.Mvc.Filters; using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { // Tests that various MVC services have the correct order. public class DefaultOrderTest { private const string SiteName = nameof(BasicWebSite); private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure; private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices; [Theory] [InlineData(typeof(IActionDescriptorProvider), typeof(ControllerActionDescriptorProvider), -1000)] [InlineData(typeof(IActionInvokerProvider), null, -1000)] [InlineData(typeof(IApiDescriptionProvider), null, -1000)] [InlineData(typeof(IFilterProvider), null, -1000)] [InlineData(typeof(IActionConstraintProvider), null, -1000)] public async Task ServiceOrder_GetOrder(Type serviceType, Type actualType, int order) { // Arrange var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var client = server.CreateClient(); var url = "http://localhost/Order/GetServiceOrder?serviceType=" + serviceType.AssemblyQualifiedName; if (actualType != null) { url += "&actualType=" + actualType.AssemblyQualifiedName; } // Act var response = await client.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(order, int.Parse(content)); } } }
// 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; using System.Net; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc.ActionConstraints; using Microsoft.AspNet.Mvc.Actions; using Microsoft.AspNet.Mvc.ApiExplorer; using Microsoft.AspNet.Mvc.Filters; using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.AspNet.Mvc.FunctionalTests { // Tests that various MVC services have the correct order. public class DefaultOrderTest { private const string SiteName = nameof(BasicWebSite); private readonly Action<IApplicationBuilder> _app = new BasicWebSite.Startup().Configure; private readonly Action<IServiceCollection> _configureServices = new BasicWebSite.Startup().ConfigureServices; [Theory] [InlineData(typeof(IActionDescriptorProvider), typeof(ControllerActionDescriptorProvider), -1000)] [InlineData(typeof(IActionInvokerProvider), null, -1000)] [InlineData(typeof(IApiDescriptionProvider), null, -1000)] [InlineData(typeof(IFilterProvider), null, -1000)] [InlineData(typeof(IActionConstraintProvider), null, -1000)] // REVIEW: Options no longer has order //[InlineData(typeof(IConfigureOptions<RazorViewEngineOptions>), null, -1000)] //[InlineData(typeof(IConfigureOptions<MvcOptions>), null, -1000)] public async Task ServiceOrder_GetOrder(Type serviceType, Type actualType, int order) { // Arrange var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var client = server.CreateClient(); var url = "http://localhost/Order/GetServiceOrder?serviceType=" + serviceType.AssemblyQualifiedName; if (actualType != null) { url += "&actualType=" + actualType.AssemblyQualifiedName; } // Act var response = await client.GetAsync(url); var content = await response.Content.ReadAsStringAsync(); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(order, int.Parse(content)); } } }
apache-2.0
C#
50b015d9fcffc94f95535bbe6f28ae82da7f92d3
test cases
jefking/King.A-Trak
King.ATrak.Test/ContentTypesTests.cs
King.ATrak.Test/ContentTypesTests.cs
namespace King.ATrak.Test { using King.ATrak; using NUnit.Framework; using System; [TestFixture] public class ContentTypesTests { [Test] [ExpectedException(typeof(ArgumentException))] public void ContentTypeFilePathInvalid() { ContentTypes.ContentType(null); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void ContentTypeFilePathWierd() { ContentTypes.ContentType(". "); } [TestCase("image/jpeg", ".jpg")] [TestCase("text/css", ".css")] [TestCase("image/png", ".png")] [TestCase("image/x-icon", ".ico")] [TestCase("text/plain", ".txt")] public void Types(string expected, string extension) { Assert.AreEqual(expected, ContentTypes.ContentType(extension)); } [TestCase("image/jpeg", ".jpg")] [TestCase("text/css", ".css")] [TestCase("image/png", ".png")] [TestCase("image/x-icon", ".ico")] [TestCase("text/plain", ".txt")] public void TypesCached(string expected, string extension) { Assert.AreEqual(expected, ContentTypes.ContentType(extension)); Assert.AreEqual(expected, ContentTypes.ContentType(extension)); Assert.AreEqual(expected, ContentTypes.ContentType(extension)); } } }
namespace King.ATrak.Test { using King.ATrak; using NUnit.Framework; using System; [TestFixture] public class ContentTypesTests { [Test] [ExpectedException(typeof(ArgumentException))] public void ContentTypeFilePathInvalid() { ContentTypes.ContentType(null); } } }
mit
C#
2626ab41c3e38b775896c652c59f7b4b0ee335d4
Add implicit braces for clarity
smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu
osu.Game/Screens/Play/ComboEffects.cs
osu.Game/Screens/Play/ComboEffects.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Audio; using osu.Game.Configuration; using osu.Game.Rulesets.Scoring; using osu.Game.Skinning; namespace osu.Game.Screens.Play { public class ComboEffects : CompositeDrawable { private readonly ScoreProcessor processor; private SkinnableSound comboBreakSample; private Bindable<bool> alwaysPlay; private bool firstTime = true; public ComboEffects(ScoreProcessor processor) { this.processor = processor; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) { InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("combobreak")); alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak); } protected override void LoadComplete() { base.LoadComplete(); processor.Combo.BindValueChanged(onComboChange); } private void onComboChange(ValueChangedEvent<int> combo) { if (combo.NewValue == 0 && (combo.OldValue > 20 || (alwaysPlay.Value && firstTime))) { comboBreakSample?.Play(); firstTime = false; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Audio; using osu.Game.Configuration; using osu.Game.Rulesets.Scoring; using osu.Game.Skinning; namespace osu.Game.Screens.Play { public class ComboEffects : CompositeDrawable { private readonly ScoreProcessor processor; private SkinnableSound comboBreakSample; private Bindable<bool> alwaysPlay; private bool firstTime = true; public ComboEffects(ScoreProcessor processor) { this.processor = processor; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) { InternalChild = comboBreakSample = new SkinnableSound(new SampleInfo("combobreak")); alwaysPlay = config.GetBindable<bool>(OsuSetting.AlwaysPlayFirstComboBreak); } protected override void LoadComplete() { base.LoadComplete(); processor.Combo.BindValueChanged(onComboChange); } private void onComboChange(ValueChangedEvent<int> combo) { if (combo.NewValue == 0 && (combo.OldValue > 20 || alwaysPlay.Value && firstTime)) { comboBreakSample?.Play(); firstTime = false; } } } }
mit
C#
5ad540c5bc4138b7991693faba8587bed5fd66c6
Update CreateObjectAction.cs
UnityTechnologies/PlaygroundProject,UnityTechnologies/PlaygroundProject
PlaygroundProject/Assets/Scripts/Conditions/Actions/CreateObjectAction.cs
PlaygroundProject/Assets/Scripts/Conditions/Actions/CreateObjectAction.cs
using UnityEngine; using System.Collections; [AddComponentMenu("Playground/Actions/Create Object")] public class CreateObjectAction : Action { public GameObject prefabToCreate; public Vector2 newPosition; public bool relative; void Update () { if (relative) { newPosition = transform.localPosition; } } // Moves the gameObject instantly to a custom position public override bool ExecuteAction(GameObject dataObject) { if(prefabToCreate != null) { //create the new object by copying the prefab GameObject newObject = Instantiate<GameObject>(prefabToCreate); //let's place it in the desired position! newObject.transform.position = newPosition; return true; } else { return false; } } }
using UnityEngine; using System.Collections; [AddComponentMenu("Playground/Actions/Create Object")] public class CreateObjectAction : Action { public GameObject prefabToCreate; public Vector3 newPosition; // Moves the gameObject instantly to a custom position public override bool ExecuteAction(GameObject dataObject) { if(prefabToCreate != null) { //create the new object by copying the prefab GameObject newObject = Instantiate<GameObject>(prefabToCreate); //let's place it in the desired position! newObject.transform.position = newPosition; return true; } else { return false; } } }
mit
C#
6a8d2a1857750c622d3a165fad48532e5a0c0107
make service helper public allowing validation that health services have been registered in extension packages
AppMetrics/Health,AppMetrics/Health
src/App.Metrics.Health/DependencyInjection/Internal/HealthServicesHelper.cs
src/App.Metrics.Health/DependencyInjection/Internal/HealthServicesHelper.cs
// <copyright file="HealthServicesHelper.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> using System; using System.Diagnostics.CodeAnalysis; namespace App.Metrics.Health.DependencyInjection.Internal { [ExcludeFromCodeCoverage] public static class HealthServicesHelper { /// <summary> /// Throws InvalidOperationException when MetricsMarkerService is not present /// in the list of services. /// </summary> /// <param name="services">The list of services.</param> public static void ThrowIfHealthChecksNotRegistered(IServiceProvider services) { if (services.GetService(typeof(HealthCheckMarkerService)) == null) { throw new InvalidOperationException("IServiceCollection.AddHealth() needs to be configured on Startup"); } } public static void ThrowIfHealthAddChecksHasAlreadyBeenCalled(IServiceProvider services) { if (services.GetService(typeof(HealthCheckFluentMarkerService)) != null) { throw new InvalidOperationException("IServiceCollection.AddHealth().AddChecks() can only be called once."); } } } }
// <copyright file="HealthServicesHelper.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> using System; using System.Diagnostics.CodeAnalysis; namespace App.Metrics.Health.DependencyInjection.Internal { [ExcludeFromCodeCoverage] internal static class HealthServicesHelper { /// <summary> /// Throws InvalidOperationException when MetricsMarkerService is not present /// in the list of services. /// </summary> /// <param name="services">The list of services.</param> public static void ThrowIfHealthChecksNotRegistered(IServiceProvider services) { if (services.GetService(typeof(HealthCheckMarkerService)) == null) { throw new InvalidOperationException("IServiceCollection.AddHealth() needs to be configured on Startup"); } } public static void ThrowIfHealthAddChecksHasAlreadyBeenCalled(IServiceProvider services) { if (services.GetService(typeof(HealthCheckFluentMarkerService)) != null) { throw new InvalidOperationException("IServiceCollection.AddHealth().AddChecks() can only be called once."); } } } }
apache-2.0
C#
b0a758253f03cf67ce5f9682ff6f3a3c9625d010
add of db connection
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Providers/EmailAlertProvider.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Providers/EmailAlertProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Appleseed.Base.Alerts.Model; using System.Data; namespace Appleseed.Base.Alerts.Providers { class EmailAlertProvider : IAlert { static IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); static List<UserAlert> GetUserAlertSchedules(string scheudle) { var userAlerts = db.Query<UserAlert>("GetPortalUserAlerts", new { alert_schedule = scheudle }, commandType: CommandType.StoredProcedure).ToList<UserAlert>(); return userAlerts; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Appleseed.Base.Alerts.Model; namespace Appleseed.Base.Alerts.Providers { class EmailAlertProvider : IAlert { } }
apache-2.0
C#
7efda0c014b34f46f4e83d19ae312d12a027655b
Update Program.cs
miladinoviczeljko/GitTest1
ConsoleApp1/ConsoleApp1/Program.cs
ConsoleApp1/ConsoleApp1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // Code was edited in GitHub // Code was added in VS // Code to call Feature 1 // Code to call Feature 3 } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { // Code was edited in GitHub // Code was added in VS // Code to call Feature1 } } }
mit
C#
c904bd123b209ad5b42f48f3a4ef33616b387734
Remove [Flags] from RegistryKeyPermissionCheck (#31998)
ericstj/corefx,wtgodbe/corefx,ptoonen/corefx,ViktorHofer/corefx,ViktorHofer/corefx,mmitche/corefx,shimingsg/corefx,Jiayili1/corefx,wtgodbe/corefx,Jiayili1/corefx,ViktorHofer/corefx,ericstj/corefx,ericstj/corefx,ericstj/corefx,BrennanConroy/corefx,ptoonen/corefx,BrennanConroy/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,shimingsg/corefx,Jiayili1/corefx,wtgodbe/corefx,ptoonen/corefx,Jiayili1/corefx,ericstj/corefx,Jiayili1/corefx,mmitche/corefx,BrennanConroy/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,mmitche/corefx,Jiayili1/corefx,mmitche/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,mmitche/corefx,wtgodbe/corefx,wtgodbe/corefx,ericstj/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,Jiayili1/corefx,ViktorHofer/corefx,mmitche/corefx,shimingsg/corefx,ptoonen/corefx
src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKeyPermissionCheck.cs
src/Microsoft.Win32.Registry/src/Microsoft/Win32/RegistryKeyPermissionCheck.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; namespace Microsoft.Win32 { #if REGISTRY_ASSEMBLY public #else internal #endif enum RegistryKeyPermissionCheck { Default = 0, ReadSubTree = 1, ReadWriteSubTree = 2, }; }
// 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; namespace Microsoft.Win32 { [Flags] #if REGISTRY_ASSEMBLY public #else internal #endif enum RegistryKeyPermissionCheck { Default = 0, ReadSubTree = 1, ReadWriteSubTree = 2, }; }
mit
C#
2f01aa3d97a356ae896f660591af9f2a9d51cc14
Fix minor issue
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerTeam/Index.cshtml
src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerTeam/Index.cshtml
@model SFA.DAS.EmployerApprenticeshipsService.Web.OrchestratorResponse<SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account.Account> <h1 class="heading-xlarge" id="company-Name">@Model.Data.Name</h1> <div class="grid-row"> <div class="column-two-thirds"> <div style="max-width: 90%"> <div class="grid-row"> <div class="column-half"> <h3 class="heading-medium" style="margin-top: 0;"> <a href="@Url.Action("View", new { accountId = Model.Data.Id })">Team</a> </h3> <p>Invite new users and manage existing ones</p> </div> <div class="column-half "> <h3 class="heading-medium" style="margin-top: 0"> <a href="@Url.Action("Index", "EmployerAccountTransactions", new { accountId = Model.Data.Id })">Funding</a> </h3> <p>Manage your funds including how much you have available to spend, your transactions and funds you could lose</p> </div> </div> <div class="grid-row"> <div class="column-half "> <h3 class="heading-medium" style="margin-top: 0"> <a href="@Url.Action("Index", "EmployerAgreement", new { accountId = Model.Data.Id })">Agreements</a> </h3> <p>Manage your agreements</p> </div> <div class="column-half"> <h3 class="heading-medium" style="margin-top: 0;"> <a href="@Url.Action("Index", "EmployerAccountPaye", new { accountId = Model.Data.Id })">PAYE</a> </h3> <p>Manage the PAYE schemes associated with your Account</p> </div> </div> </div> </div> </div>
@model SFA.DAS.EmployerApprenticeshipsService.Web.OrchestratorResponse<SFA.DAS.EmployerApprenticeshipsService.Domain.Entities.Account.Account> <h1 class="heading-xlarge" id="company-Name">@Model.Data.Name</h1> <div class="grid-row"> <div class="column-two-thirds"> <div style="max-width: 90%"> <div class="grid-row"> <div class="column-half"> <h3 class="heading-medium" style="margin-top: 0;"> <a href="@Url.Action("View", new { accountId = Model.Data.Id })">Team</a> </h3> <p>Invite new users and manage existing ones</p> </div> <div class="column-half "> <h3 class="heading-medium" style="margin-top: 0"> <a href="@Url.Action("Index", "EmployerAccountTransactions", new { accountId = Model.Data.Id })">Funding</a> </h3> <p>Manage your funds including how much you have available to spend, your transactions and funds you could lose</p> </div> </div> <div class="grid-row"> <div class="column-half "> <h3 class="heading-medium" style="margin-top: 0"> <a href="@Url.Action("Index", "EmployerAgreement", new { accountId = Model.Id })">Agreements</a> </h3> <p>Manage your agreements</p> </div> <div class="column-half"> <h3 class="heading-medium" style="margin-top: 0;"> <a href="@Url.Action("Index", "EmployerAccountPaye", new { accountId = Model.Data.Id })">PAYE</a> </h3> <p>Manage the PAYE schemes associated with your Account</p> </div> </div> </div> </div> </div>
mit
C#
2b8610447a0c739ebee33cd3d4a94d12e0aed53c
Simplify expressino
weltkante/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,davkean/roslyn,weltkante/roslyn,jmarolf/roslyn,diryboy/roslyn,gafter/roslyn,gafter/roslyn,genlu/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,tmat/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,ErikSchierboom/roslyn,davkean/roslyn,tmat/roslyn,genlu/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,physhi/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,brettfo/roslyn,AmadeusW/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,stephentoub/roslyn,dotnet/roslyn,diryboy/roslyn,aelij/roslyn,tannergooding/roslyn,heejaechang/roslyn,reaction1989/roslyn,brettfo/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,genlu/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,physhi/roslyn,stephentoub/roslyn,AmadeusW/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,gafter/roslyn,diryboy/roslyn,eriawan/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,davkean/roslyn,mavasani/roslyn,tannergooding/roslyn,jmarolf/roslyn,dotnet/roslyn,aelij/roslyn,jmarolf/roslyn,brettfo/roslyn,bartdesmet/roslyn,heejaechang/roslyn,KevinRansom/roslyn,sharwell/roslyn,KevinRansom/roslyn,wvdd007/roslyn,physhi/roslyn,stephentoub/roslyn
src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldInfo.cs
src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationFieldInfo.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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationFieldInfo { private static readonly ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo> s_fieldToInfoMap = new ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo>(); private readonly bool _isUnsafe; private readonly bool _isWithEvents; private readonly SyntaxNode _initializer; private CodeGenerationFieldInfo( bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { _isUnsafe = isUnsafe; _isWithEvents = isWithEvents; _initializer = initializer; } public static void Attach( IFieldSymbol field, bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { var info = new CodeGenerationFieldInfo(isUnsafe, isWithEvents, initializer); s_fieldToInfoMap.Add(field, info); } private static CodeGenerationFieldInfo GetInfo(IFieldSymbol field) { s_fieldToInfoMap.TryGetValue(field, out var info); return info; } private static bool GetIsUnsafe(CodeGenerationFieldInfo info) { return info != null && info._isUnsafe; } public static bool GetIsUnsafe(IFieldSymbol field) { return GetIsUnsafe(GetInfo(field)); } private static bool GetIsWithEvents(CodeGenerationFieldInfo info) { return info != null && info._isWithEvents; } public static bool GetIsWithEvents(IFieldSymbol field) { return GetIsWithEvents(GetInfo(field)); } private static SyntaxNode GetInitializer(CodeGenerationFieldInfo info) => info?._initializer; public static SyntaxNode GetInitializer(IFieldSymbol field) { return GetInitializer(GetInfo(field)); } } }
// 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.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CodeGeneration { internal class CodeGenerationFieldInfo { private static readonly ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo> s_fieldToInfoMap = new ConditionalWeakTable<IFieldSymbol, CodeGenerationFieldInfo>(); private readonly bool _isUnsafe; private readonly bool _isWithEvents; private readonly SyntaxNode _initializer; private CodeGenerationFieldInfo( bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { _isUnsafe = isUnsafe; _isWithEvents = isWithEvents; _initializer = initializer; } public static void Attach( IFieldSymbol field, bool isUnsafe, bool isWithEvents, SyntaxNode initializer) { var info = new CodeGenerationFieldInfo(isUnsafe, isWithEvents, initializer); s_fieldToInfoMap.Add(field, info); } private static CodeGenerationFieldInfo GetInfo(IFieldSymbol field) { s_fieldToInfoMap.TryGetValue(field, out var info); return info; } private static bool GetIsUnsafe(CodeGenerationFieldInfo info) { return info != null && info._isUnsafe; } public static bool GetIsUnsafe(IFieldSymbol field) { return GetIsUnsafe(GetInfo(field)); } private static bool GetIsWithEvents(CodeGenerationFieldInfo info) { return info != null && info._isWithEvents; } public static bool GetIsWithEvents(IFieldSymbol field) { return GetIsWithEvents(GetInfo(field)); } private static SyntaxNode GetInitializer(CodeGenerationFieldInfo info) { return info == null ? null : info._initializer; } public static SyntaxNode GetInitializer(IFieldSymbol field) { return GetInitializer(GetInfo(field)); } } }
mit
C#
312a036743b8e65231ce729cecd1e2493295b507
Move StringExtensions to the Eco.Extensions namespace.
lukyad/Eco
Eco/Extensions/StringExtensions.cs
Eco/Extensions/StringExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Eco.Extensions { public static class StringExtensions { public static string[] SplitAndTrim(this string str) { return SplitAndTrim(str, ','); } public static string[] SplitAndTrim(this string str, params char[] delimiters) { return str.Split(delimiters).Select(s => s.Trim()).ToArray(); } public static string ToUpperCamel(this string word) { return String.Format("{0}{1}", word[0].ToString().ToUpperInvariant(), word.Substring(1) ); } public static string ToLowerCamel(this string word) { return String.Format("{0}{1}", word[0].ToString().ToLowerInvariant(), word.Substring(1) ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Eco { public static class StringExtensions { public static string[] SplitAndTrim(this string str) { return SplitAndTrim(str, ','); } public static string[] SplitAndTrim(this string str, params char[] delimiters) { return str.Split(delimiters).Select(s => s.Trim()).ToArray(); } public static string ToUpperCamel(this string word) { return String.Format("{0}{1}", word[0].ToString().ToUpperInvariant(), word.Substring(1) ); } public static string ToLowerCamel(this string word) { return String.Format("{0}{1}", word[0].ToString().ToLowerInvariant(), word.Substring(1) ); } } }
apache-2.0
C#
0d814317ae1b285c955d9a8878614c7181b9bbd3
Remove confirmation for exit with no verification
aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
aspnet-core/src/AbpCompanyName.AbpProjectName.Migrator/Program.cs
aspnet-core/src/AbpCompanyName.AbpProjectName.Migrator/Program.cs
using System; using Abp; using Abp.Collections.Extensions; using Abp.Dependency; using Castle.Facilities.Logging; using Abp.Castle.Logging.Log4Net; namespace AbpCompanyName.AbpProjectName.Migrator { public class Program { private static bool _skipConnVerification = false; public static void Main(string[] args) { ParseArgs(args); using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>()) { bootstrapper.IocManager.IocContainer .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net() .WithConfig("log4net.config") ); bootstrapper.Initialize(); using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>()) { migrateExecuter.Object.Run(_skipConnVerification); } if (!_skipConnVerification) { Console.WriteLine("Press ENTER to exit..."); Console.ReadLine(); } } } private static void ParseArgs(string[] args) { if (args.IsNullOrEmpty()) { return; } for (int i = 0; i < args.Length; i++) { var arg = args[i]; switch (arg) { case "-s": _skipConnVerification = true; break; } } } } }
using System; using Abp; using Abp.Collections.Extensions; using Abp.Dependency; using Castle.Facilities.Logging; using Abp.Castle.Logging.Log4Net; namespace AbpCompanyName.AbpProjectName.Migrator { public class Program { private static bool _skipConnVerification = false; public static void Main(string[] args) { ParseArgs(args); using (var bootstrapper = AbpBootstrapper.Create<AbpProjectNameMigratorModule>()) { bootstrapper.IocManager.IocContainer .AddFacility<LoggingFacility>(f => f.UseAbpLog4Net() .WithConfig("log4net.config") ); bootstrapper.Initialize(); using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MultiTenantMigrateExecuter>()) { migrateExecuter.Object.Run(_skipConnVerification); } Console.WriteLine("Press ENTER to exit..."); Console.ReadLine(); } } private static void ParseArgs(string[] args) { if (args.IsNullOrEmpty()) { return; } for (int i = 0; i < args.Length; i++) { var arg = args[i]; switch (arg) { case "-s": _skipConnVerification = true; break; } } } } }
mit
C#
535044e4f4a1d42380b88e53aafdbccedba5113c
Add private setters so deserializing on integration event handler works as expected.
dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers
src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Address.cs
src/Services/Ordering/Ordering.Domain/AggregatesModel/OrderAggregate/Address.cs
using Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork; using System; using System.Collections.Generic; namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate { public class Address : ValueObject { public String Street { get; private set; } public String City { get; private set; } public String State { get; private set; } public String Country { get; private set; } public String ZipCode { get; private set; } private Address() { } public Address(string street, string city, string state, string country, string zipcode) { Street = street; City = city; State = state; Country = country; ZipCode = zipcode; } protected override IEnumerable<object> GetAtomicValues() { // Using a yield return statement to return each element one at a time yield return Street; yield return City; yield return State; yield return Country; yield return ZipCode; } } }
using Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork; using System; using System.Collections.Generic; namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate { public class Address : ValueObject { public String Street { get; } public String City { get; } public String State { get; } public String Country { get; } public String ZipCode { get; } private Address() { } public Address(string street, string city, string state, string country, string zipcode) { Street = street; City = city; State = state; Country = country; ZipCode = zipcode; } protected override IEnumerable<object> GetAtomicValues() { // Using a yield return statement to return each element one at a time yield return Street; yield return City; yield return State; yield return Country; yield return ZipCode; } } }
mit
C#
ce78938a1abc866fcf72539d81dcd2b67af8c104
Check for metrics route in HttpContext.
alhardy/AppMetrics,alhardy/AppMetrics
src/App.Metrics.Extensions.Middleware/Extensions/HttpContextExtensions.cs
src/App.Metrics.Extensions.Middleware/Extensions/HttpContextExtensions.cs
// <copyright file="HttpContextExtensions.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> using System; using System.Linq; using System.Net; // ReSharper disable CheckNamespace namespace Microsoft.AspNetCore.Http { // ReSharper restore CheckNamespace internal static class HttpContextExtensions { private static readonly string MetricsCurrentRouteName = "__App.Metrics.CurrentRouteName__"; public static void AddMetricsCurrentRouteName(this HttpContext context, string metricName) { context.Items.Add(MetricsCurrentRouteName, metricName); } public static string GetMetricsCurrentRouteName(this HttpContext context) { if (context.Items.TryGetValue(MetricsCurrentRouteName, out var item)) { var route = item as string; if (route.IsPresent()) { return $"{context.Request.Method} {route}"; } } return context.Request.Method; } public static bool HasMetricsCurrentRouteName(this HttpContext context) { return context.Items.ContainsKey(MetricsCurrentRouteName); } public static bool IsSuccessfulResponse(this HttpResponse httpResponse) { return httpResponse.StatusCode >= (int)HttpStatusCode.OK && httpResponse.StatusCode <= 299; } public static string OAuthClientId(this HttpContext httpContext) { var claimsPrincipal = httpContext.User; var clientId = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == "client_id"); return clientId?.Value; } public static void SetNoCacheHeaders(this HttpContext context) { context.Response.Headers["Cache-Control"] = new[] { "no-cache, no-store, must-revalidate" }; context.Response.Headers["Pragma"] = new[] { "no-cache" }; context.Response.Headers["Expires"] = new[] { "0" }; } } }
// <copyright file="HttpContextExtensions.cs" company="Allan Hardy"> // Copyright (c) Allan Hardy. All rights reserved. // </copyright> using System; using System.Linq; using System.Net; // ReSharper disable CheckNamespace namespace Microsoft.AspNetCore.Http { // ReSharper restore CheckNamespace internal static class HttpContextExtensions { private static readonly string MetricsCurrentRouteName = "__App.Metrics.CurrentRouteName__"; public static void AddMetricsCurrentRouteName(this HttpContext context, string metricName) { context.Items.Add(MetricsCurrentRouteName, metricName); } public static string GetMetricsCurrentRouteName(this HttpContext context) { var route = context.Items[MetricsCurrentRouteName] as string; if (route.IsPresent()) { return context.Request.Method + " " + context.Items[MetricsCurrentRouteName]; } return context.Request.Method; } public static bool HasMetricsCurrentRouteName(this HttpContext context) { return context.Items.ContainsKey(MetricsCurrentRouteName); } public static bool IsSuccessfulResponse(this HttpResponse httpResponse) { return httpResponse.StatusCode >= (int)HttpStatusCode.OK && httpResponse.StatusCode <= 299; } public static string OAuthClientId(this HttpContext httpContext) { var claimsPrincipal = httpContext.User; var clientId = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == "client_id"); return clientId?.Value; } public static void SetNoCacheHeaders(this HttpContext context) { context.Response.Headers["Cache-Control"] = new[] { "no-cache, no-store, must-revalidate" }; context.Response.Headers["Pragma"] = new[] { "no-cache" }; context.Response.Headers["Expires"] = new[] { "0" }; } } }
apache-2.0
C#
fd77ac2577b57ddc22aca743d409d4900a675e25
Update Program.cs (#197)
nanoframework/nf-Visual-Studio-extension
source/CSharp.BlankApplication/Program.cs
source/CSharp.BlankApplication/Program.cs
using System; using System.Threading; using System.Diagnostics; namespace $safeprojectname$ { public class Program { public static void Main() { while (!Debugger.IsAttached) { Thread.Sleep(100); } // Wait for debugger (only needed for debugging session) Console.WriteLine("Program started"); // You can remove this line once it outputs correctly on the console try { // User code goes here } catch (Exception ex) { // Do whatever please you with the exception caught } finally // Enter the infinite loop in all cases { while (true) { Thread.Sleep(200); } } } } }
using System; using System.Threading; namespace $safeprojectname$ { public class Program { public static void Main() { Thread.Sleep(1000); // Temporary dirty fix to enable correct debugging session // Insert your code below this line // The main() method has to end with this infinite loop. // Do not use the NETMF style : Thread.Sleep(Timeout.Infinite) while (true) { Thread.Sleep(200); } } } }
mit
C#
6fde4b84fe546d20196c316e46b19f1e641e1e18
Update ContactsSample for MfA 4.2
xamarin/Xamarin.Mobile,orand/Xamarin.Mobile,moljac/Xamarin.Mobile,nexussays/Xamarin.Mobile,xamarin/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile
MonoDroid/Samples/ContactsSample/MainActivity.cs
MonoDroid/Samples/ContactsSample/MainActivity.cs
using System; using System.Text; using Android.App; using Android.Content; using Android.Database; using Android.Net; using Android.OS; using Android.Provider; using Android.Widget; using Xamarin.Contacts; using System.Linq; using System.Collections.Generic; namespace ContactsSample { [Activity(Label = "ContactsSample", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : ListActivity { List<String> contacts = new List<String>(); List<String> contactIDs = new List<String>(); protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // // get the address book, which gives us access to the // the contacts store // var book = new AddressBook (this); // // important: PreferContactAggregation must be set to the // the same value when looking up contacts by ID // since we look up contacts by ID on the subsequent // ContactsActivity in this sample, we will set both to true // book.PreferContactAggregation = true; // // loop through the contacts and put them into a List<String> // // Note that the contacts are ordered by last name - contacts can be selected and sorted using LINQ! // A more performant solution would create a custom adapter to lazily pull the contacts // // In this sample, we'll just use LINQ to grab the first 10 users with mobile phone entries // foreach (Contact contact in book.Where(c => c.Phones.Any(p => p.Type == PhoneType.Mobile)).Take(10)) { contacts.Add(contact.DisplayName); contactIDs.Add(contact.Id); //save the ID in a parallel list } ListAdapter = new ArrayAdapter<string> (this, Resource.Layout.list_item, contacts.ToArray()); ListView.TextFilterEnabled = true; // // When clicked, start a new activity to display more contact details // ListView.ItemClick += delegate (object sender, AdapterView.ItemClickEventArgs args) { // // to show the contact on the details activity, we // need to send that activity the contacts ID // String contactID = contactIDs[args.Position]; Intent showContactDetails = new Intent(this, typeof(ContactActivity)); showContactDetails.PutExtra("contactID", contactID); StartActivity(showContactDetails); // // alternatively, show a toast with the name of the contact selected // //Toast.MakeText (Application, ((TextView)args.View).Text, ToastLength.Short).Show (); }; } } }
using System; using System.Text; using Android.App; using Android.Content; using Android.Database; using Android.Net; using Android.OS; using Android.Provider; using Android.Widget; using Xamarin.Contacts; using System.Linq; using System.Collections.Generic; namespace ContactsSample { [Activity(Label = "ContactsSample", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : ListActivity { List<String> contacts = new List<String>(); List<String> contactIDs = new List<String>(); protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // // get the address book, which gives us access to the // the contacts store // var book = new AddressBook (this); // // important: PreferContactAggregation must be set to the // the same value when looking up contacts by ID // since we look up contacts by ID on the subsequent // ContactsActivity in this sample, we will set both to true // book.PreferContactAggregation = true; // // loop through the contacts and put them into a List<String> // // Note that the contacts are ordered by last name - contacts can be selected and sorted using LINQ! // A more performant solution would create a custom adapter to lazily pull the contacts // // In this sample, we'll just use LINQ to grab the first 10 users with mobile phone entries // foreach (Contact contact in book.Where(c => c.Phones.Any(p => p.Type == PhoneType.Mobile)).Take(10)) { contacts.Add(contact.DisplayName); contactIDs.Add(contact.Id); //save the ID in a parallel list } ListAdapter = new ArrayAdapter<string> (this, Resource.Layout.list_item, contacts.ToArray()); ListView.TextFilterEnabled = true; // // When clicked, start a new activity to display more contact details // ListView.ItemClick += delegate (object sender, ItemEventArgs args) { // // to show the contact on the details activity, we // need to send that activity the contacts ID // String contactID = contactIDs[args.Position]; Intent showContactDetails = new Intent(this, typeof(ContactActivity)); showContactDetails.PutExtra("contactID", contactID); StartActivity(showContactDetails); // // alternatively, show a toast with the name of the contact selected // //Toast.MakeText (Application, ((TextView)args.View).Text, ToastLength.Short).Show (); }; } } }
apache-2.0
C#
7f40b9320987c1e4c33ea9da8f974e254955ea4c
Use git repository url variable rather than duplicating logic
appharbor/appharbor-cli
src/AppHarbor/ApplicationConfiguration.cs
src/AppHarbor/ApplicationConfiguration.cs
using System; using System.IO; using System.Linq; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration : IApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { try { using (var stream = _fileSystem.OpenRead(ConfigurationFile.FullName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (FileNotFoundException) { } var url = _gitExecutor.Execute("config remote.appharbor.url", CurrentDirectory).FirstOrDefault(); if (url != null) { return url.Split(new string[] { "/", ".git" }, StringSplitOptions.RemoveEmptyEntries).Last(); } throw new ApplicationConfigurationException("Application is not configured"); } public virtual void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor {0}", repositoryUrl), CurrentDirectory); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); using (var stream = _fileSystem.OpenWrite(ConfigurationFile.FullName)) { using (var writer = new StreamWriter(stream)) { writer.Write(id); } } Console.WriteLine("Wrote application configuration to {0}", ConfigurationFile); } private static DirectoryInfo CurrentDirectory { get { return new DirectoryInfo(Directory.GetCurrentDirectory()); } } private static FileInfo ConfigurationFile { get { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); return appharborConfigurationFile; } } } }
using System; using System.IO; using System.Linq; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration : IApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { try { using (var stream = _fileSystem.OpenRead(ConfigurationFile.FullName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (FileNotFoundException) { } var url = _gitExecutor.Execute("config remote.appharbor.url", CurrentDirectory).FirstOrDefault(); if (url != null) { return url.Split(new string[] { "/", ".git" }, StringSplitOptions.RemoveEmptyEntries).Last(); } throw new ApplicationConfigurationException("Application is not configured"); } public virtual void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), CurrentDirectory); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); using (var stream = _fileSystem.OpenWrite(ConfigurationFile.FullName)) { using (var writer = new StreamWriter(stream)) { writer.Write(id); } } Console.WriteLine("Wrote application configuration to {0}", ConfigurationFile); } private static DirectoryInfo CurrentDirectory { get { return new DirectoryInfo(Directory.GetCurrentDirectory()); } } private static FileInfo ConfigurationFile { get { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); return appharborConfigurationFile; } } } }
mit
C#
4b0bbe1653c4a1d0a7fab41b36b1ba06c7c8cd2e
Make ApplicationConfiguration#SetupApplication virtual
appharbor/appharbor-cli
src/AppHarbor/ApplicationConfiguration.cs
src/AppHarbor/ApplicationConfiguration.cs
using System; using System.IO; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { try { using (var stream = _fileSystem.OpenRead(ConfigurationFile.FullName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (FileNotFoundException) { throw new ApplicationConfigurationException("Application is not configured"); } } public virtual void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), new DirectoryInfo(Directory.GetCurrentDirectory())); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); using (var stream = _fileSystem.OpenWrite(ConfigurationFile.FullName)) { using (var writer = new StreamWriter(stream)) { writer.Write(id); } } Console.WriteLine("Wrote application configuration to {0}", ConfigurationFile); } private static FileInfo ConfigurationFile { get { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); return appharborConfigurationFile; } } } }
using System; using System.IO; using AppHarbor.Model; namespace AppHarbor { public class ApplicationConfiguration { private readonly IFileSystem _fileSystem; private readonly IGitExecutor _gitExecutor; public ApplicationConfiguration(IFileSystem fileSystem, IGitExecutor gitExecutor) { _fileSystem = fileSystem; _gitExecutor = gitExecutor; } public string GetApplicationId() { try { using (var stream = _fileSystem.OpenRead(ConfigurationFile.FullName)) { using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } catch (FileNotFoundException) { throw new ApplicationConfigurationException("Application is not configured"); } } public void SetupApplication(string id, User user) { var repositoryUrl = string.Format("https://{0}@appharbor.com/{1}.git", user.Username, id); try { _gitExecutor.Execute(string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id), new DirectoryInfo(Directory.GetCurrentDirectory())); Console.WriteLine("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master"); return; } catch (InvalidOperationException) { } Console.WriteLine("Couldn't add appharbor repository as a git remote. Repository URL is: {0}", repositoryUrl); using (var stream = _fileSystem.OpenWrite(ConfigurationFile.FullName)) { using (var writer = new StreamWriter(stream)) { writer.Write(id); } } Console.WriteLine("Wrote application configuration to {0}", ConfigurationFile); } private static FileInfo ConfigurationFile { get { var directory = Directory.GetCurrentDirectory(); var appharborConfigurationFile = new FileInfo(Path.Combine(directory, ".appharbor")); return appharborConfigurationFile; } } } }
mit
C#
580697b25db7da2f1d251f666101287f4910fb30
Make DrawingPresenter obsolete.
jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,SuperJMN/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex
src/Avalonia.Controls/DrawingPresenter.cs
src/Avalonia.Controls/DrawingPresenter.cs
using System; using Avalonia.Controls.Shapes; using Avalonia.Media; using Avalonia.Metadata; namespace Avalonia.Controls { [Obsolete("Use Image control with DrawingImage source")] public class DrawingPresenter : Control { static DrawingPresenter() { AffectsMeasure<DrawingPresenter>(DrawingProperty); AffectsRender<DrawingPresenter>(DrawingProperty); } public static readonly StyledProperty<Drawing> DrawingProperty = AvaloniaProperty.Register<DrawingPresenter, Drawing>(nameof(Drawing)); public static readonly StyledProperty<Stretch> StretchProperty = AvaloniaProperty.Register<DrawingPresenter, Stretch>(nameof(Stretch), Stretch.Uniform); [Content] public Drawing Drawing { get => GetValue(DrawingProperty); set => SetValue(DrawingProperty, value); } public Stretch Stretch { get => GetValue(StretchProperty); set => SetValue(StretchProperty, value); } private Matrix _transform = Matrix.Identity; protected override Size MeasureOverride(Size availableSize) { if (Drawing == null) return new Size(); var (size, transform) = Shape.CalculateSizeAndTransform(availableSize, Drawing.GetBounds(), Stretch); _transform = transform; return size; } public override void Render(DrawingContext context) { if (Drawing != null) { using (context.PushPreTransform(_transform)) using (context.PushClip(new Rect(Bounds.Size))) { Drawing.Draw(context); } } } } }
using Avalonia.Controls.Shapes; using Avalonia.Media; using Avalonia.Metadata; namespace Avalonia.Controls { public class DrawingPresenter : Control { static DrawingPresenter() { AffectsMeasure<DrawingPresenter>(DrawingProperty); AffectsRender<DrawingPresenter>(DrawingProperty); } public static readonly StyledProperty<Drawing> DrawingProperty = AvaloniaProperty.Register<DrawingPresenter, Drawing>(nameof(Drawing)); public static readonly StyledProperty<Stretch> StretchProperty = AvaloniaProperty.Register<DrawingPresenter, Stretch>(nameof(Stretch), Stretch.Uniform); [Content] public Drawing Drawing { get => GetValue(DrawingProperty); set => SetValue(DrawingProperty, value); } public Stretch Stretch { get => GetValue(StretchProperty); set => SetValue(StretchProperty, value); } private Matrix _transform = Matrix.Identity; protected override Size MeasureOverride(Size availableSize) { if (Drawing == null) return new Size(); var (size, transform) = Shape.CalculateSizeAndTransform(availableSize, Drawing.GetBounds(), Stretch); _transform = transform; return size; } public override void Render(DrawingContext context) { if (Drawing != null) { using (context.PushPreTransform(_transform)) using (context.PushClip(new Rect(Bounds.Size))) { Drawing.Draw(context); } } } } }
mit
C#
e6618495a7d3389f4a21284027a71945b271e70f
Set assembly properties to Version 0.1 and filled assembly company and description
renber/SecondaryTaskbarClock
SecondaryTaskbarClock/Properties/AssemblyInfo.cs
SecondaryTaskbarClock/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("SecondaryTaskbarClock")] [assembly: AssemblyDescription("Application which shows the clock on all secondary taskbars for Windows 8 and 10")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("René Bergelt")] [assembly: AssemblyProduct("SecondaryTaskbarClock")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("64cba600-96a1-4596-997e-bf563cbdac21")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [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; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("SecondaryTaskbarClock")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SecondaryTaskbarClock")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("64cba600-96a1-4596-997e-bf563cbdac21")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
056922ce53d90ef1c563caf741c5a6de04c8b57b
Update the version number in Woopsa C# assembly to 1.2
fabien-chevalley/Woopsa,fabien-chevalley/Woopsa,woopsa-protocol/Woopsa,fabien-chevalley/Woopsa,fabien-chevalley/Woopsa,woopsa-protocol/Woopsa,woopsa-protocol/Woopsa,woopsa-protocol/Woopsa,fabien-chevalley/Woopsa,woopsa-protocol/Woopsa,fabien-chevalley/Woopsa,woopsa-protocol/Woopsa
Sources/DotNet/Woopsa/Properties/AssemblyInfo.cs
Sources/DotNet/Woopsa/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("Woopsa")] [assembly: AssemblyDescription("Woopsa is a protocol that's simple, lightweight, free, open-source, web and object-oriented, publish-subscribe, real-time capable and Industry 4.0 ready. It contributes to the revolution of the Internet of Things")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Objectis SA")] [assembly: AssemblyProduct("Woopsa")] [assembly: AssemblyCopyright("Copyright © Objectis SA 2016")] [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("11e39986-1641-4ffa-b91c-a928a72b819e")] // 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.2.0.*")] [assembly: AssemblyFileVersion("1.2.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("Woopsa")] [assembly: AssemblyDescription("Woopsa is a protocol that's simple, lightweight, free, open-source, web and object-oriented, publish-subscribe, real-time capable and Industry 4.0 ready. It contributes to the revolution of the Internet of Things")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Objectis SA")] [assembly: AssemblyProduct("Woopsa")] [assembly: AssemblyCopyright("Copyright © Objectis SA 2016")] [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("11e39986-1641-4ffa-b91c-a928a72b819e")] // 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.1.9.*")] [assembly: AssemblyFileVersion("1.1.9.0")]
mit
C#
fdc37c881062cb091c344913419e43d8d4aa37d8
Update LastHit
ThytHY0001/ProjectThy
ThyLastHit/ThyLastHit/Properties/AssemblyInfo.cs
ThyLastHit/ThyLastHit/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("ThyLastHit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ThyLastHit")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("cd75afc9-587b-4102-b620-eccc35d31ff1")] // 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.2.5.0")] [assembly: AssemblyFileVersion("1.2.5.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("ThyLastHit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ThyLastHit")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("cd75afc9-587b-4102-b620-eccc35d31ff1")] // 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")]
apache-2.0
C#
2868eb8d69bc41d56fc2807e72cde383557ab061
Add about change
SteveLasker/AspNetCoreMultiProject,SteveLasker/AspNetCoreMultiProject
Web/Views/Home/About.cshtml
Web/Views/Home/About.cshtml
@{ ViewData["Title"] = "About"; } <h2>@ViewData["Title"]</h2> <h3>@ViewData["Message"]</h3> <h3>Host Information</h3> <b>HostName:</b> @ViewData["HOSTNAME"]<br /> <b>OS Architecture:</b> @ViewData["OSARCHITECTURE"]<br /> <b>OS Description:</b> @ViewData["OSDESCRIPTION"]<br /> <b>Process Architecture:</b> @ViewData["PROCESSARCHITECTURE"]<br /> <b>Framework Description:</b> @ViewData["FRAMEWORKDESCRIPTION"]<br /> <b>ASP.NET Hosting Environment:</b> @ViewData["ASPNETCORE_ENVIRONMENT"]<br /> <h3>Environment Variables:</h3> @Html.Raw(ViewData["ENV_VARS"])
@{ ViewData["Title"] = "About"; } <h2>@ViewData["Title"].</h2> <h3>@ViewData["Message"]</h3> <p>Use this area to provide additional information.</p>
mit
C#
8d06ca80adc87515a58c48e2caa0012e3a14d52e
Update Android designer file auto generated by mono
bbqchickenrobot/oxyplot,shoelzer/oxyplot,objorke/oxyplot,H2ONaCl/oxyplot,DotNetDoctor/oxyplot,mattleibow/oxyplot,objorke/oxyplot,oxyplot/oxyplot,lynxkor/oxyplot,Jofta/oxyplot,H2ONaCl/oxyplot,DotNetDoctor/oxyplot,shoelzer/oxyplot,svendu/oxyplot,Mitch-Connor/oxyplot,Rustemt/oxyplot,NilesDavis/oxyplot,H2ONaCl/oxyplot,olegtarasov/oxyplot,olegtarasov/oxyplot,jeremyiverson/oxyplot,jeremyiverson/oxyplot,HermanEldering/oxyplot,shoelzer/oxyplot,TheAlmightyBob/oxyplot,br111an/oxyplot,Jonarw/oxyplot,BRER-TECH/oxyplot,jeremyiverson/oxyplot,GeertvanHorrik/oxyplot,Mitch-Connor/oxyplot,lynxkor/oxyplot,freudenthal/oxyplot,Kaplas80/oxyplot,freudenthal/oxyplot,br111an/oxyplot,sevoku/oxyplot,sevoku/oxyplot,Sbosanquet/oxyplot,Isolocis/oxyplot,BRER-TECH/oxyplot,bbqchickenrobot/oxyplot,bbqchickenrobot/oxyplot,Kaplas80/oxyplot,Sbosanquet/oxyplot,GeertvanHorrik/oxyplot,svendu/oxyplot,ze-pequeno/oxyplot,objorke/oxyplot,br111an/oxyplot,HermanEldering/oxyplot,Rustemt/oxyplot,as-zhuravlev/oxyplot_wpf_fork,TheAlmightyBob/oxyplot,lynxkor/oxyplot,mattleibow/oxyplot,freudenthal/oxyplot,GeertvanHorrik/oxyplot,TheAlmightyBob/oxyplot,svendu/oxyplot,Sbosanquet/oxyplot,Mitch-Connor/oxyplot,as-zhuravlev/oxyplot_wpf_fork,as-zhuravlev/oxyplot_wpf_fork,Rustemt/oxyplot,zur003/oxyplot
Source/Examples/XamarinAndroid/ExampleBrowser/Resources/Resource.Designer.cs
Source/Examples/XamarinAndroid/ExampleBrowser/Resources/Resource.Designer.cs
#pragma warning disable 1591 // ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.17020 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ [assembly: Android.Runtime.ResourceDesignerAttribute("ExampleBrowser.Resource", IsApplication=true)] namespace ExampleBrowser { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f050000 public const int plotview = 2131034112; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int ListItem = 2130903040; // aapt resource value: 0x7f030001 public const int PlotActivity = 2130903041; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class String { // aapt resource value: 0x7f040001 public const int ApplicationName = 2130968577; // aapt resource value: 0x7f040000 public const int Hello = 2130968576; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
#pragma warning disable 1591 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Android.Runtime.ResourceDesignerAttribute("ExampleBrowser.Resource", IsApplication=true)] namespace ExampleBrowser { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")] public partial class Resource { static Resource() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } public static void UpdateIdValues() { } public partial class Attribute { static Attribute() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Attribute() { } } public partial class Drawable { // aapt resource value: 0x7f020000 public const int icon = 2130837504; static Drawable() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Drawable() { } } public partial class Id { // aapt resource value: 0x7f050000 public const int plotview = 2131034112; static Id() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Id() { } } public partial class Layout { // aapt resource value: 0x7f030000 public const int ListItem = 2130903040; // aapt resource value: 0x7f030001 public const int PlotActivity = 2130903041; static Layout() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private Layout() { } } public partial class String { // aapt resource value: 0x7f040001 public const int ApplicationName = 2130968577; // aapt resource value: 0x7f040000 public const int Hello = 2130968576; static String() { global::Android.Runtime.ResourceIdManager.UpdateIdValues(); } private String() { } } } } #pragma warning restore 1591
mit
C#
d9498bcd797fdb6c4161001f689524c388013909
add class
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
src/StockportWebapp/Views/stockportgov/Shared/Semantic/EmailBanner.cshtml
src/StockportWebapp/Views/stockportgov/Shared/Semantic/EmailBanner.cshtml
@using StockportWebapp.ViewModels @model EmailBannerViewModel <section class="banner"> <div class="hide-on-tablet hide-on-mobile"> <span class="si-envelope-open" aria-hidden="true"></span> </div> <div class="email-alert"> <h2 class="h3">@Model.EmailAlertsText</h2> <form method="post" role="form" action="/subscribe"> <button type="submit" id="test-subscribe" class="button-primary">Subscribe</button> @Html.HiddenFor(o => o.EmailAlertsTopicId) </form> </div> </section>
@using StockportWebapp.ViewModels @model EmailBannerViewModel <section class="banner"> <div class="hide-on-tablet hide-on-mobile"> <span class="si-envelope-open" aria-hidden="true"></span> </div> <div> <h2 class="h3">@Model.EmailAlertsText</h2> <form method="get" role="form" action="/subscribe"> <input type="email" name="emailAddress" placeholder="Enter your email address" title="Enter your email address" aria-label="Enter your email address"> <button type="submit" id="test-subscribe" class="button-primary">Subscribe</button> @Html.HiddenFor(o => o.EmailAlertsTopicId) </form> </div> </section>
mit
C#
aad7584c36ac5fabf14aecadd2a18d76d946ba8f
update version
HouseBreaker/Shameless
Shameless/Properties/AssemblyInfo.cs
Shameless/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("Shameless")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shameless")] [assembly: AssemblyCopyright("Copyright © Housey 2016")] [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("c103c186-94f8-486f-ad20-4f636bdbfd6c")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
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("Shameless")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Shameless")] [assembly: AssemblyCopyright("Copyright © Housey 2016")] [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("c103c186-94f8-486f-ad20-4f636bdbfd6c")] // 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.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
mit
C#
76cefe43ae72254b4bc43e5232f2cb114f535c6e
Fix bundling and minification
kriasoft/AngularJS-SPA-Template,rucila/AngularJS-SPA-Template,rucila/AngularJS-SPA-Template,dalfriedrice/AngularJS-SPA-Template,kriasoft/AngularJS-SPA-Template,dankahle/MyApp,dalfriedrice/AngularJS-SPA-Template,hitesh97/AngularJS-SPA-Template,dankahle/MyApp,hitesh97/AngularJS-SPA-Template,REALTOBIZ/AngularJS-SPA-Template,REALTOBIZ/AngularJS-SPA-Template
Source/Web/App_Start/BundleConfig.cs
Source/Web/App_Start/BundleConfig.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BundleConfig.cs" company="KriaSoft LLC"> // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace App.Web { using System.Web; using System.Web.Optimization; public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/css/app").Include("~/content/app.css")); bundles.Add(new ScriptBundle("~/js/jquery").Include("~/scripts/vendor/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/js/app").Include( "~/scripts/vendor/angular-ui-router.js", "~/scripts/filters.js", "~/scripts/services.js", "~/scripts/directives.js", "~/scripts/controllers.js", "~/scripts/app.js")); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BundleConfig.cs" company="KriaSoft LLC"> // Copyright © 2013 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace App.Web { using System.Web; using System.Web.Optimization; public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/css/app").Include("~/content/app.css")); bundles.Add(new ScriptBundle("~/js/jquery").Include("~/scripts/vendor/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/js/app").Include( "~/scripts/vendor/angular-ui-router.js", "~/scripts/app.js", "~/scripts/controllers.js")); } } }
mit
C#
3164ff4b553ca2a3d8ef388bad90cced5e808c8f
Add RedirectType and ResponseLimit to collectors
bcemmett/SurveyMonkeyApi-v3
SurveyMonkey/Containers/Collector.cs
SurveyMonkey/Containers/Collector.cs
using System; using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class Collector : IPageableContainer { [JsonConverter(typeof(TolerantJsonConverter))] public enum StatusType { New, Open, Closed } [JsonConverter(typeof(TolerantJsonConverter))] public enum CollectorType { Weblink, Email } [JsonConverter(typeof(TolerantJsonConverter))] public enum EditResponseOption { UntilComplete, Never, Always } [JsonConverter(typeof(TolerantJsonConverter))] public enum AnonymousOption { NotAnonymous, PartiallyAnonymous, FullyAnonymous } [JsonConverter(typeof(TolerantJsonConverter))] public enum RedirectOption { Url, Close, Loop } public StatusType? Status { get; set; } public long? Id { get; set; } public string Name { get; set; } public CollectorType? Type { get; set; } public string ThankYouMessage { get; set; } public string DisqualificationMessage { get; set; } public DateTime? CloseDate { get; set; } public string ClosedPageMessage { get; set; } public string RedirectUrl { get; set; } public bool? DisplaySurveyResults { get; set; } public EditResponseOption? EditResponseType { get; set; } public AnonymousOption? AnonymousType { get; set; } public RedirectOption? RedirectType { get; set; } public int? ResponseLimit { get; set; } public bool? AllowMultipleResponses { get; set; } public DateTime? DateModified { get; set; } public DateTime? DateCreated { get; set; } public string Url { get; set; } public bool? PasswordEnabled { get; set; } public string SenderEmail { get; set; } internal string Href { get; set; } public int? ResponseCount { get; set; } } }
using System; using Newtonsoft.Json; namespace SurveyMonkey.Containers { [JsonConverter(typeof(TolerantJsonConverter))] public class Collector : IPageableContainer { [JsonConverter(typeof(TolerantJsonConverter))] public enum StatusType { New, Open, Closed } [JsonConverter(typeof(TolerantJsonConverter))] public enum CollectorType { Weblink, Email } [JsonConverter(typeof(TolerantJsonConverter))] public enum EditResponseOption { UntilComplete, Never, Always } [JsonConverter(typeof(TolerantJsonConverter))] public enum AnonymousOption { NotAnonymous, PartiallyAnonymous, FullyAnonymous } public StatusType? Status { get; set; } public long? Id { get; set; } public string Name { get; set; } public CollectorType? Type { get; set; } public string ThankYouMessage { get; set; } public string DisqualificationMessage { get; set; } public DateTime? CloseDate { get; set; } public string ClosedPageMessage { get; set; } public string RedirectUrl { get; set; } public bool? DisplaySurveyResults { get; set; } public EditResponseOption? EditResponseType { get; set; } public AnonymousOption? AnonymousType { get; set; } public bool? AllowMultipleResponses { get; set; } public DateTime? DateModified { get; set; } public DateTime? DateCreated { get; set; } public string Url { get; set; } public bool? PasswordEnabled { get; set; } public string SenderEmail { get; set; } internal string Href { get; set; } public int? ResponseCount { get; set; } } }
mit
C#
825dd7fbce376cc534ea03849fa3495ebd32248b
rename new content type name namespace to match original one for type forwarding
nguerrera/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,mavasani/roslyn,davkean/roslyn,nguerrera/roslyn,brettfo/roslyn,panopticoncentral/roslyn,sharwell/roslyn,VSadov/roslyn,physhi/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,KevinRansom/roslyn,dotnet/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,diryboy/roslyn,aelij/roslyn,sharwell/roslyn,dotnet/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,AlekseyTs/roslyn,MichalStrehovsky/roslyn,DustinCampbell/roslyn,physhi/roslyn,wvdd007/roslyn,bartdesmet/roslyn,aelij/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,jcouv/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,davkean/roslyn,brettfo/roslyn,bartdesmet/roslyn,sharwell/roslyn,stephentoub/roslyn,abock/roslyn,abock/roslyn,VSadov/roslyn,tannergooding/roslyn,DustinCampbell/roslyn,VSadov/roslyn,weltkante/roslyn,weltkante/roslyn,jcouv/roslyn,davkean/roslyn,agocke/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,gafter/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,KevinRansom/roslyn,mavasani/roslyn,diryboy/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,aelij/roslyn,agocke/roslyn,physhi/roslyn,jcouv/roslyn,gafter/roslyn,gafter/roslyn,panopticoncentral/roslyn,abock/roslyn,AlekseyTs/roslyn,eriawan/roslyn,heejaechang/roslyn,jmarolf/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,heejaechang/roslyn,genlu/roslyn,heejaechang/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,KevinRansom/roslyn,diryboy/roslyn,reaction1989/roslyn,stephentoub/roslyn,tmat/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,tmat/roslyn,AmadeusW/roslyn,eriawan/roslyn,tmat/roslyn,MichalStrehovsky/roslyn,wvdd007/roslyn,reaction1989/roslyn
src/EditorFeatures/Text/ContentTypeNames.cs
src/EditorFeatures/Text/ContentTypeNames.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Editor { internal static class ContentTypeNames { public const string CSharpContentType = "CSharp"; public const string CSharpSignatureHelpContentType = "CSharp Signature Help"; public const string RoslynContentType = "Roslyn Languages"; public const string VisualBasicContentType = "Basic"; public const string VisualBasicSignatureHelpContentType = "Basic Signature Help"; public const string XamlContentType = "XAML"; public const string JavaScriptContentTypeName = "JavaScript"; public const string TypeScriptContentTypeName = "TypeScript"; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.Editor.Text { internal static class ContentTypeNames { public const string CSharpContentType = "CSharp"; public const string CSharpSignatureHelpContentType = "CSharp Signature Help"; public const string RoslynContentType = "Roslyn Languages"; public const string VisualBasicContentType = "Basic"; public const string VisualBasicSignatureHelpContentType = "Basic Signature Help"; public const string XamlContentType = "XAML"; public const string JavaScriptContentTypeName = "JavaScript"; public const string TypeScriptContentTypeName = "TypeScript"; } }
mit
C#
f54c97d6cb24dbb11583a622e91f8396c4ca5b76
Update Program.cs
DelKatey/vig.sq.crypt.gui
VigenereSquareCryptor_GUI/Program.cs
VigenereSquareCryptor_GUI/Program.cs
using System; using System.Windows.Forms; namespace VigenereSquareCryptor_GUI { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { /// <summary> /// Program entry point. /// </summary> [STAThread] private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
/* * Created by SharpDevelop. * User: delkatey * Date: 20/11/2015 * Time: 9:19 AM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Windows.Forms; namespace VigenereSquareCryptor_GUI { /// <summary> /// Class with program entry point. /// </summary> internal sealed class Program { /// <summary> /// Program entry point. /// </summary> [STAThread] private static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
mit
C#
18514ca02a99ae40ecee7bf3c6d04837d070c658
update to work with taxonomies
smeehan82/Hermes,smeehan82/Hermes,smeehan82/Hermes
src/Hermes/DataAccess/DataContextBuilder.cs
src/Hermes/DataAccess/DataContextBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hermes.DataAccess { public class DataContextBuilder { public IList<Type> RegisteredModelTypes { get; } = new List<Type>(); public void RegisterModel<T>() where T : IContent { RegisterModel(typeof(T)); } public void RegisterModel(Type contentType) { if (!typeof(IContent).IsAssignableFrom(contentType)) { throw new ArgumentException("Parameter should implement IContent", nameof(contentType)); } RegisteredModelTypes.Add(contentType); } public void RegisterTaxonomyModel<T>() where T : ITaxonomy { RegisterTaxonomyModel(typeof(T)); } public void RegisterTaxonomyModel(Type contentType) { if (!typeof(ITaxonomy).IsAssignableFrom(contentType)) { throw new ArgumentException("Parameter should implement IContent", nameof(contentType)); } RegisteredModelTypes.Add(contentType); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hermes.DataAccess { public class DataContextBuilder { public IList<Type> RegisteredModelTypes { get; } = new List<Type>(); public void RegisterModel<T>() where T : IContent { RegisterModel(typeof(T)); } public void RegisterModel(Type contentType) { if (!typeof(IContent).IsAssignableFrom(contentType)) { throw new ArgumentException("Parameter should implement IContent", nameof(contentType)); } RegisteredModelTypes.Add(contentType); } } }
mit
C#
e7504218ca99e1ddf5cbe832e8df4eea9ef12aa8
Resolve #13
bcanseco/magnanibot
src/Magnanibot.Discord/Modules/Translate.cs
src/Magnanibot.Discord/Modules/Translate.cs
using System.Threading.Tasks; using CommonBotLibrary.Services; using CommonBotLibrary.Services.Models; using Discord; using Discord.Commands; using Magnanibot.Extensions; namespace Magnanibot.Modules { [Group(nameof(Translate)), Alias("trans")] [Summary("Translates text to another language.")] public class Translate : Module { public Translate(YandexTranslateService service) => Service = service; private YandexTranslateService Service { get; } [Command, Summary("Translates explicitly from one language to another.")] [Remarks("Example: !translate english spanish How are you?")] [Priority(3)] private async Task GetAsync(YandexLanguage source, YandexLanguage target, [Remainder] string text) => await GetAsync(text, source, target); [Command, Summary("Translates by auto-detecting the source text's language.")] [Remarks("Example: !translate spanish How are you?")] [Priority(2)] private async Task GetAsync(YandexLanguage target, [Remainder] string text) => await GetAsync(text, null, target); [Command, Summary("Translates to English by auto-detecting the source text's language.")] [Remarks("Example: !translate ¿Cómo estás?")] [Priority(1)] private async Task GetAsync([Remainder] string text) => await GetAsync(text, null, new YandexLanguage("en")); private async Task GetAsync(string text, YandexLanguage source, YandexLanguage target) { var translation = await Service.TranslateAsync(text, target, source); await EmbedAsync(new EmbedBuilder() .WithColor(new Color(0x2faf8f)) .WithTitle($"{translation.TargetLanguage} translation") .WithDescription(translation.OutputText) .WithFooter(translation.IsSourceDetected ? $"Source language was detected as {translation.SourceLanguage}." : $"Translated from {translation.SourceLanguage}.")); } } }
using System.Threading.Tasks; using CommonBotLibrary.Services; using CommonBotLibrary.Services.Models; using Discord; using Discord.Commands; using Magnanibot.Extensions; namespace Magnanibot.Modules { [Group(nameof(Translate)), Alias("trans")] [Summary("Translates text to another language.")] public class Translate : Module { public Translate(YandexTranslateService service) => Service = service; private YandexTranslateService Service { get; } [Command, Summary("Translates with an explicitly provided source text language.")] [Remarks("Example: !translate english spanish How are you?")] [Priority(2)] private async Task GetAsync(YandexLanguage source, YandexLanguage target, [Remainder] string text) => await GetAsync(text, source, target); [Command, Summary("Translates by auto-detecting the source text's language.")] [Remarks("Example: !translate spanish How are you?")] [Priority(1)] private async Task GetAsync(YandexLanguage target, [Remainder] string text) => await GetAsync(text, null, target); private async Task GetAsync(string text, YandexLanguage source, YandexLanguage target) { var translation = await Service.TranslateAsync(text, target, source); await EmbedAsync(new EmbedBuilder() .WithColor(new Color(0x2faf8f)) .WithTitle($"{translation.TargetLanguage} translation") .WithDescription(translation.OutputText) .WithFooter(translation.IsSourceDetected ? $"Source language was detected as {translation.SourceLanguage}." : $"Translated from {translation.SourceLanguage}.")); } } }
mit
C#
071b9831b6b6e959a77a8f4c24d8b5b53e1e294d
remove ask a question link
jbubriski/MassivelyDapperSimpleData,jbubriski/MassivelyDapperSimpleData
src/StackUnderToe/Views/Shared/_Menu.cshtml
src/StackUnderToe/Views/Shared/_Menu.cshtml
@model System.String <ul class="nav nav-list" data-spy="affix" data-offset-top="40"> <li class="nav-header">Questions</li> <li>@Html.ActionLink("New Unanswered Questions", "", "Questions")</li> <li class="nav-header">Users</li> <li>@Html.ActionLink("Newest Users", "", "Users")</li> <li>@Html.ActionLink("Oldest Users", "Oldest", "Users")</li> <li>@Html.ActionLink("Top Users", "Top", "Users")</li> <li>@Html.ActionLink("Create User", "Create", "Users")</li> <li class="nav-header">Badges</li> <li>@Html.ActionLink("Stats", "", "Badges")</li> <li>@Html.ActionLink("Top Badges", "Top", "Badges")</li> <li>@Html.ActionLink("Rare Badges", "Rare", "Badges")</li> </ul>
@model System.String <ul class="nav nav-list" data-spy="affix" data-offset-top="40"> <li class="nav-header">Questions</li> <li>@Html.ActionLink("New Unanswered Questions", "", "Questions")</li> <li>@Html.ActionLink("Ask a Question", "new", "Questions")</li> <li class="nav-header">Users</li> <li>@Html.ActionLink("Newest Users", "", "Users")</li> <li>@Html.ActionLink("Oldest Users", "Oldest", "Users")</li> <li>@Html.ActionLink("Top Users", "Top", "Users")</li> <li>@Html.ActionLink("Create User", "Create", "Users")</li> <li class="nav-header">Badges</li> <li>@Html.ActionLink("Stats", "", "Badges")</li> <li>@Html.ActionLink("Top Badges", "Top", "Badges")</li> <li>@Html.ActionLink("Rare Badges", "Rare", "Badges")</li> </ul>
mit
C#
7a66d360f043b179f5c80d86ef9daeeff579f2be
add transform parse
wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,Perspex/Perspex
src/Avalonia.Visuals/Media/Transform.cs
src/Avalonia.Visuals/Media/Transform.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Animation; using Avalonia.Animation.Animators; using Avalonia.VisualTree; namespace Avalonia.Media { /// <summary> /// Represents a transform on an <see cref="IVisual"/>. /// </summary> public abstract class Transform : Animatable { static Transform() { Animation.Animation.RegisterAnimator<TransformAnimator>(prop => typeof(Transform).IsAssignableFrom(prop.OwnerType)); } /// <summary> /// Raised when the transform changes. /// </summary> public event EventHandler Changed; /// <summary> /// Gets the transform's <see cref="Matrix"/>. /// </summary> public abstract Matrix Value { get; } /// <summary> /// Parses a <see cref="Transform"/> string. /// </summary> /// <param name="s">The string.</param> /// <returns>The <see cref="Transform"/>.</returns> public static Transform Parse(string s) { return new MatrixTransform(Matrix.Parse(s)); } /// <summary> /// Raises the <see cref="Changed"/> event. /// </summary> protected void RaiseChanged() { Changed?.Invoke(this, EventArgs.Empty); } /// <summary> /// Returns a String representing this transform matrix instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { return Value.ToString(); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Animation; using Avalonia.Animation.Animators; using Avalonia.VisualTree; namespace Avalonia.Media { /// <summary> /// Represents a transform on an <see cref="IVisual"/>. /// </summary> public abstract class Transform : Animatable { static Transform() { Animation.Animation.RegisterAnimator<TransformAnimator>(prop => typeof(Transform).IsAssignableFrom(prop.OwnerType)); } /// <summary> /// Raised when the transform changes. /// </summary> public event EventHandler Changed; /// <summary> /// Gets the transform's <see cref="Matrix"/>. /// </summary> public abstract Matrix Value { get; } /// <summary> /// Raises the <see cref="Changed"/> event. /// </summary> protected void RaiseChanged() { Changed?.Invoke(this, EventArgs.Empty); } } }
mit
C#
709c8bf4defb741b1e81a08d7a55fec8aa252c29
Use cancellationToken whenever possible
hurricanepkt/DropboxRestAPI,saguiitay/DropboxRestAPI
src/DropboxRestAPI/LargeFileUploader.cs
src/DropboxRestAPI/LargeFileUploader.cs
using System; using System.IO; using System.Threading; using System.Threading.Tasks; using DropboxRestAPI.Models.Core; namespace DropboxRestAPI { public class LargeFileUploader { public static long BufferSize = 4 * 1024 * 1024; private readonly Client _client; private readonly Stream _dataSource; public LargeFileUploader(Client client, Stream dataSource) { _client = client; _dataSource = dataSource; } public async Task<MetaData> UploadFileStream(string path, string locale = null, bool overwrite = true, string parent_rev = null, bool autorename = true, string asTeamMember = null, CancellationToken cancellationToken = default(CancellationToken)) { string uploadId = null; long currentPosition = 0; var fragmentBuffer = new byte[BufferSize]; do { long endPosition = currentPosition + BufferSize; if (endPosition > _dataSource.Length) { endPosition = _dataSource.Length; } var count = await _dataSource.ReadAsync(fragmentBuffer, 0, (int) Math.Max(0, endPosition - currentPosition), cancellationToken).ConfigureAwait(false); var response = await _client.Core.Metadata.ChunkedUploadAsync(fragmentBuffer, count, uploadId, currentPosition, asTeamMember, cancellationToken).ConfigureAwait(false); uploadId = response.upload_id; currentPosition = endPosition; } while (currentPosition < _dataSource.Length); if (uploadId == null) return null; var uploadedItem = await _client.Core.Metadata.CommitChunkedUploadAsync(path, uploadId, locale, overwrite, parent_rev, autorename, asTeamMember, cancellationToken).ConfigureAwait(false); return uploadedItem; } } }
using System; using System.IO; using System.Threading.Tasks; using DropboxRestAPI.Models.Core; namespace DropboxRestAPI { public class LargeFileUploader { public static long BufferSize = 4 * 1024 * 1024; private readonly Client _client; private readonly Stream _dataSource; public LargeFileUploader(Client client, Stream dataSource) { _client = client; _dataSource = dataSource; } public async Task<MetaData> UploadFileStream(string path, string locale = null, bool overwrite = true, string parent_rev = null, bool autorename = true, string asTeamMember = null) { string uploadId = null; long currentPosition = 0; var fragmentBuffer = new byte[BufferSize]; do { long endPosition = currentPosition + BufferSize; if (endPosition > _dataSource.Length) { endPosition = _dataSource.Length; } var count = await _dataSource.ReadAsync(fragmentBuffer, 0, (int) Math.Max(0, endPosition - currentPosition)).ConfigureAwait(false); var response = await _client.Core.Metadata.ChunkedUploadAsync(fragmentBuffer, count, uploadId, currentPosition, asTeamMember).ConfigureAwait(false); uploadId = response.upload_id; currentPosition = endPosition; } while (currentPosition < _dataSource.Length); if (uploadId == null) return null; var uploadedItem = await _client.Core.Metadata.CommitChunkedUploadAsync(path, uploadId, locale, overwrite, parent_rev, autorename, asTeamMember).ConfigureAwait(false); return uploadedItem; } } }
mit
C#
84bc88c8885487a2e722e34fcd194b37f556456e
Correct #Name #2
darbio/cap-net,TeamnetGroup/cap-net
src/CAPNet.Tests/ValidatorTests/PolygonCoordinatePairsFirstLastValidatorTests.cs
src/CAPNet.Tests/ValidatorTests/PolygonCoordinatePairsFirstLastValidatorTests.cs
using CAPNet.Models; using System.Linq; using Xunit; namespace CAPNet { public class PolygonCoordinatePairsFirstLastValidatorTests { [Fact] public void PolygonWithFirstCoordinatePairDifferentFromLastCoordinatePairIsInvalid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 39.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.False(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.NotEmpty(pairErrors); } [Fact] public void PolygonWithFirstCoordinatePairEqualToLastCoordinatePairIsValid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 38.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.True(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.Empty(pairErrors); } } }
using CAPNet.Models; using System.Linq; using Xunit; namespace CAPNet { public class PolygonCoordinatePairsFirstLastValidatorTests { [Fact] public void PolygonWithFirstCoordinatePairDifferentFromLastCoordinatePairIsInvalid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 39.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.False(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.NotEmpty(pairErrors); } [Fact] public void PolygonWithFirstCoordinatePairEqualToLastCoordinatePairsIsValid() { var polygon = new Polygon("38.47,-120.14 38.34,-119.95 38.52,-119.74 38.62,-119.89 38.47,-120.14"); var polygonCoordinatePairsFirstLastValidator = new PolygonCoordinatePairsFirstLastValidator(polygon); Assert.True(polygonCoordinatePairsFirstLastValidator.IsValid); var pairErrors = from error in polygonCoordinatePairsFirstLastValidator.Errors where error.GetType() == typeof(PolygonCoordinatePairsFirstLastError) select error; Assert.Empty(pairErrors); } } }
mit
C#
7bf796bd5cc98604f18af4cc562f3aad94a0cf05
Test edge cases
bbrandt/FizzBuzzInc
src/UnitTests/FizzBuzzGeneratorTests.cs
src/UnitTests/FizzBuzzGeneratorTests.cs
using System; using System.Linq; using FizzBuzz; using FluentAssertions; using NUnit.Framework; namespace UnitTests { [TestFixture] public class FizzBuzzGeneratorTests { [Test] public void GetNumbers_should_return_buzz_when_5() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(4, 5).ToArray().Should().EndWith("buzz"); } [Test] public void GetNumbers_should_return_fizz_when_3() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(1, 3).ToArray().Should().EndWith("fizz"); } [Test] public void GetNumbers_should_return_fizzbuzz_when_15() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(1, 15).ToArray().Should().EndWith("fizzbuzz"); } [Test] public void GetNumbers_should_support_single_number() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(2, 2).ToArray().Should().EndWith("2"); } [Test] public void GetNumbers_should_support_up_to_max_int() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(int.MaxValue - 5, int.MaxValue).ToArray().Should() .StartWith((int.MaxValue - 5).ToString()).And.EndWith(int.MaxValue.ToString()); } [Test] public void GetNumbers_should_throw_when_reversed() { var fizzBuzzGenerator = new FizzBuzzGenerator(); Action act = () => fizzBuzzGenerator.GetNumbers(57, 54).ToArray(); act.ShouldThrow<ArgumentOutOfRangeException>(); } [Test] public void GetNumbers_should_support_negative_numbers() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(-3, -1).ToArray().Should() .StartWith("fizz").And.EndWith("-1"); } // Configure CI // git repo // Add build script // Allow user to pass in as many number and word pairs as they like to replace the generated numbers // Add tests to ensure no regression } }
using System.Linq; using FizzBuzz; using FluentAssertions; using NUnit.Framework; namespace UnitTests { [TestFixture] public class FizzBuzzGeneratorTests { [Test] public void GetNumbers_should_return_buzz_when_5() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(4, 5).ToArray().Should().EndWith("buzz"); } [Test] public void GetNumbers_should_return_fizz_when_3() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(1, 3).ToArray().Should().EndWith("fizz"); } [Test] public void GetNumbers_should_return_fizzbuzz_when_15() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(1, 15).ToArray().Should().EndWith("fizzbuzz"); } [Test] public void GetNumbers_should_support_single_number() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(2, 2).ToArray().Should().EndWith("2"); } [Test] public void GetNumbers_should_support_up_to_max_int() { var fizzBuzzGenerator = new FizzBuzzGenerator(); fizzBuzzGenerator.GetNumbers(int.MaxValue - 5, int.MaxValue).ToArray().Should() .StartWith((int.MaxValue - 5).ToString()).And.EndWith(int.MaxValue.ToString()); } // Configure CI // git repo // Add build script // Allow user to pass in as many number and word pairs as they like to replace the generated numbers // Add tests to ensure no regression } }
apache-2.0
C#
64edbf27a2c2c5957c478e8839b52b3c44cce026
Update file version to 3.2.1.0
amay077/Xamarin.Forms.GoogleMaps
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2019"; public const string Trademark = ""; public const string Version = "3.2.1.0"; } }
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2019"; public const string Trademark = ""; public const string Version = "3.2.0.0"; } }
mit
C#
3dc1787d7f119e6d2cbf02ae903e008c53071cd2
ADD VERIFIER
ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins
stankinsv2/solution/StankinsV2/StankinsTestXUnit/TestReceiverHtmlSelector.cs
stankinsv2/solution/StankinsV2/StankinsTestXUnit/TestReceiverHtmlSelector.cs
using FluentAssertions; using Stankins.File; using Stankins.HTML; using Stankins.Interfaces; using StankinsObjects; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Xbehave; using Xunit; using static System.Environment; namespace StankinsTestXUnit { [Trait("ReceiverHtmlSelector", "")] [Trait("ExternalDependency", "0")] public class TestReceiverHtmlSelector { [Scenario] [Example(@"Assets\bookmarks_11_17_17.html", "//dt/a",23)] public void TestSimpleCSV(string filepath,string selectgor, int NumberRows) { IDataToSent data=null; $"receiving the file {filepath} ".w(async () => { data= await new ReceiverHtmlSelector(filepath, Encoding.UTF8, selectgor).TransformData(null); }); $"Then should be a data".w(() => data.Should().NotBeNull()); $"With a table".w(() => { data.DataToBeSentFurther.Should().NotBeNull(); data.DataToBeSentFurther.Count.Should().Be(1); }); $"The number of rows should be {NumberRows}".w(() => data.DataToBeSentFurther[0].Rows.Count.Should().Be(NumberRows)); $"and verifier is ok".w(async () => data= await new Verifier().TransformData(data)); } } }
using FluentAssertions; using Stankins.File; using Stankins.HTML; using Stankins.Interfaces; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Xbehave; using Xunit; using static System.Environment; namespace StankinsTestXUnit { [Trait("ReceiverHtmlSelector", "")] [Trait("ExternalDependency", "0")] public class TestReceiverHtmlSelector { [Scenario] [Example(@"Assets\bookmarks_11_17_17.html", "//dt/a",23)] public void TestSimpleCSV(string filepath,string selectgor, int NumberRows) { IDataToSent data=null; $"receiving the file {filepath} ".w(async () => { data= await new ReceiverHtmlSelector(filepath, Encoding.UTF8, selectgor).TransformData(null); }); $"Then should be a data".w(() => data.Should().NotBeNull()); $"With a table".w(() => { data.DataToBeSentFurther.Should().NotBeNull(); data.DataToBeSentFurther.Count.Should().Be(1); }); $"The number of rows should be {NumberRows}".w(() => data.DataToBeSentFurther[0].Rows.Count.Should().Be(NumberRows)); } } }
mit
C#
e7ba86c13c348be0b671dd052fd9a3a351fdc487
Remove obsolete field set.
adamfur/NEventStore,gael-ltd/NEventStore,paritoshmmmec/NEventStore,NEventStore/NEventStore,chris-evans/NEventStore,nerdamigo/NEventStore,AGiorgetti/NEventStore,D3-LucaPiombino/NEventStore,jamiegaines/NEventStore,deltatre-webplu/NEventStore,marcoaoteixeira/NEventStore
src/tests/EventStore.Persistence.MongoPersistence.Tests/AcceptanceTests/PersistenceEngineFixture.cs
src/tests/EventStore.Persistence.MongoPersistence.Tests/AcceptanceTests/PersistenceEngineFixture.cs
using EventStore.Persistence.MongoPersistence.Tests; namespace EventStore.Persistence.AcceptanceTests { public partial class PersistenceEngineFixture { public PersistenceEngineFixture() { this.createPersistence = () => new AcceptanceTestMongoPersistenceFactory().Build(); } } }
using EventStore.Persistence.MongoPersistence.Tests; namespace EventStore.Persistence.AcceptanceTests { public partial class PersistenceEngineFixture { public PersistenceEngineFixture() { this.createPersistence = () => new AcceptanceTestMongoPersistenceFactory().Build(); this.purgeOnDispose = true; } } }
mit
C#
6e8e4611e8896357c17cf5ee6d45db5d71e9439f
Increase the rebuild timebox to 24 hours
Elders/Cronus,Elders/Cronus
src/Elders.Cronus/Projections/Versioning/VersionRequestTimebox.cs
src/Elders.Cronus/Projections/Versioning/VersionRequestTimebox.cs
using System; using System.Runtime.Serialization; namespace Elders.Cronus.Projections.Versioning { /// <summary> /// Specifies a time frame when a projection rebuild starts and when it expires /// </summary> [DataContract(Name = "4c8d4c59-cc5a-40f8-9b08-14fcc57f51a9")] public class VersionRequestTimebox { const int OneHour = 3600000; const int EightHours = 28800000; const int RealyLongTime = 24 * 60 * 60; VersionRequestTimebox() { } public VersionRequestTimebox(DateTime rebuildStartAt) : this(rebuildStartAt, rebuildStartAt.AddMilliseconds(RealyLongTime)) { } public VersionRequestTimebox(DateTime rebuildStartAt, DateTime rebuildFinishUntil) { if (rebuildStartAt.AddMinutes(1) >= rebuildFinishUntil) throw new ArgumentException("Projection rebuild timebox is not realistic."); RebuildStartAt = rebuildStartAt; RebuildFinishUntil = rebuildFinishUntil; } /// <summary> /// The time when a <see cref="VersionRequestTimebox"/> starts /// </summary> [DataMember(Order = 1)] public DateTime RebuildStartAt { get; private set; } /// <summary> /// The time when a <see cref="VersionRequestTimebox"/> expires /// </summary> [DataMember(Order = 2)] public DateTime RebuildFinishUntil { get; private set; } public VersionRequestTimebox GetNext() { var newStartAt = DateTime.UtcNow; if (newStartAt < RebuildFinishUntil) newStartAt = RebuildFinishUntil; return new VersionRequestTimebox(newStartAt); } public VersionRequestTimebox Reset() { return new VersionRequestTimebox() { RebuildStartAt = RebuildStartAt, RebuildFinishUntil = DateTime.UtcNow }; } public override string ToString() { return $"Version request timebox: Starts at `{RebuildStartAt}`. Expires at `{RebuildFinishUntil}`"; } } }
using System; using System.Runtime.Serialization; namespace Elders.Cronus.Projections.Versioning { /// <summary> /// Specifies a time frame when a projection rebuild starts and when it expires /// </summary> [DataContract(Name = "4c8d4c59-cc5a-40f8-9b08-14fcc57f51a9")] public class VersionRequestTimebox { const int OneHour = 3600000; const int EightHours = 28800000; VersionRequestTimebox() { } public VersionRequestTimebox(DateTime rebuildStartAt) : this(rebuildStartAt, rebuildStartAt.AddMilliseconds(EightHours)) { } public VersionRequestTimebox(DateTime rebuildStartAt, DateTime rebuildFinishUntil) { if (rebuildStartAt.AddMinutes(1) >= rebuildFinishUntil) throw new ArgumentException("Projection rebuild timebox is not realistic."); RebuildStartAt = rebuildStartAt; RebuildFinishUntil = rebuildFinishUntil; } /// <summary> /// The time when a <see cref="VersionRequestTimebox"/> starts /// </summary> [DataMember(Order = 1)] public DateTime RebuildStartAt { get; private set; } /// <summary> /// The time when a <see cref="VersionRequestTimebox"/> expires /// </summary> [DataMember(Order = 2)] public DateTime RebuildFinishUntil { get; private set; } public VersionRequestTimebox GetNext() { var newStartAt = DateTime.UtcNow; if (newStartAt < RebuildFinishUntil) newStartAt = RebuildFinishUntil; return new VersionRequestTimebox(newStartAt); } public VersionRequestTimebox Reset() { return new VersionRequestTimebox() { RebuildStartAt = RebuildStartAt, RebuildFinishUntil = DateTime.UtcNow }; } public override string ToString() { return $"Version request timebox: Starts at `{RebuildStartAt}`. Expires at `{RebuildFinishUntil}`"; } } }
apache-2.0
C#
00ac030dbdef9f145432583739419fa05b1ea601
Fix test
andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop
src/BloomTests/web/ReadersApiTests.cs
src/BloomTests/web/ReadersApiTests.cs
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using Bloom.Edit; using Bloom.Api; using Bloom.Collection; using NUnit.Framework; namespace BloomTests.web { [TestFixture] public class ReadersApiTests { private EnhancedImageServer _server; [SetUp] public void Setup() { _server = new EnhancedImageServer(); //needed to avoid a check in the server _server.CurrentCollectionSettings = new CollectionSettings(); CurrentBookHandler.CurrentBook = new Bloom.Book.Book(); ReadersApi.Init(_server); //this won't get us far, as there is no project context setup } [TearDown] public void TearDown() { _server.Dispose(); _server = null; } [Test] public void Get_Test_Works() { var result = ApiTest.GetString(_server,"readers/test"); Assert.That(result, Is.EqualTo("OK")); } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using Bloom.Edit; using Bloom.Api; using NUnit.Framework; namespace BloomTests.web { [TestFixture] public class ReadersApiTests { private EnhancedImageServer _server; [SetUp] public void Setup() { _server = new EnhancedImageServer(); ReadersApi.Init(_server); //this won't get us far, as there is no project context setup } [TearDown] public void TearDown() { _server.Dispose(); _server = null; } [Test] public void Get_Test_Works() { var result = ApiTest.GetString(_server,"readers/test"); Assert.That(result, Is.EqualTo("OK")); } } }
mit
C#
430da258baa86efd966381fcf71f26998e5b94e2
Allow CreateBundles task Source property to be relative to current directory
honestegg/cassette,honestegg/cassette,damiensawyer/cassette,honestegg/cassette,andrewdavey/cassette,BluewireTechnologies/cassette,andrewdavey/cassette,andrewdavey/cassette,damiensawyer/cassette,damiensawyer/cassette,BluewireTechnologies/cassette
src/Cassette.MSBuild/CreateBundles.cs
src/Cassette.MSBuild/CreateBundles.cs
using System; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Cassette.MSBuild { [Serializable] [LoadInSeparateAppDomain] public class CreateBundles : AppDomainIsolatedTask { /// <summary> /// The root directory of the web application. /// </summary> public string Source { get; set; } /// <summary> /// The directory containing the web application assemblies. Default is "bin". /// </summary> public string Bin { get; set; } /// <summary> /// The directory to save the created bundles to. Default is "cassette-cache". /// </summary> public string Output { get; set; } public override bool Execute() { AssignPropertyDefaultsIfMissing(); MakePathsAbsolute(); using (var host = new MSBuildHost(Source, Bin, Output)) { host.Initialize(); host.Execute(); } return true; } void AssignPropertyDefaultsIfMissing() { if (string.IsNullOrEmpty(Source)) { Source = Environment.CurrentDirectory; } if (string.IsNullOrEmpty(Bin)) { Bin = "bin"; } if (string.IsNullOrEmpty(Output)) { Output = "cassette-cache"; } } void MakePathsAbsolute() { Source = Path.Combine(Environment.CurrentDirectory, Source); Bin = Path.Combine(Source, Bin); Output = Path.Combine(Source, Output); } } }
using System; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Cassette.MSBuild { [Serializable] [LoadInSeparateAppDomain] public class CreateBundles : AppDomainIsolatedTask { /// <summary> /// The root directory of the web application. /// </summary> public string Source { get; set; } /// <summary> /// The directory containing the web application assemblies. Default is "bin". /// </summary> public string Bin { get; set; } /// <summary> /// The directory to save the created bundles to. Default is "cassette-cache". /// </summary> public string Output { get; set; } public override bool Execute() { AssignPropertyDefaultsIfMissing(); MakePathsAbsolute(); using (var host = new MSBuildHost(Source, Bin, Output)) { host.Initialize(); host.Execute(); } return true; } void AssignPropertyDefaultsIfMissing() { if (string.IsNullOrEmpty(Source)) { Source = Environment.CurrentDirectory; } if (string.IsNullOrEmpty(Bin)) { Bin = "bin"; } if (string.IsNullOrEmpty(Output)) { Output = "cassette-cache"; } } void MakePathsAbsolute() { Bin = Path.Combine(Source, Bin); Output = Path.Combine(Source, Output); } } }
mit
C#
24757cb69e2b1458e59270b280d5200fcaeaa45b
Remove SpecsFor from TypingIndicator
noobot/SlackConnector
src/SlackConnector.Tests.Unit/SlackConnectionTests/TypingIndicatorTests.cs
src/SlackConnector.Tests.Unit/SlackConnectionTests/TypingIndicatorTests.cs
using System.Threading.Tasks; using Moq; using NUnit.Framework; using SlackConnector.Connections.Sockets; using SlackConnector.Connections.Sockets.Messages.Outbound; using SlackConnector.Models; namespace SlackConnector.Tests.Unit.SlackConnectionTests { internal class TypingIndicatorTests { [Test, AutoMoqData] public async Task should_send_ping(Mock<IWebSocketClient> webSocket, SlackConnection slackConnection) { // given const string slackKey = "key-yay"; var connectionInfo = new ConnectionInformation { WebSocket = webSocket.Object, SlackKey = slackKey }; await slackConnection.Initialise(connectionInfo); var chatHub = new SlackChatHub { Id = "channelz-id" }; // when await slackConnection.IndicateTyping(chatHub); // then webSocket.Verify(x => x.SendMessage(It.Is((TypingIndicatorMessage p) => p.Channel == chatHub.Id))); } } }
using NUnit.Framework; using Should; using SlackConnector.Connections.Sockets.Messages.Outbound; using SlackConnector.Models; using SlackConnector.Tests.Unit.Stubs; using SpecsFor; namespace SlackConnector.Tests.Unit.SlackConnectionTests { public static class TypingIndicatorTests { internal class given_valid_bot_message : SpecsFor<SlackConnection> { private string SlackKey = "doobeedoo"; private SlackChatHub _chatHub; private WebSocketClientStub _webSocketClient; protected override void Given() { _webSocketClient = new WebSocketClientStub(); _chatHub = new SlackChatHub { Id = "channelz-id" }; var connectionInfo = new ConnectionInformation { SlackKey = SlackKey, WebSocket = _webSocketClient }; SUT.Initialise(connectionInfo).Wait(); } protected override void When() { SUT.IndicateTyping(_chatHub).Wait(); } [Test] public void then_should_pass_expected_message_object() { var typingMessage = _webSocketClient.SendMessage_Message as TypingIndicatorMessage; typingMessage.ShouldNotBeNull(); typingMessage.Channel.ShouldEqual(_chatHub.Id); typingMessage.Type.ShouldEqual("typing"); } } } }
mit
C#
c0ce971a6fdc3d8f806ee16aaa84479bbd50c184
Fix null ref when opening Manage Packages dialog when no solution open
mrward/monodevelop-nuget-extensions,mrward/monodevelop-nuget-extensions
src/MonoDevelop.PackageManagement.Extensions/MonoDevelop.PackageManagement/ManagePackagesHandler2.cs
src/MonoDevelop.PackageManagement.Extensions/MonoDevelop.PackageManagement/ManagePackagesHandler2.cs
// // ManagePackagesHandler.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2013 Matthew Ward // // 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 ICSharpCode.PackageManagement; using MonoDevelop.Components.Commands; using MonoDevelop.Ide; using MonoDevelop.PackageManagement.Commands; namespace MonoDevelop.PackageManagement { public class ManagePackagesHandler2 : PackagesCommandHandler { protected override void Run () { try { ManagePackagesViewModel2 viewModel = CreateViewModel (); IPackageManagementEvents packageEvents = PackageManagementServices.PackageManagementEvents; var dialog = new ManagePackagesDialog2 (viewModel, packageEvents); MessageService.ShowCustomDialog (dialog); } catch (Exception ex) { MessageService.ShowException (ex); } } ManagePackagesViewModel2 CreateViewModel () { var packageEvents = new ThreadSafePackageManagementEvents (PackageManagementServices.PackageManagementEvents); var viewModels = new PackagesViewModels2 ( PackageManagementServices.Solution, PackageManagementServices.RegisteredPackageRepositories, packageEvents, PackageManagementServices.PackageActionRunner, new PackageManagementTaskFactory()); return new ManagePackagesViewModel2 ( viewModels, new ManagePackagesViewTitle (PackageManagementServices.Solution), packageEvents); } protected override void Update (CommandInfo info) { info.Enabled = PackageManagementServices.Solution.IsOpen && !IsDotNetProjectSelected (); } } }
// // ManagePackagesHandler.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2013 Matthew Ward // // 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 ICSharpCode.PackageManagement; using MonoDevelop.Components.Commands; using MonoDevelop.Ide; using MonoDevelop.PackageManagement.Commands; namespace MonoDevelop.PackageManagement { public class ManagePackagesHandler2 : PackagesCommandHandler { protected override void Run () { try { ManagePackagesViewModel2 viewModel = CreateViewModel (); IPackageManagementEvents packageEvents = PackageManagementServices.PackageManagementEvents; var dialog = new ManagePackagesDialog2 (viewModel, packageEvents); MessageService.ShowCustomDialog (dialog); } catch (Exception ex) { MessageService.ShowException (ex); } } ManagePackagesViewModel2 CreateViewModel () { var packageEvents = new ThreadSafePackageManagementEvents (PackageManagementServices.PackageManagementEvents); var viewModels = new PackagesViewModels2 ( PackageManagementServices.Solution, PackageManagementServices.RegisteredPackageRepositories, packageEvents, PackageManagementServices.PackageActionRunner, new PackageManagementTaskFactory()); return new ManagePackagesViewModel2 ( viewModels, new ManagePackagesViewTitle (PackageManagementServices.Solution), packageEvents); } protected override void Update (CommandInfo info) { info.Enabled = !IsDotNetProjectSelected (); } } }
mit
C#
cfa1c600910cb40cffcc71bbb72db392ad7d25f3
Fix list to use new deviceId
MatkovIvan/azure-mobile-apps-net-client,Azure/azure-mobile-apps-net-client,Azure/azure-mobile-apps-net-client,Azure/azure-mobile-apps-net-client,MatkovIvan/azure-mobile-apps-net-client,MatkovIvan/azure-mobile-apps-net-client
src/Microsoft.WindowsAzure.MobileServices.WindowsStore/Push/PushHttpClient.cs
src/Microsoft.WindowsAzure.MobileServices.WindowsStore/Push/PushHttpClient.cs
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ using System; using System.Net.Http; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.MobileServices { using System.Collections.Generic; using System.Threading.Tasks; internal sealed class PushHttpClient { private readonly MobileServiceHttpClient httpClient; private readonly MobileServiceSerializer serializer; internal PushHttpClient(MobileServiceHttpClient httpClient, MobileServiceSerializer serializer) { this.httpClient = httpClient; this.serializer = serializer; } public async Task<IEnumerable<Registration>> ListRegistrationsAsync(string channelUri) { var response = await httpClient.RequestAsync(HttpMethod.Get, string.Format("/push/registrations?deviceId={0}&platform=wns", Uri.EscapeUriString(channelUri))); var jsonRegistrations = JToken.Parse(response.Content) as JArray; return serializer.Deserialize<Registration>(jsonRegistrations); } public Task UnregisterAsync(string registrationId) { return httpClient.RequestAsync(HttpMethod.Delete, "/push/registrations/" + registrationId, ensureResponseContent: false); } public async Task<string> CreateRegistrationIdAsync() { var response = await httpClient.RequestAsync(HttpMethod.Post, "/push/registrationids", null, null); var locationPath = response.Headers.Location.AbsolutePath; return locationPath.Substring(locationPath.LastIndexOf('/') + 1); } public Task CreateOrUpdateRegistrationAsync(Registration registration) { var content = this.serializer.Serialize(registration).ToString(); return httpClient.RequestAsync(HttpMethod.Put, "/push/registrations/" + registration.RegistrationId, content, ensureResponseContent: false); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ using System; using System.Net.Http; using Newtonsoft.Json.Linq; namespace Microsoft.WindowsAzure.MobileServices { using System.Collections.Generic; using System.Threading.Tasks; internal sealed class PushHttpClient { private readonly MobileServiceHttpClient httpClient; private readonly MobileServiceSerializer serializer; internal PushHttpClient(MobileServiceHttpClient httpClient, MobileServiceSerializer serializer) { this.httpClient = httpClient; this.serializer = serializer; } public async Task<IEnumerable<Registration>> ListRegistrationsAsync(string channelUri) { var response = await httpClient.RequestAsync(HttpMethod.Get, string.Format("/push/registrations?channelUri={0}&platform=wns", Uri.EscapeUriString(channelUri))); var jsonRegistrations = JToken.Parse(response.Content) as JArray; return serializer.Deserialize<Registration>(jsonRegistrations); } public Task UnregisterAsync(string registrationId) { return httpClient.RequestAsync(HttpMethod.Delete, "/push/registrations/" + registrationId, ensureResponseContent: false); } public async Task<string> CreateRegistrationIdAsync() { var response = await httpClient.RequestAsync(HttpMethod.Post, "/push/registrationids", null, null); var locationPath = response.Headers.Location.AbsolutePath; return locationPath.Substring(locationPath.LastIndexOf('/') + 1); } public Task CreateOrUpdateRegistrationAsync(Registration registration) { var content = this.serializer.Serialize(registration).ToString(); return httpClient.RequestAsync(HttpMethod.Put, "/push/registrations/" + registration.RegistrationId, content, ensureResponseContent: false); } } }
apache-2.0
C#
783bf7ac16a46cb02c568a174765292deca0eaa1
Add test case to enumerate all states and inspect state vector layout
isse-augsburg/ssharp,maul-esel/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp
Models/SelfOrganizingPillProduction/Analysis/ModelCheckingTests.cs
Models/SelfOrganizingPillProduction/Analysis/ModelCheckingTests.cs
using NUnit.Framework; using SafetySharp.Analysis; using SafetySharp.Modeling; using SafetySharp.CaseStudies.SelfOrganizingPillProduction.Modeling; using static SafetySharp.Analysis.Operators; namespace SafetySharp.CaseStudies.SelfOrganizingPillProduction.Analysis { public class ModelCheckingTests { [Test] public void Dcca() { //var model = Model.NoRedundancyCircularModel(); var model = new ModelSetupParser().Parse("Analysis/medium_setup.model"); var modelChecker = new SafetyAnalysis(); modelChecker.Configuration.StateCapacity = 20000; var result = modelChecker.ComputeMinimalCriticalSets(model, model.ObserverController.Unsatisfiable); System.Console.WriteLine(result); } [Test] public void EnumerateAllStates() { var model = new ModelSetupParser().Parse("Analysis/medium_setup.model"); model.Faults.SuppressActivations(); var checker = new SSharpChecker { Configuration = { StateCapacity = 1 << 18 } }; var result = checker.CheckInvariant(model, true); Console.WriteLine(result.StateVectorLayout); } [Test] public void ProductionCompletesIfNoFaultsOccur() { var model = Model.NoRedundancyCircularModel(); var recipe = new Recipe(new[] { new Ingredient(IngredientType.BlueParticulate, 1), new Ingredient(IngredientType.RedParticulate, 3), new Ingredient(IngredientType.BlueParticulate, 1) }, 6); model.ScheduleProduction(recipe); model.Faults.SuppressActivations(); var invariant = ((Formula) !recipe.ProcessingComplete).Implies(F(recipe.ProcessingComplete)); var result = ModelChecker.Check(model, invariant); Assert.That(result.FormulaHolds, "Recipe production never finishes"); } } }
using NUnit.Framework; using SafetySharp.Analysis; using SafetySharp.Modeling; using SafetySharp.CaseStudies.SelfOrganizingPillProduction.Modeling; using static SafetySharp.Analysis.Operators; namespace SafetySharp.CaseStudies.SelfOrganizingPillProduction.Analysis { public class ModelCheckingTests { [Test] public void Dcca() { //var model = Model.NoRedundancyCircularModel(); var model = new ModelSetupParser().Parse("Analysis/medium_setup.model"); var modelChecker = new SafetyAnalysis(); modelChecker.Configuration.StateCapacity = 20000; var result = modelChecker.ComputeMinimalCriticalSets(model, model.ObserverController.Unsatisfiable); System.Console.WriteLine(result); } [Test] public void ProductionCompletesIfNoFaultsOccur() { var model = Model.NoRedundancyCircularModel(); var recipe = new Recipe(new[] { new Ingredient(IngredientType.BlueParticulate, 1), new Ingredient(IngredientType.RedParticulate, 3), new Ingredient(IngredientType.BlueParticulate, 1) }, 6); model.ScheduleProduction(recipe); model.Faults.SuppressActivations(); var invariant = ((Formula) !recipe.ProcessingComplete).Implies(F(recipe.ProcessingComplete)); var result = ModelChecker.Check(model, invariant); Assert.That(result.FormulaHolds, "Recipe production never finishes"); } } }
mit
C#
12ece15edb12b354c3b8b208321405160bf1acd8
Update FBXExporter assembly info
songjiahong/revitapisamples
1.6.FBXExporter/Properties/AssemblyInfo.cs
1.6.FBXExporter/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("FBXExporter")] [assembly: AssemblyDescription("Export all Revit files (rvt) in a given folder as fbx files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("revitapp.com")] [assembly: AssemblyProduct("FBXExporter")] [assembly: AssemblyCopyright("Copyright © revitapp.com 2017")] [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("90189ef4-d8e4-483b-aad5-90abbbcdfb50")] // 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")]
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("FBXExporter")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FBXExporter")] [assembly: AssemblyCopyright("Copyright © 2017")] [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("90189ef4-d8e4-483b-aad5-90abbbcdfb50")] // 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#
4c553a598045f9a5d87e3a07e53183cb910ca8cc
fix Upgrade_20211119_TimeZoneManagerToClock
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20211119_TimeZoneManagerToClock.cs
Signum.Upgrade/Upgrades/Upgrade_20211119_TimeZoneManagerToClock.cs
namespace Signum.Upgrade.Upgrades; class Upgrade_20211119_ClockToClock : CodeUpgradeBase { public override string Description => "Rename TimeZoneManager -> Clock"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile("*.cs", file => { file.Replace("TimeZoneManager", "Clock"); }); } }
namespace Signum.Upgrade.Upgrades; class Upgrade_20211119_ClockToClock : CodeUpgradeBase { public override string Description => "Rename TimeZoneManager -> Clock"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile("*.cs", new[] { uctx.AbsolutePath(""), uctx.AbsolutePath("Framework") }, file => { file.Replace("TimeZoneManager", "Clock"); }); } }
mit
C#
58deb3eb2a3bf07ca63fa116e57e1d296431c0fe
tweak to make tests pass
Brightspace/D2L.Security.OAuth2
test/D2L.Security.OAuth2.UnitTests/TestUtilities/Mocks/AccessTokenValidatorMock.cs
test/D2L.Security.OAuth2.UnitTests/TestUtilities/Mocks/AccessTokenValidatorMock.cs
using System; using D2L.Security.OAuth2.Validation.AccessTokens; using D2L.Security.OAuth2.Validation.Exceptions; using Moq; using NUnit.Framework; namespace D2L.Security.OAuth2.TestUtilities.Mocks { public static class AccessTokenValidatorMock { public static Mock<IAccessTokenValidator> Create( string accessToken, IAccessToken accessTokenAfterValidation, Type expectedExceptionType ) { var mock = new Mock<IAccessTokenValidator>(); var invocation = mock.Setup( v => v.ValidateAsync( accessToken ) ); if( expectedExceptionType == typeof( ValidationException ) ) { invocation.Throws( new ValidationException( "" ) ); } else if( expectedExceptionType != null ) { invocation.Throws( ( Exception )Activator.CreateInstance( expectedExceptionType ) ); } else { Assert.IsNotNull( accessTokenAfterValidation ); invocation.ReturnsAsync( accessTokenAfterValidation ); } return mock; } } }
using System; using D2L.Security.OAuth2.Validation.AccessTokens; using D2L.Security.OAuth2.Validation.Exceptions; using Moq; using NUnit.Framework; namespace D2L.Security.OAuth2.TestUtilities.Mocks { public static class AccessTokenValidatorMock { public static Mock<IAccessTokenValidator> Create( string accessToken, IAccessToken accessTokenAfterValidation, Type expectedExceptionType ) { var mock = new Mock<IAccessTokenValidator>(); var invocation = mock.Setup( v => v.ValidateAsync( accessToken ) ); if( expectedExceptionType == typeof( ValidationException ) ) { invocation.Throws( new ValidationException( "" ) ); } else if( expectedExceptionType != null ) { invocation.Throws( ( Exception )Activator.CreateInstance( expectedExceptionType, "" ) ); } else { Assert.IsNotNull( accessTokenAfterValidation ); invocation.ReturnsAsync( accessTokenAfterValidation ); } return mock; } } }
apache-2.0
C#
ab68d6056522280d4f4276426d460dbe93cd2501
Add comments in ButtonRoom.cs to explain behaviour.
Nilihum/fungus,tapiralec/Fungus,snozbot/fungus,kdoore/Fungus,RonanPearce/Fungus,inarizushi/Fungus,FungusGames/Fungus,lealeelu/Fungus
Assets/FungusExample/Scripts/ButtonRoom.cs
Assets/FungusExample/Scripts/ButtonRoom.cs
using UnityEngine; using System.Collections; using Fungus; public class ButtonRoom : Room { public Room menuRoom; public AudioClip effectClip; public SpriteRenderer homeSprite; public SpriteRenderer musicSprite; public SpriteRenderer questionSprite; void OnEnter() { // Normal button, always visible AddButton(homeSprite, OnHomeClicked); // Auto buttons, hidden when story/options are being displayed AddAutoButton(musicSprite, OnMusicClicked); AddAutoButton(questionSprite, OnQuestionClicked); // NOTE: Add auto buttons before first Say() command to ensure they start hidden Say("The Mushroom read his book with great interest."); Say("After turning the last page, he considered his options."); // Once the last Say command executes the page will dissappear because there's no more content to show. // At that point, the game will automatically fade in all Auto Buttons in the room } void OnHomeClicked() { MoveToRoom(menuRoom); } void OnMusicClicked() { PlaySound(effectClip); } void OnQuestionClicked() { // All Auto Buttons are automatically hidden as soon as the page has more content to show Say("What book was he reading?"); Say("Sadly we will never know for sure."); } }
using UnityEngine; using System.Collections; using Fungus; public class ButtonRoom : Room { public Room menuRoom; public AudioClip effectClip; public SpriteRenderer homeSprite; public SpriteRenderer musicSprite; public SpriteRenderer questionSprite; void OnEnter() { // Normal button, always visible AddButton(homeSprite, OnHomeClicked); // Auto buttons, hidden when story/options are being displayed AddAutoButton(musicSprite, OnMusicClicked); AddAutoButton(questionSprite, OnQuestionClicked); // NOTE: Add auto buttons before first Say() command to ensure they start hidden Say("The Mushroom read his book with great interest."); Say("After turning the last page, he considered his options."); } void OnHomeClicked() { MoveToRoom(menuRoom); } void OnMusicClicked() { PlaySound(effectClip); } void OnQuestionClicked() { Say("What book was he reading?"); Say("Perhaps we will never know for sure."); } }
mit
C#
530dfba4a2cfb4620bc39453c83d6f5a75840e4e
rename IMediaFile.Path to Extension
ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey
client/BlueMonkey/BlueMonkey.ExpenseServices.Azure.Shared/AzureFileUploadService.cs
client/BlueMonkey/BlueMonkey.ExpenseServices.Azure.Shared/AzureFileUploadService.cs
using BlueMonkey.MediaServices; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.Threading.Tasks; namespace BlueMonkey.ExpenseServices.Azure { public class AzureFileUploadService : IFileUploadService { private static readonly string ContainerName = "pictures"; private readonly CloudBlobContainer _container; public AzureFileUploadService() { var account = CloudStorageAccount.Parse(Secrets.FileUploadStorageConnectionString); var client = account.CreateCloudBlobClient(); _container = client.GetContainerReference(ContainerName); } public async Task<Uri> UploadMediaFileAsync(IMediaFile mediaFile) { await _container.CreateIfNotExistsAsync(); await _container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); var fileName = $"{Guid.NewGuid()}{mediaFile.Extension}"; var blockBlob = _container.GetBlockBlobReference(fileName); using (var stream = mediaFile.GetStream()) { await blockBlob.UploadFromStreamAsync(stream); } return blockBlob.Uri; } } }
using BlueMonkey.MediaServices; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.IO; using System.Threading.Tasks; namespace BlueMonkey.ExpenseServices.Azure { public class AzureFileUploadService : IFileUploadService { private static readonly string ContainerName = "pictures"; private readonly CloudBlobContainer _container; public AzureFileUploadService() { var account = CloudStorageAccount.Parse(Secrets.FileUploadStorageConnectionString); var client = account.CreateCloudBlobClient(); _container = client.GetContainerReference(ContainerName); } public async Task<Uri> UploadMediaFileAsync(IMediaFile mediaFile) { await _container.CreateIfNotExistsAsync(); await _container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }); var fileName = $"{Guid.NewGuid()}{Path.GetExtension(mediaFile.Path)}"; var blockBlob = _container.GetBlockBlobReference(fileName); using (var stream = mediaFile.GetStream()) { await blockBlob.UploadFromStreamAsync(stream); } return blockBlob.Uri; } } }
mit
C#
db5eada48afb00b284a48e9aea3c8afcb5ef7dbd
Check encoding for export-msipatchxml cmdlet tests
SamB/psmsi,SamB/psmsi,jkorell/psmsi,heaths/psmsi,heaths/psmsi,jkorell/psmsi
src/Microsoft.Tools.WindowsInstaller.PowerShell.Test/PowerShell/Commands/ExportPatchXmlCommandTests.cs
src/Microsoft.Tools.WindowsInstaller.PowerShell.Test/PowerShell/Commands/ExportPatchXmlCommandTests.cs
// Copyright (C) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; using System.Text; namespace Microsoft.Tools.WindowsInstaller.PowerShell.Commands { /// <summary> /// Tests for the <see cref="ExportPatchXmlCommand"/> class. /// </summary> [TestClass] public sealed class ExportPatchXmlCommandTests : CommandTestBase { [TestMethod] public void ExtractPatchFileXml() { using (var rs = this.TestRunspace.CreatePipeline(@"export-msipatchxml ""$TestDeploymentDirectory\example.msp"" ""$TestRunDirectory\patchfilexml.xml""")) { rs.Invoke(); string path = Path.Combine(this.TestContext.TestRunDirectory, "patchfilexml.xml"); Assert.IsTrue(File.Exists(path), "The output file does not exist."); // Check that the default encoding is correct. using (var file = File.OpenText(path)) { Assert.AreEqual<Encoding>(Encoding.UTF8, file.CurrentEncoding, "The encoding is incorreect."); } } } [TestMethod] public void ExtractPatchFileFormattedXml() { using (var rs = this.TestRunspace.CreatePipeline(@"export-msipatchxml ""$TestDeploymentDirectory\example.msp"" ""$TestRunDirectory\patchfileformattedxml.xml"" -encoding Unicode -formatted")) { rs.Invoke(); string path = Path.Combine(this.TestContext.TestRunDirectory, "patchfileformattedxml.xml"); Assert.IsTrue(File.Exists(path), "The output file does not exist."); // Make sure the file contains tabs. using (var file = File.OpenText(path)) { string xml = file.ReadToEnd(); StringAssert.Contains(xml, "\t", "The file does not contain tabs."); Assert.AreEqual<Encoding>(Encoding.Unicode, file.CurrentEncoding, "The encoding is incorrect."); } } } } }
// Copyright (C) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace Microsoft.Tools.WindowsInstaller.PowerShell.Commands { /// <summary> /// Tests for the <see cref="ExportPatchXmlCommand"/> class. /// </summary> [TestClass] public sealed class ExportPatchXmlCommandTests : CommandTestBase { [TestMethod] public void ExtractPatchFileXml() { using (var rs = this.TestRunspace.CreatePipeline(@"export-msipatchxml ""$TestDeploymentDirectory\example.msp"" ""$TestRunDirectory\patchfilexml.xml""")) { rs.Invoke(); string path = Path.Combine(this.TestContext.TestRunDirectory, "patchfilexml.xml"); Assert.IsTrue(File.Exists(path), "The output file does not exist."); } } [TestMethod] public void ExtractPatchFileFormattedXml() { using (var rs = this.TestRunspace.CreatePipeline(@"export-msipatchxml ""$TestDeploymentDirectory\example.msp"" ""$TestRunDirectory\patchfileformattedxml.xml"" -formatted")) { rs.Invoke(); string path = Path.Combine(this.TestContext.TestRunDirectory, "patchfileformattedxml.xml"); Assert.IsTrue(File.Exists(path), "The output file does not exist."); // Make sure the file contains tabs. using (var file = File.OpenText(path)) { string xml = file.ReadToEnd(); StringAssert.Contains(xml, "\t", "The file does not contain tabs."); } } } } }
mit
C#
bbe0f22d3319c9eb2341330b46c1ce091a1fff94
test cases
jefking/King.Mapper
King.Mapper.Tests/Data/IDataReaderTests.cs
King.Mapper.Tests/Data/IDataReaderTests.cs
namespace King.Mapper.Tests.Data { using King.Mapper.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Data; [TestClass] public class IDataReaderTests { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void LoadObjectReaderNull() { IDataReader reader = null; reader.LoadObject<object>(); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void LoadObjectsReaderNull() { IDataReader reader = null; reader.LoadObjects<object>(); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void GetFieldNamesReaderNull() { IDataReader reader = null; reader.GetFieldNames(); } } }
namespace King.Mapper.Tests.Data { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Data; using King.Mapper.Data; [TestClass] public class IDataReaderTests { [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void LoadObjectReaderNull() { IDataReader reader = null; reader.LoadObject<object>(); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void LoadObjectsReaderNull() { IDataReader reader = null; reader.LoadObjects<object>(); } } }
mit
C#
d817b2a2c3c999167ed10071ad0fd75fceeb327d
Fix small bug
kw90/SantasSledge
Santa/MetaHeuristics/SimulatedAnnealing.cs
Santa/MetaHeuristics/SimulatedAnnealing.cs
using System; using System.Collections.Generic; using Common; using FirstSolution.Algos; namespace MetaHeuristics { public class SimulatedAnnealing : ISolver { double _temperature; Random random = new Random(); double _coolingRate; public SimulatedAnnealing(double temperature, double coolingRate) { this._temperature = temperature; this._coolingRate = coolingRate; } public SimulatedAnnealing() { _temperature = 1000000; _coolingRate = 0.003; } private double acceptanceProbability(double energy, double newEnergy, double temperature) { if (newEnergy < energy) return 1.0; return Math.Exp((energy - newEnergy) / temperature); } public List<Gift> Solve(List<Tour> tours) { int numberOfTours = tours.Count; List<Tour> bestTours = tours; double totalCurrentEnergy = Common.Algos.WeightedReindeerWeariness.Calculate(bestTours); while (_temperature > 1) { var maxIndex = numberOfTours - 1; int randomNumber1 = random.Next(0, maxIndex); int randomNumber2 = random.Next(0, maxIndex); Tour first = tours[randomNumber1]; Tour second = tours[randomNumber2]; double firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first); double secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second); double currentEnergy = firstWRW + secondWRW; List<Tour> changedTours = RouteImprovement.Swap(tours[randomNumber1], tours[randomNumber2]) as List<Tour>; first = changedTours[0]; second = changedTours[1]; firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first); secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second); double neighbourEnergy = firstWRW + secondWRW; if (acceptanceProbability(currentEnergy, neighbourEnergy, _temperature) >= random.Next(0, 1)) { tours[randomNumber1] = changedTours[0]; tours[randomNumber2] = changedTours[1]; } var currentNewEnergy = Common.Algos.WeightedReindeerWeariness.Calculate(tours); Console.WriteLine("{0}, {1}", totalCurrentEnergy, currentNewEnergy); if (totalCurrentEnergy > currentNewEnergy) { bestTours = tours; } _temperature *= 1 - _coolingRate; } List<Gift> bestGiftOrder = new List<Gift>(); foreach (Tour tour in bestTours) { bestGiftOrder.AddRange(tour.Gifts); } return bestGiftOrder; } } }
using System; using System.Collections.Generic; using Common; using FirstSolution.Algos; namespace MetaHeuristics { public class SimulatedAnnealing : ISolver { double _temperature; Random random = new Random(); double _coolingRate; public SimulatedAnnealing(double temperature, double coolingRate) { this._temperature = temperature; this._coolingRate = coolingRate; } public SimulatedAnnealing() { _temperature = 1000000; _coolingRate = 0.003; } private double acceptanceProbability(double energy, double newEnergy, double temperature) { if (newEnergy < energy) return 1.0; return Math.Exp((energy - newEnergy) / temperature); } public List<Gift> Solve(List<Tour> tours) { int numberOfTours = tours.Count; List<Tour> bestTours = new List<Tour>(); while (_temperature > 1) { var maxIndex = numberOfTours - 1; int randomNumber1 = random.Next(0, maxIndex); int randomNumber2 = random.Next(0, maxIndex); Tour first = tours[randomNumber1]; Tour second = tours[randomNumber2]; double firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first); double secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second); double currentEnergy = firstWRW + secondWRW; List<Tour> changedTours = RouteImprovement.Swap(tours[randomNumber1], tours[randomNumber2]) as List<Tour>; first = changedTours[0]; second = changedTours[1]; firstWRW = Common.Algos.WeightedReindeerWeariness.Calculate(first); secondWRW = Common.Algos.WeightedReindeerWeariness.Calculate(second); double neighbourEnergy = firstWRW + secondWRW; if (acceptanceProbability(currentEnergy, neighbourEnergy, _temperature) >= random.Next(0, 1)) { tours[randomNumber1] = changedTours[0]; tours[randomNumber2] = changedTours[1]; } var currentNewEnergy = Common.Algos.WeightedReindeerWeariness.Calculate(bestTours); Console.WriteLine("{0}, {1}", currentEnergy, currentNewEnergy); if (currentEnergy < currentNewEnergy) { bestTours = tours; } _temperature *= 1 - _coolingRate; } List<Gift> bestGiftOrder = new List<Gift>(); foreach (Tour tour in bestTours) { bestGiftOrder.AddRange(tour.Gifts); } return bestGiftOrder; } } }
mit
C#
be3d841e576a83354476c905b51882159daba5cc
Fix mono compilation error
k-t/SharpHaven
SharpHaven.Common/Resources/ResourceRef.cs
SharpHaven.Common/Resources/ResourceRef.cs
using System; namespace SharpHaven.Resources { public struct ResourceRef { public ResourceRef(string name, ushort version) { if (name == null) throw new ArgumentNullException(nameof(name)); this.Name = name; this.Version = version; } public string Name { get; } public ushort Version { get; } public override int GetHashCode() { return Name.GetHashCode() ^ Version.GetHashCode(); } public override bool Equals(object obj) { if (!(obj is ResourceRef)) return false; var other = (ResourceRef)obj; return string.Equals(Name, other.Name) && Version == other.Version; } } }
using System; namespace SharpHaven.Resources { public struct ResourceRef { public ResourceRef(string name, ushort version) { if (name == null) throw new ArgumentNullException(nameof(name)); Name = name; Version = version; } public string Name { get; } public ushort Version { get; } public override int GetHashCode() { return Name.GetHashCode() ^ Version.GetHashCode(); } public override bool Equals(object obj) { if (!(obj is ResourceRef)) return false; var other = (ResourceRef)obj; return string.Equals(Name, other.Name) && Version == other.Version; } } }
mit
C#
fb59c07847df00f9ca0e452b79374e9a2fca1845
Fix failed test
amironov73/ManagedIrbis,amironov73/ManagedIrbis,amironov73/ManagedIrbis,amironov73/ManagedIrbis,amironov73/ManagedIrbis
UnitTests/ManagedClient/IrbisRecordTest.cs
UnitTests/ManagedClient/IrbisRecordTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AM.Runtime; using ManagedClient; namespace UnitTests.ManagedClient { [TestClass] public class IrbisRecordTest { [TestMethod] public void TestIrbisRecordConstruction() { IrbisRecord record = new IrbisRecord(); Assert.IsNotNull(record); Assert.IsNotNull(record.Fields); Assert.IsNull(record.Database); Assert.IsNull(record.Description); Assert.AreEqual(0, record.Version); } private void _TestSerialization ( IrbisRecord record1 ) { byte[] bytes = record1.SaveToMemory(); IrbisRecord record2 = bytes .RestoreObjectFromMemory<IrbisRecord>(); Assert.IsNotNull(record2); Assert.AreEqual ( 0, IrbisRecord.Compare ( record1, record2 ) ); } [TestMethod] public void TestIrbisRecordSerialization() { IrbisRecord record = new IrbisRecord(); _TestSerialization(record); record.Fields.Add(new RecordField("200")); _TestSerialization(record); record.Fields.Add(new RecordField("300", "Hello")); _TestSerialization(record); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AM.Runtime; using ManagedClient; namespace UnitTests.ManagedClient { [TestClass] public class IrbisRecordTest { [TestMethod] public void TestIrbisRecordConstruction() { IrbisRecord record = new IrbisRecord(); Assert.IsNotNull(record); Assert.IsNotNull(record.Fields); Assert.IsNull(record.Database); Assert.IsNotNull(record.Description); Assert.AreEqual(0, record.Version); } private void _TestSerialization ( IrbisRecord record1 ) { byte[] bytes = record1.SaveToMemory(); IrbisRecord record2 = bytes .RestoreObjectFromMemory<IrbisRecord>(); Assert.IsNotNull(record2); Assert.AreEqual ( 0, IrbisRecord.Compare ( record1, record2 ) ); } [TestMethod] public void TestIrbisRecordSerialization() { IrbisRecord record = new IrbisRecord(); _TestSerialization(record); record.Fields.Add(new RecordField("200")); _TestSerialization(record); record.Fields.Add(new RecordField("300", "Hello")); _TestSerialization(record); } } }
mit
C#
8c5a526b2af9299ec126b34586c9c632e8c88853
update file
SiddharthChatrolaMs/azure-sdk-for-net,peshen/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,atpham256/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,nathannfan/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,peshen/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,mihymel/azure-sdk-for-net,djyou/azure-sdk-for-net,r22016/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,samtoubia/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,olydis/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,samtoubia/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,smithab/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,AzCiS/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,pilor/azure-sdk-for-net,djyou/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,samtoubia/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,pilor/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,nathannfan/azure-sdk-for-net,djyou/azure-sdk-for-net,mihymel/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,btasdoven/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,smithab/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,pankajsn/azure-sdk-for-net,r22016/azure-sdk-for-net,pilor/azure-sdk-for-net,pankajsn/azure-sdk-for-net,stankovski/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,shutchings/azure-sdk-for-net,markcowl/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,shutchings/azure-sdk-for-net,r22016/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,btasdoven/azure-sdk-for-net,btasdoven/azure-sdk-for-net,jamestao/azure-sdk-for-net,atpham256/azure-sdk-for-net,hyonholee/azure-sdk-for-net,shutchings/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,olydis/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jamestao/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,begoldsm/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,mihymel/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,pankajsn/azure-sdk-for-net,begoldsm/azure-sdk-for-net,jamestao/azure-sdk-for-net,stankovski/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,AzCiS/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,jamestao/azure-sdk-for-net,atpham256/azure-sdk-for-net,nathannfan/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,olydis/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,begoldsm/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,peshen/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,AzCiS/azure-sdk-for-net,smithab/azure-sdk-for-net,samtoubia/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net
src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/Models/ExpressRouteServiceProvider.cs
src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/Models/ExpressRouteServiceProvider.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// ExpressRouteResourceProvider object /// </summary> public partial class ExpressRouteServiceProvider : Resource { /// <summary> /// Initializes a new instance of the ExpressRouteServiceProvider /// class. /// </summary> public ExpressRouteServiceProvider() { } /// <summary> /// Initializes a new instance of the ExpressRouteServiceProvider /// class. /// </summary> public ExpressRouteServiceProvider(IList<string> peeringLocations = default(IList<string>), IList<ExpressRouteServiceProviderBandwidthsOffered> bandwidthsOffered = default(IList<ExpressRouteServiceProviderBandwidthsOffered>), string provisioningState = default(string)) { PeeringLocations = peeringLocations; BandwidthsOffered = bandwidthsOffered; ProvisioningState = provisioningState; } /// <summary> /// Gets or list of peering locations /// </summary> [JsonProperty(PropertyName = "properties.peeringLocations")] public IList<string> PeeringLocations { get; set; } /// <summary> /// Gets or bandwidths offered /// </summary> [JsonProperty(PropertyName = "properties.bandwidthsOffered")] public IList<ExpressRouteServiceProviderBandwidthsOffered> BandwidthsOffered { get; set; } /// <summary> /// Gets or sets Provisioning state of the resource /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Microsoft.Rest.Azure; /// <summary> /// ExpressRouteResourceProvider object /// </summary> public partial class ExpressRouteServiceProvider : Resource { /// <summary> /// Initializes a new instance of the ExpressRouteServiceProvider /// class. /// </summary> public ExpressRouteServiceProvider() { } /// <summary> /// Initializes a new instance of the ExpressRouteServiceProvider /// class. /// </summary> public ExpressRouteServiceProvider(IList<string> peeringLocations = default(IList<string>), IList<ExpressRouteServiceProviderBandwidthsOffered> bandwidthsOffered = default(IList<ExpressRouteServiceProviderBandwidthsOffered>), string provisioningState = default(string)) { PeeringLocations = peeringLocations; BandwidthsOffered = bandwidthsOffered; ProvisioningState = provisioningState; } /// <summary> /// Gets or list of peering locations /// </summary> [JsonProperty(PropertyName = "properties.peeringLocations")] public IList<string> PeeringLocations { get; set; } /// <summary> /// Gets or bandwidths offered /// </summary> [JsonProperty(PropertyName = "properties.bandwidthsOffered")] public IList<ExpressRouteServiceProviderBandwidthsOffered> BandwidthsOffered { get; set; } /// <summary> /// Gets or sets Provisioning state of the resource /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } } }
apache-2.0
C#
8f169f27814342c68672fdf4c58d26049338cb91
Use invariant culture
genlu/roslyn,brettfo/roslyn,reaction1989/roslyn,tannergooding/roslyn,dotnet/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,agocke/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,abock/roslyn,AmadeusW/roslyn,dotnet/roslyn,nguerrera/roslyn,genlu/roslyn,eriawan/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,AmadeusW/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,stephentoub/roslyn,dotnet/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,physhi/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,weltkante/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,tmat/roslyn,gafter/roslyn,KevinRansom/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,agocke/roslyn,panopticoncentral/roslyn,sharwell/roslyn,jmarolf/roslyn,abock/roslyn,KevinRansom/roslyn,physhi/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,davkean/roslyn,mgoertz-msft/roslyn,gafter/roslyn,aelij/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,ErikSchierboom/roslyn,ErikSchierboom/roslyn,davkean/roslyn,nguerrera/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,eriawan/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,aelij/roslyn,weltkante/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,stephentoub/roslyn,tannergooding/roslyn,tannergooding/roslyn,genlu/roslyn,mavasani/roslyn,heejaechang/roslyn,brettfo/roslyn,heejaechang/roslyn,abock/roslyn,jmarolf/roslyn,wvdd007/roslyn,aelij/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,agocke/roslyn,physhi/roslyn,sharwell/roslyn,AlekseyTs/roslyn,davkean/roslyn,wvdd007/roslyn
src/Features/CSharp/Portable/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs
src/Features/CSharp/Portable/ConvertSwitchStatementToExpression/ConvertSwitchStatementToExpressionDiagnosticAnalyzer.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed partial class ConvertSwitchStatementToExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public ConvertSwitchStatementToExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId, new LocalizableResourceString(nameof(CSharpFeaturesResources.Convert_switch_statement_to_expression), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources)), new LocalizableResourceString(nameof(CSharpFeaturesResources.Use_switch_expression), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.SwitchStatement); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var switchStatement = context.Node; if (switchStatement.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) { return; } var nodeToGenerate = Analyzer.Analyze((SwitchStatementSyntax)switchStatement, out var shouldRemoveNextStatement); if (nodeToGenerate == default) { return; } context.ReportDiagnostic(Diagnostic.Create(Descriptor, // Report the diagnostic on the "switch" keyword. location: switchStatement.GetFirstToken().GetLocation(), additionalLocations: new[] { switchStatement.GetLocation() }, properties: ImmutableDictionary<string, string>.Empty .Add(Constants.NodeToGenerateKey, ((int)nodeToGenerate).ToString(CultureInfo.InvariantCulture)) .Add(Constants.ShouldRemoveNextStatementKey, shouldRemoveNextStatement.ToString(CultureInfo.InvariantCulture)))); } public override bool OpenFileOnly(Workspace workspace) => false; public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxAnalysis; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.ConvertSwitchStatementToExpression { using Constants = ConvertSwitchStatementToExpressionConstants; [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed partial class ConvertSwitchStatementToExpressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public ConvertSwitchStatementToExpressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.ConvertSwitchStatementToExpressionDiagnosticId, new LocalizableResourceString(nameof(CSharpFeaturesResources.Convert_switch_statement_to_expression), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources)), new LocalizableResourceString(nameof(CSharpFeaturesResources.Use_switch_expression), CSharpFeaturesResources.ResourceManager, typeof(CSharpFeaturesResources))) { } protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.SwitchStatement); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var switchStatement = context.Node; if (switchStatement.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) { return; } var nodeToGenerate = Analyzer.Analyze((SwitchStatementSyntax)switchStatement, out var shouldRemoveNextStatement); if (nodeToGenerate == default) { return; } context.ReportDiagnostic(Diagnostic.Create(Descriptor, // Report the diagnostic on the "switch" keyword. location: switchStatement.GetFirstToken().GetLocation(), additionalLocations: new[] { switchStatement.GetLocation() }, properties: ImmutableDictionary<string, string>.Empty .Add(Constants.NodeToGenerateKey, ((int)nodeToGenerate).ToString()) .Add(Constants.ShouldRemoveNextStatementKey, shouldRemoveNextStatement.ToString()))); } public override bool OpenFileOnly(Workspace workspace) => false; public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxAnalysis; } }
mit
C#
6e214001a1815f4f725b0453b97d1fc7eec1b09e
Extend the ParsePhoto example to also show the image size
Clancey/taglib-sharp,Clancey/taglib-sharp,archrival/taglib-sharp,CamargoR/taglib-sharp,archrival/taglib-sharp,hwahrmann/taglib-sharp,CamargoR/taglib-sharp,Clancey/taglib-sharp,mono/taglib-sharp,punker76/taglib-sharp,punker76/taglib-sharp,hwahrmann/taglib-sharp
examples/ParsePhoto.cs
examples/ParsePhoto.cs
using System; public class ParsePhotoApp { public static void Main (string [] args) { if(args.Length == 0) { Console.Error.WriteLine("USAGE: mono ParsePhoto.exe PATH [...]"); return; } foreach (string path in args) ParsePhoto (path); } static void ParsePhoto (string path) { TagLib.File file = null; try { file = TagLib.File.Create(path); } catch (TagLib.UnsupportedFormatException) { Console.WriteLine ("UNSUPPORTED FILE: " + path); Console.WriteLine (String.Empty); Console.WriteLine ("---------------------------------------"); Console.WriteLine (String.Empty); return; } var image = file as TagLib.Image.File; if (file == null) { Console.WriteLine ("NOT AN IMAGE FILE: " + path); Console.WriteLine (String.Empty); Console.WriteLine ("---------------------------------------"); Console.WriteLine (String.Empty); return; } Console.WriteLine (String.Empty); Console.WriteLine (path); Console.WriteLine (String.Empty); Console.WriteLine("Tags in object: " + image.TagTypes); Console.WriteLine (String.Empty); Console.WriteLine("Comment: " + image.ImageTag.Comment); Console.Write("Keywords: "); foreach (var keyword in image.ImageTag.Keywords) { Console.Write (keyword + " "); } Console.WriteLine (); Console.WriteLine("Rating: " + image.ImageTag.Rating); Console.WriteLine("DateTime: " + image.ImageTag.DateTime); Console.WriteLine("Orientation: " + image.ImageTag.Orientation); Console.WriteLine("Software: " + image.ImageTag.Software); Console.WriteLine("ExposureTime: " + image.ImageTag.ExposureTime); Console.WriteLine("FNumber: " + image.ImageTag.FNumber); Console.WriteLine("ISOSpeedRatings: " + image.ImageTag.ISOSpeedRatings); Console.WriteLine("FocalLength: " + image.ImageTag.FocalLength); Console.WriteLine("FocalLength35mm: " + image.ImageTag.FocalLengthIn35mmFilm); Console.WriteLine("Make: " + image.ImageTag.Make); Console.WriteLine("Model: " + image.ImageTag.Model); if (image.Properties != null) { Console.WriteLine("Width : " + image.Properties.PhotoWidth); Console.WriteLine("Height : " + image.Properties.PhotoHeight); } Console.WriteLine (String.Empty); Console.WriteLine ("---------------------------------------"); } }
using System; public class ParsePhotoApp { public static void Main (string [] args) { if(args.Length == 0) { Console.Error.WriteLine("USAGE: mono ParsePhoto.exe PATH [...]"); return; } foreach (string path in args) ParsePhoto (path); } static void ParsePhoto (string path) { TagLib.File file = null; try { file = TagLib.File.Create(path); } catch (TagLib.UnsupportedFormatException) { Console.WriteLine ("UNSUPPORTED FILE: " + path); Console.WriteLine (String.Empty); Console.WriteLine ("---------------------------------------"); Console.WriteLine (String.Empty); return; } var image = file as TagLib.Image.File; if (file == null) { Console.WriteLine ("NOT AN IMAGE FILE: " + path); Console.WriteLine (String.Empty); Console.WriteLine ("---------------------------------------"); Console.WriteLine (String.Empty); return; } Console.WriteLine (String.Empty); Console.WriteLine (path); Console.WriteLine (String.Empty); Console.WriteLine("Tags in object: " + image.TagTypes); Console.WriteLine (String.Empty); Console.WriteLine("Comment: " + image.ImageTag.Comment); Console.Write("Keywords: "); foreach (var keyword in image.ImageTag.Keywords) { Console.Write (keyword + " "); } Console.WriteLine (); Console.WriteLine("Rating: " + image.ImageTag.Rating); Console.WriteLine("DateTime: " + image.ImageTag.DateTime); Console.WriteLine("Orientation: " + image.ImageTag.Orientation); Console.WriteLine("Software: " + image.ImageTag.Software); Console.WriteLine("ExposureTime: " + image.ImageTag.ExposureTime); Console.WriteLine("FNumber: " + image.ImageTag.FNumber); Console.WriteLine("ISOSpeedRatings: " + image.ImageTag.ISOSpeedRatings); Console.WriteLine("FocalLength: " + image.ImageTag.FocalLength); Console.WriteLine("FocalLength35mm: " + image.ImageTag.FocalLengthIn35mmFilm); Console.WriteLine("Make: " + image.ImageTag.Make); Console.WriteLine("Model: " + image.ImageTag.Model); Console.WriteLine (String.Empty); Console.WriteLine ("---------------------------------------"); } }
lgpl-2.1
C#
0f2fa5b4f214e80760bd3f8dca9a89ac8c2b07f0
Bump version to 0.30.3
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.30.3"; } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.30.2"; } }
mit
C#
d103888f8851367d6fc319f0db01ddf8495d89bc
Bump version to 1.2.2
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { private const string GitHubForUnityVersion = "1.2.2"; internal const string VersionForAssembly = GitHubForUnityVersion; // If this is an alpha, beta or other pre-release, mark it as such as shown below internal const string Version = GitHubForUnityVersion; // GitHubForUnityVersion + "-beta1" } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { private const string GitHubForUnityVersion = "1.2.1"; internal const string VersionForAssembly = GitHubForUnityVersion; // If this is an alpha, beta or other pre-release, mark it as such as shown below internal const string Version = GitHubForUnityVersion; // GitHubForUnityVersion + "-beta1" } }
mit
C#
de43e6af166eb4ef6855c0426dec5b72005b5c39
Update DataRegistry.cs
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2/DependencyResolution/DataRegistry.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2/DependencyResolution/DataRegistry.cs
using System; using SFA.DAS.CommitmentsV2.Data; using System.Data.Common; using Microsoft.Azure.Services.AppAuthentication; using Microsoft.Data.SqlClient; using StructureMap; using SFA.DAS.CommitmentsV2.Configuration; using SFA.DAS.Configuration; namespace SFA.DAS.CommitmentsV2.DependencyResolution { public class DataRegistry : Registry { private const string AzureResource = "https://database.windows.net/"; public DataRegistry() { var environmentName = Environment.GetEnvironmentVariable(EnvironmentVariableNames.EnvironmentName); For<DbConnection>().Use($"Build DbConnection", c => { var azureServiceTokenProvider = new AzureServiceTokenProvider(); return /*environmentName.Equals("LOCAL", StringComparison.CurrentCultureIgnoreCase) ? new SqlConnection(GetConnectionString(c)) : */ new SqlConnection { ConnectionString = GetConnectionString(c), AccessToken = azureServiceTokenProvider.GetAccessTokenAsync(AzureResource).Result }; }); For<ProviderCommitmentsDbContext>().Use(c => c.GetInstance<IDbContextFactory>().CreateDbContext()); For<IProviderCommitmentsDbContext>().Use(c => c.GetInstance<IDbContextFactory>().CreateDbContext()); } private string GetConnectionString(IContext context) { return context.GetInstance<CommitmentsV2Configuration>().DatabaseConnectionString; } } }
using System; using SFA.DAS.CommitmentsV2.Data; using System.Data.Common; using Microsoft.Azure.Services.AppAuthentication; using Microsoft.Data.SqlClient; using StructureMap; using SFA.DAS.CommitmentsV2.Configuration; using SFA.DAS.Configuration; namespace SFA.DAS.CommitmentsV2.DependencyResolution { public class DataRegistry : Registry { private const string AzureResource = "https://database.windows.net/"; public DataRegistry() { var environmentName = Environment.GetEnvironmentVariable(EnvironmentVariableNames.EnvironmentName); For<DbConnection>().Use($"Build DbConnection", c => { var azureServiceTokenProvider = new AzureServiceTokenProvider(); return environmentName.Equals("LOCAL", StringComparison.CurrentCultureIgnoreCase) ? new SqlConnection(GetConnectionString(c)) : new SqlConnection { ConnectionString = GetConnectionString(c), AccessToken = azureServiceTokenProvider.GetAccessTokenAsync(AzureResource).Result }; }); For<ProviderCommitmentsDbContext>().Use(c => c.GetInstance<IDbContextFactory>().CreateDbContext()); For<IProviderCommitmentsDbContext>().Use(c => c.GetInstance<IDbContextFactory>().CreateDbContext()); } private string GetConnectionString(IContext context) { return context.GetInstance<CommitmentsV2Configuration>().DatabaseConnectionString; } } }
mit
C#
0d2ab5648433f75cf4a34772e8bd1c02d9b247a7
optimize code
jiangzhhhh/slua,luzexi/slua-3rd,soulgame/slua,haolly/slua_source_note,shrimpz/slua,shrimpz/slua,Roland0511/slua,yaukeywang/slua,jiangzhhhh/slua,Roland0511/slua,jiangzhhhh/slua,pangweiwei/slua,soulgame/slua,Roland0511/slua,luzexi/slua-3rd-lib,haolly/slua_source_note,soulgame/slua,yaukeywang/slua,luzexi/slua-3rd-lib,luzexi/slua-3rd-lib,yaukeywang/slua,pangweiwei/slua,mr-kelly/slua,luzexi/slua-3rd,jiangzhhhh/slua,luzexi/slua-3rd,mr-kelly/slua,pangweiwei/slua,pangweiwei/slua,luzexi/slua-3rd-lib,soulgame/slua,yaukeywang/slua,jiangzhhhh/slua,yaukeywang/slua,luzexi/slua-3rd-lib,soulgame/slua,haolly/slua_source_note,luzexi/slua-3rd,soulgame/slua,mr-kelly/slua,Roland0511/slua,yaukeywang/slua,luzexi/slua-3rd,pangweiwei/slua,Roland0511/slua,mr-kelly/slua,jiangzhhhh/slua,mr-kelly/slua,haolly/slua_source_note,luzexi/slua-3rd,haolly/slua_source_note,Roland0511/slua,haolly/slua_source_note,luzexi/slua-3rd-lib,mr-kelly/slua
Assets/Plugins/Slua_Managed/Lua3rdDLL.cs
Assets/Plugins/Slua_Managed/Lua3rdDLL.cs
using System.Collections.Generic; using LuaInterface; using System; using System.Linq; using System.Reflection; namespace SLua{ public static class Lua3rdDLL{ static Dictionary<string, LuaCSFunction> DLLRegFuncs = new Dictionary<string, LuaCSFunction>(); static Lua3rdDLL(){ // LuaSocketDLL.Reg(DLLRegFuncs); } public static void open(IntPtr L){ // var now = System.DateTime.Now; Assembly assembly = null; foreach(var assem in AppDomain.CurrentDomain.GetAssemblies()){ if(assem.GetName().Name == "Assembly-CSharp"){ assembly = assem; } } if(assembly != null){ var csfunctions = assembly.GetExportedTypes() .SelectMany(x => x.GetMethods()) .Where(y => y.IsDefined(typeof(LualibRegAttribute),false)); foreach(MethodInfo func in csfunctions){ var attr = System.Attribute.GetCustomAttribute(func,typeof(LualibRegAttribute)) as LualibRegAttribute; var csfunc = Delegate.CreateDelegate(typeof(LuaCSFunction),func) as LuaCSFunction; DLLRegFuncs.Add(attr.luaName,csfunc); // UnityEngine.Debug.Log(attr.luaName); } } // UnityEngine.Debug.Log("find all methods marked by [Lua3rdRegAttribute] cost :"+(System.DateTime.Now - now).TotalSeconds); if(DLLRegFuncs.Count == 0){ return; } LuaDLL.lua_getglobal(L, "package"); LuaDLL.lua_getfield(L, -1, "preload"); foreach (KeyValuePair<string, LuaCSFunction> pair in DLLRegFuncs) { LuaDLL.lua_pushcfunction (L, pair.Value); LuaDLL.lua_setfield(L, -2, pair.Key); } LuaDLL.lua_settop(L, 0); } [AttributeUsage(AttributeTargets.Method)] public class LualibRegAttribute:System.Attribute{ public string luaName; public LualibRegAttribute(string luaName){ this.luaName = luaName; } } } }
using System.Collections.Generic; using LuaInterface; using System; using System.Linq; using System.Reflection; namespace SLua{ public static class Lua3rdDLL{ static Dictionary<string, LuaCSFunction> DLLRegFuncs = new Dictionary<string, LuaCSFunction>(); static Lua3rdDLL(){ // LuaSocketDLL.Reg(DLLRegFuncs); } public static void open(IntPtr L){ // var now = System.DateTime.Now; Assembly assembly = null; foreach(var assem in AppDomain.CurrentDomain.GetAssemblies()){ if(assem.GetName().Name == "Assembly-CSharp"){ assembly = assem; } } if(assembly != null){ var csfunctions = assembly.GetExportedTypes() .SelectMany(x => x.GetMethods()) .Where(y => y.GetCustomAttributes(typeof(LualibRegAttribute),false).Any()) .ToList(); foreach(MethodInfo func in csfunctions){ var attr = System.Attribute.GetCustomAttribute(func,typeof(LualibRegAttribute)) as LualibRegAttribute; var csfunc = Delegate.CreateDelegate(typeof(LuaCSFunction),func) as LuaCSFunction; DLLRegFuncs.Add(attr.luaName,csfunc); // UnityEngine.Debug.Log(attr.luaName); } } // UnityEngine.Debug.Log("find all methods marked by [Lua3rdRegAttribute] cost :"+(System.DateTime.Now - now).TotalSeconds); if(DLLRegFuncs.Count == 0){ return; } LuaDLL.lua_getglobal(L, "package"); LuaDLL.lua_getfield(L, -1, "preload"); foreach (KeyValuePair<string, LuaCSFunction> pair in DLLRegFuncs) { LuaDLL.lua_pushcfunction (L, pair.Value); LuaDLL.lua_setfield(L, -2, pair.Key); } LuaDLL.lua_settop(L, 0); } [AttributeUsage(AttributeTargets.Method)] public class LualibRegAttribute:System.Attribute{ public string luaName; public LualibRegAttribute(string luaName){ this.luaName = luaName; } } } }
mit
C#
e7eb41c2e1e3c74dd2f4dd9a3767b16f1a080a9a
Disable sockets perf tests on OSX
parjong/corefx,JosephTremoulet/corefx,stephenmichaelf/corefx,nbarbettini/corefx,tijoytom/corefx,marksmeltzer/corefx,rjxby/corefx,tijoytom/corefx,mazong1123/corefx,BrennanConroy/corefx,MaggieTsang/corefx,rahku/corefx,gkhanna79/corefx,YoupHulsebos/corefx,the-dwyer/corefx,elijah6/corefx,krk/corefx,jlin177/corefx,JosephTremoulet/corefx,marksmeltzer/corefx,zhenlan/corefx,DnlHarvey/corefx,ptoonen/corefx,dotnet-bot/corefx,krytarowski/corefx,billwert/corefx,ptoonen/corefx,JosephTremoulet/corefx,gkhanna79/corefx,mmitche/corefx,stone-li/corefx,dotnet-bot/corefx,stone-li/corefx,Ermiar/corefx,rjxby/corefx,gkhanna79/corefx,stone-li/corefx,dhoehna/corefx,JosephTremoulet/corefx,krk/corefx,alexperovich/corefx,DnlHarvey/corefx,elijah6/corefx,marksmeltzer/corefx,axelheer/corefx,Jiayili1/corefx,mazong1123/corefx,Jiayili1/corefx,cydhaselton/corefx,dotnet-bot/corefx,nchikanov/corefx,DnlHarvey/corefx,Petermarcu/corefx,seanshpark/corefx,mmitche/corefx,seanshpark/corefx,cydhaselton/corefx,ericstj/corefx,dhoehna/corefx,rjxby/corefx,tijoytom/corefx,alexperovich/corefx,zhenlan/corefx,DnlHarvey/corefx,yizhang82/corefx,nbarbettini/corefx,Ermiar/corefx,rahku/corefx,ViktorHofer/corefx,shimingsg/corefx,axelheer/corefx,dotnet-bot/corefx,lggomez/corefx,Petermarcu/corefx,wtgodbe/corefx,the-dwyer/corefx,gkhanna79/corefx,krytarowski/corefx,rahku/corefx,MaggieTsang/corefx,rjxby/corefx,krytarowski/corefx,billwert/corefx,weltkante/corefx,Petermarcu/corefx,stephenmichaelf/corefx,wtgodbe/corefx,weltkante/corefx,krk/corefx,marksmeltzer/corefx,elijah6/corefx,JosephTremoulet/corefx,richlander/corefx,jlin177/corefx,dotnet-bot/corefx,alexperovich/corefx,tijoytom/corefx,twsouthwick/corefx,dhoehna/corefx,MaggieTsang/corefx,stephenmichaelf/corefx,krk/corefx,richlander/corefx,weltkante/corefx,ViktorHofer/corefx,elijah6/corefx,twsouthwick/corefx,zhenlan/corefx,axelheer/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,yizhang82/corefx,richlander/corefx,krytarowski/corefx,ptoonen/corefx,zhenlan/corefx,yizhang82/corefx,stephenmichaelf/corefx,ptoonen/corefx,the-dwyer/corefx,elijah6/corefx,wtgodbe/corefx,dhoehna/corefx,MaggieTsang/corefx,seanshpark/corefx,ViktorHofer/corefx,weltkante/corefx,marksmeltzer/corefx,ericstj/corefx,richlander/corefx,tijoytom/corefx,gkhanna79/corefx,MaggieTsang/corefx,ViktorHofer/corefx,nbarbettini/corefx,rjxby/corefx,axelheer/corefx,YoupHulsebos/corefx,cydhaselton/corefx,wtgodbe/corefx,elijah6/corefx,richlander/corefx,ericstj/corefx,ravimeda/corefx,stephenmichaelf/corefx,Jiayili1/corefx,billwert/corefx,ericstj/corefx,weltkante/corefx,wtgodbe/corefx,ravimeda/corefx,gkhanna79/corefx,nchikanov/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,nbarbettini/corefx,fgreinacher/corefx,MaggieTsang/corefx,YoupHulsebos/corefx,yizhang82/corefx,jlin177/corefx,twsouthwick/corefx,ptoonen/corefx,krk/corefx,Jiayili1/corefx,shimingsg/corefx,rubo/corefx,richlander/corefx,shimingsg/corefx,Ermiar/corefx,parjong/corefx,billwert/corefx,mmitche/corefx,cydhaselton/corefx,parjong/corefx,stone-li/corefx,axelheer/corefx,stone-li/corefx,fgreinacher/corefx,lggomez/corefx,twsouthwick/corefx,the-dwyer/corefx,billwert/corefx,wtgodbe/corefx,ericstj/corefx,Petermarcu/corefx,Ermiar/corefx,BrennanConroy/corefx,rahku/corefx,tijoytom/corefx,weltkante/corefx,the-dwyer/corefx,stephenmichaelf/corefx,mmitche/corefx,parjong/corefx,rahku/corefx,ptoonen/corefx,gkhanna79/corefx,zhenlan/corefx,yizhang82/corefx,parjong/corefx,billwert/corefx,nchikanov/corefx,ptoonen/corefx,ericstj/corefx,cydhaselton/corefx,billwert/corefx,mazong1123/corefx,rahku/corefx,lggomez/corefx,alexperovich/corefx,dhoehna/corefx,nchikanov/corefx,seanshpark/corefx,tijoytom/corefx,DnlHarvey/corefx,twsouthwick/corefx,parjong/corefx,ravimeda/corefx,mmitche/corefx,ravimeda/corefx,rubo/corefx,shimingsg/corefx,stone-li/corefx,krytarowski/corefx,Jiayili1/corefx,ravimeda/corefx,mazong1123/corefx,nbarbettini/corefx,alexperovich/corefx,mmitche/corefx,cydhaselton/corefx,dotnet-bot/corefx,richlander/corefx,fgreinacher/corefx,jlin177/corefx,shimingsg/corefx,Petermarcu/corefx,marksmeltzer/corefx,seanshpark/corefx,alexperovich/corefx,nbarbettini/corefx,lggomez/corefx,ravimeda/corefx,zhenlan/corefx,dhoehna/corefx,rubo/corefx,dhoehna/corefx,rahku/corefx,twsouthwick/corefx,ViktorHofer/corefx,Ermiar/corefx,krytarowski/corefx,rubo/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,zhenlan/corefx,weltkante/corefx,nchikanov/corefx,jlin177/corefx,stone-li/corefx,twsouthwick/corefx,jlin177/corefx,lggomez/corefx,nbarbettini/corefx,rubo/corefx,Ermiar/corefx,krk/corefx,mazong1123/corefx,elijah6/corefx,MaggieTsang/corefx,parjong/corefx,rjxby/corefx,alexperovich/corefx,Ermiar/corefx,ravimeda/corefx,mazong1123/corefx,ericstj/corefx,rjxby/corefx,lggomez/corefx,mazong1123/corefx,ViktorHofer/corefx,Jiayili1/corefx,nchikanov/corefx,dotnet-bot/corefx,axelheer/corefx,Petermarcu/corefx,seanshpark/corefx,Petermarcu/corefx,the-dwyer/corefx,marksmeltzer/corefx,Jiayili1/corefx,krk/corefx,yizhang82/corefx,shimingsg/corefx,fgreinacher/corefx,wtgodbe/corefx,krytarowski/corefx,mmitche/corefx,YoupHulsebos/corefx,nchikanov/corefx,YoupHulsebos/corefx,BrennanConroy/corefx,the-dwyer/corefx,JosephTremoulet/corefx,jlin177/corefx,lggomez/corefx,seanshpark/corefx,cydhaselton/corefx,yizhang82/corefx,shimingsg/corefx,YoupHulsebos/corefx
src/System.Net.Sockets/tests/PerformanceTests/SocketPerformanceAsyncTests.cs
src/System.Net.Sockets/tests/PerformanceTests/SocketPerformanceAsyncTests.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.Net.Sockets.Tests; using System.Net.Test.Common; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Performance.Tests { [Trait("Perf", "true")] public class SocketPerformanceAsyncTests { private readonly ITestOutputHelper _log; public SocketPerformanceAsyncTests(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } [ActiveIssue(13349, TestPlatforms.OSX)] [OuterLoop] [Fact] public void SocketPerformance_SingleSocketClientAsync_LocalHostServerAsync() { SocketImplementationType serverType = SocketImplementationType.Async; SocketImplementationType clientType = SocketImplementationType.Async; int iterations = 10000; int bufferSize = 256; int socket_instances = 1; var test = new SocketPerformanceTests(_log); // Run in Stress mode no expected time to complete. test.ClientServerTest( serverType, clientType, iterations, bufferSize, socket_instances); } [ActiveIssue(13349, TestPlatforms.OSX)] [OuterLoop] [Fact] public void SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync() { SocketImplementationType serverType = SocketImplementationType.Async; SocketImplementationType clientType = SocketImplementationType.Async; int iterations = 2000; int bufferSize = 256; int socket_instances = 500; var test = new SocketPerformanceTests(_log); // Run in Stress mode no expected time to complete. test.ClientServerTest( serverType, clientType, iterations, bufferSize, socket_instances); } } }
// 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.Net.Sockets.Tests; using System.Net.Test.Common; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Performance.Tests { [Trait("Perf", "true")] public class SocketPerformanceAsyncTests { private readonly ITestOutputHelper _log; public SocketPerformanceAsyncTests(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } [OuterLoop] [Fact] public void SocketPerformance_SingleSocketClientAsync_LocalHostServerAsync() { SocketImplementationType serverType = SocketImplementationType.Async; SocketImplementationType clientType = SocketImplementationType.Async; int iterations = 10000; int bufferSize = 256; int socket_instances = 1; var test = new SocketPerformanceTests(_log); // Run in Stress mode no expected time to complete. test.ClientServerTest( serverType, clientType, iterations, bufferSize, socket_instances); } [OuterLoop] [Fact] public void SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync() { SocketImplementationType serverType = SocketImplementationType.Async; SocketImplementationType clientType = SocketImplementationType.Async; int iterations = 2000; int bufferSize = 256; int socket_instances = 500; var test = new SocketPerformanceTests(_log); // Run in Stress mode no expected time to complete. test.ClientServerTest( serverType, clientType, iterations, bufferSize, socket_instances); } } }
mit
C#
2709b6ff4ce2e58a4b037a127e317e8136cd4b96
Fix WeightedRoundRobin not updated when MemberStatus has changed.
tomliversidge/protoactor-dotnet,AsynkronIT/protoactor-dotnet,masteryee/protoactor-dotnet,masteryee/protoactor-dotnet,tomliversidge/protoactor-dotnet
src/MemberStrategies/WeightedMemberStrategy/WeightedMemberStrategy.cs
src/MemberStrategies/WeightedMemberStrategy/WeightedMemberStrategy.cs
// ----------------------------------------------------------------------- // <copyright file="WeightedMemberStrategy.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System.Collections.Generic; namespace Proto.Cluster.WeightedMemberStrategy { public class WeightedMemberStrategy : IMemberStrategy { private List<MemberStatus> _members; private Rendezvous _rdv; private WeightedRoundRobin _wrr; public WeightedMemberStrategy() { _members = new List<MemberStatus>(); _rdv = new Rendezvous(this); _wrr = new WeightedRoundRobin(this); } public List<MemberStatus> GetAllMembers() => _members; public void AddMember(MemberStatus member) { _members.Add(member); _wrr.UpdateRR(); _rdv.UpdateRdv(); } public void UpdateMember(MemberStatus member) { for (int i = 0; i < _members.Count; i++) { if (_members[i].Address == member.Address) { _members[i] = member; _wrr.UpdateRR(); return; } } } public void RemoveMember(MemberStatus member) { for (int i = 0; i < _members.Count; i++) { if (_members[i].Address == member.Address) { _members.RemoveAt(i); _wrr.UpdateRR(); _rdv.UpdateRdv(); return; } } } public string GetPartition(string key) => _rdv.GetNode(key); public string GetActivator() => _wrr.GetNode(); } }
// ----------------------------------------------------------------------- // <copyright file="WeightedMemberStrategy.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System.Collections.Generic; namespace Proto.Cluster.WeightedMemberStrategy { public class WeightedMemberStrategy : IMemberStrategy { private List<MemberStatus> _members; private Rendezvous _rdv; private WeightedRoundRobin _wrr; public WeightedMemberStrategy() { _members = new List<MemberStatus>(); _rdv = new Rendezvous(this); _wrr = new WeightedRoundRobin(this); } public List<MemberStatus> GetAllMembers() => _members; public void AddMember(MemberStatus member) { _members.Add(member); _wrr.UpdateRR(); _rdv.UpdateRdv(); } public void UpdateMember(MemberStatus member) { for (int i = 0; i < _members.Count; i++) { if (_members[i].Address == member.Address) { _members[i] = member; return; } } } public void RemoveMember(MemberStatus member) { for (int i = 0; i < _members.Count; i++) { if (_members[i].Address == member.Address) { _members.RemoveAt(i); _wrr.UpdateRR(); _rdv.UpdateRdv(); return; } } } public string GetPartition(string key) => _rdv.GetNode(key); public string GetActivator() => _wrr.GetNode(); } }
apache-2.0
C#
d02e2a9c9b69a868f6b4c4fc499f760abfde0a40
Fix saving filter rules
sboulema/CodeNav,sboulema/CodeNav
CodeNav.Shared/Helpers/SettingsHelper.cs
CodeNav.Shared/Helpers/SettingsHelper.cs
using CodeNav.Models; using Newtonsoft.Json; using System; using System.Collections.ObjectModel; namespace CodeNav.Helpers { public static class SettingsHelper { private static bool? _useXmlComments; public static bool UseXMLComments { get { if (_useXmlComments == null) { _useXmlComments = General.Instance.UseXMLComments; } return _useXmlComments.Value; } set => _useXmlComments = value; } private static ObservableCollection<FilterRule> _filterRules; public static ObservableCollection<FilterRule> FilterRules { get => LoadFilterRules(); set => _filterRules = value; } public static void SaveFilterRules(ObservableCollection<FilterRule> filterRules) { General.Instance.FilterRules = JsonConvert.SerializeObject(filterRules); General.Instance.Save(); } public static void Refresh() { _useXmlComments = null; _filterRules = null; } private static ObservableCollection<FilterRule> LoadFilterRules() { if (_filterRules != null) { return _filterRules; } try { _filterRules = JsonConvert.DeserializeObject<ObservableCollection<FilterRule>>(General.Instance.FilterRules); } catch (Exception) { // Ignore error while loading filter rules _filterRules = new ObservableCollection<FilterRule>(); } return _filterRules; } } }
using CodeNav.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace CodeNav.Helpers { public static class SettingsHelper { private static bool? _useXmlComments; public static bool UseXMLComments { get { if (_useXmlComments == null) { _useXmlComments = General.Instance.UseXMLComments; } return _useXmlComments.Value; } set => _useXmlComments = value; } private static ObservableCollection<FilterRule> _filterRules; public static ObservableCollection<FilterRule> FilterRules { get => LoadFilterRules(); set => _filterRules = value; } public static void SaveFilterRules(ObservableCollection<FilterRule> filterRules) { General.Instance.FilterRules = JsonConvert.SerializeObject(filterRules); General.Instance.Save(); } public static void Refresh() { _useXmlComments = null; _filterRules = null; } private static ObservableCollection<FilterRule> LoadFilterRules() { if (_filterRules != null) { return _filterRules; } try { _filterRules = JsonConvert.DeserializeObject<ObservableCollection<FilterRule>>(General.Instance.FilterRules); } catch (Exception) { // Ignore error while loading filter rules } finally { _filterRules = new ObservableCollection<FilterRule>(); } return _filterRules; } } }
mit
C#
42d4892f5d836e11079688291f5446f7b5057b53
Update iOSLinearAccelerationProbe.cs
predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus
Sensus.iOS.Shared/Probes/Movement/iOSLinearAccelerationProbe.cs
Sensus.iOS.Shared/Probes/Movement/iOSLinearAccelerationProbe.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using CoreMotion; using Foundation; using Plugin.Permissions.Abstractions; using Sensus.Probes.Movement; namespace Sensus.iOS.Probes.Movement { class iOSLinearAccelerationProbe : LinearAccelerationProbe { private CMMotionManager _motionManager; protected override async Task InitializeAsync() { await base.InitializeAsync(); if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Sensors) == PermissionStatus.Granted) { _motionManager = new CMMotionManager(); } else { // throw standard exception instead of NotSupportedException, since the user might decide to enable sensors in the future // and we'd like the probe to be restarted at that time. string error = "This device does not contain a linear accelerometer, or the user has denied access to it. Cannot start accelerometer probe."; await SensusServiceHelper.Get().FlashNotificationAsync(error); throw new Exception(error); } } protected override async Task StartListeningAsync() { await base.StartListeningAsync(); _motionManager?.StartDeviceMotionUpdates(new NSOperationQueue(), async (data, error) => { if (data != null && error == null) { await StoreDatumAsync(new LinearAccelerationDatum(DateTimeOffset.UtcNow, data.UserAcceleration.X, data.UserAcceleration.Y, data.UserAcceleration.Z)); } }); } protected override async Task StopListeningAsync() { await base.StopListeningAsync(); _motionManager?.StopDeviceMotionUpdates(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using CoreMotion; using Foundation; using Plugin.Permissions.Abstractions; using Sensus.Probes.Movement; namespace Sensus.iOS.Probes.Movement { class iOSLinearAccelerationProbe : LinearAccelerationProbe { private CMMotionManager _motionManager; protected override async Task InitializeAsync() { await base.InitializeAsync(); if (await SensusServiceHelper.Get().ObtainPermissionAsync(Permission.Sensors) == PermissionStatus.Granted) { _motionManager = new CMMotionManager(); } else { // throw standard exception instead of NotSupportedException, since the user might decide to enable sensors in the future // and we'd like the probe to be restarted at that time. string error = "This device does not contain a linear accelerometer, or the user has denied access to it. Cannot start accelerometer probe."; await SensusServiceHelper.Get().FlashNotificationAsync(error); throw new Exception(error); } } protected override async Task StartListeningAsync() { await base.StartListeningAsync(); _motionManager?.StartDeviceMotionUpdates(new NSOperationQueue(), async (data, error) => { if (data != null && error == null) { await StoreDatumAsync(new AccelerometerDatum(DateTimeOffset.UtcNow, data.UserAcceleration.X, data.UserAcceleration.Y, data.UserAcceleration.Z)); } }); } protected override async Task StopListeningAsync() { await base.StopListeningAsync(); _motionManager?.StopDeviceMotionUpdates(); } } }
apache-2.0
C#
7e18ac9c05ebc63de15a6e5dbc3692e1ca5568a6
add two more ex to excluded by default
PFalkowski/ErrorHandling
ErrorHandling/ExceptionHandlingFilter.cs
ErrorHandling/ExceptionHandlingFilter.cs
using System; using System.Collections.Generic; using System.Threading; namespace ErrorHandling { public class ExceptionHandlingFilter : IExceptionHandlingPolicy { private readonly IExceptionHandlingPolicy _wrappedPolicy; /// <summary> /// Add your unhandlable / filtered out exception types to this HashSet /// </summary> public readonly HashSet<Type> ExcludedExceptios = new HashSet<Type> { typeof (OutOfMemoryException), typeof(StackOverflowException), typeof(ThreadAbortException), typeof (InsufficientExecutionStackException) }; public ExceptionHandlingFilter(IExceptionHandlingPolicy wrappedPolicy) { _wrappedPolicy = wrappedPolicy; } public void HandleException(Exception ex) { if (CanBeHandled(ex)) { _wrappedPolicy.HandleException(ex); } else { throw new ExceptionCannotBeHandledException(ex); // preserve original exception's stack trace } } public bool CanBeHandled(Exception ex) { return !CanNotBeHandled(ex); } public bool CanNotBeHandled(Exception ex) { return ExcludedExceptios.Contains(ex.GetType()); } } }
using System; using System.Collections.Generic; namespace ErrorHandling { public class ExceptionHandlingFilter : IExceptionHandlingPolicy { private readonly IExceptionHandlingPolicy _wrappedPolicy; /// <summary> /// Add your unhandlable / filtered out exception types to this HashSet /// </summary> public readonly HashSet<Type> ExcludedExceptios = new HashSet<Type> { typeof (OutOfMemoryException), typeof (InsufficientExecutionStackException) }; public ExceptionHandlingFilter(IExceptionHandlingPolicy wrappedPolicy) { _wrappedPolicy = wrappedPolicy; } public void HandleException(Exception ex) { if (CanBeHandled(ex)) { _wrappedPolicy.HandleException(ex); } else { throw new ExceptionCannotBeHandledException(ex); // preserve original exception's stack trace } } public bool CanBeHandled(Exception ex) { return !CanNotBeHandled(ex); } public bool CanNotBeHandled(Exception ex) { return ExcludedExceptios.Contains(ex.GetType()); } } }
mit
C#
c9593d485a11e9d0d1e4b5db284ddfdb8da6938a
Update version to 5.0.0
Phrynohyas/eve-o-preview,Phrynohyas/eve-o-preview
Eve-O-Preview/Properties/AssemblyInfo.cs
Eve-O-Preview/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("EVE-O Preview")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EVE-O Preview")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")] [assembly: AssemblyVersion("5.0.0.0")] [assembly: AssemblyFileVersion("5.0.0.0")] [assembly: CLSCompliant(false)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("EVE-O Preview")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EVE-O Preview")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("04f08f8d-9e98-423b-acdb-4effb31c0d35")] [assembly: AssemblyVersion("4.1.0.6")] [assembly: AssemblyFileVersion("4.1.0.6")] [assembly: CLSCompliant(false)]
mit
C#
739a72195ebb68868f4c53099593701513e2d9c0
Update Dispatcher documentation
Vtek/Bartender
src/Bartender/Dispatcher.cs
src/Bartender/Dispatcher.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bartender { /// <summary> /// Dispatcher. /// </summary> public class Dispatcher : IQueryDispatcher, IAsyncQueryDispatcher { /// <summary> /// Dependency container. /// </summary> public IDependencyContainer Container { get; } /// <summary> /// Initializes a new instance of the Dispatcher class. /// </summary> /// <param name="container">Dependency container.</param> public Dispatcher(IDependencyContainer container) { Container = container; } /// <summary> /// Dispatch the specified query. /// </summary> /// <param name="query">Query.</param> /// <returns>ReadModel</returns> TReadModel IQueryDispatcher.Dispatch<TQuery, TReadModel>(TQuery query) => GetHandler<IQueryHandler<TQuery, TReadModel>>() .Single() .Handle(query); /// <summary> /// Dispatch a query asynchronously. /// </summary> /// <param name="query">Query to dispatch</param> /// <returns>ReadModel</returns> async Task<TReadModel> IAsyncQueryDispatcher.DispatchAsync<TQuery, TReadModel>(TQuery query) => await GetHandler<IAsyncQueryHandler<TQuery, TReadModel>>() .Single() .HandleAsync(query); /// <summary> /// Get handler /// </summary> /// <returns>Enumerable of handlers</returns> IEnumerable<THandler> GetHandler<THandler>() { var handlers = Container.GetAllInstances<THandler>(); var messageType = typeof(THandler).GenericTypeArguments.First().FullName; if(!handlers.Any()) throw new DispatcherException($"No handler for '{messageType}'."); if(handlers.Count() > 1) throw new DispatcherException($"Multiple handler for '{messageType}'."); return handlers; } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bartender { /// <summary> /// Dispatcher. /// </summary> public class Dispatcher : IQueryDispatcher, IAsyncQueryDispatcher { /// <summary> /// Dependency container. /// </summary> public IDependencyContainer Container { get; } /// <summary> /// Initializes a new instance of the Dispatcher class. /// </summary> /// <param name="container">Dependency container.</param> public Dispatcher(IDependencyContainer container) { Container = container; } /// <summary> /// Dispatch the specified query. /// </summary> /// <param name="query">Query.</param> /// <returns>ReadModel</returns> TReadModel IQueryDispatcher.Dispatch<TQuery, TReadModel>(TQuery query) => GetHandler<IQueryHandler<TQuery, TReadModel>>() .Single() .Handle(query); /// <summary> /// Dispatch a query asynchronously. /// </summary> /// <param name="query">Query to dispatch</param> async Task<TReadModel> IAsyncQueryDispatcher.DispatchAsync<TQuery, TReadModel>(TQuery query) => await GetHandler<IAsyncQueryHandler<TQuery, TReadModel>>() .Single() .HandleAsync(query); IEnumerable<THandler> GetHandler<THandler>() { var handlers = Container.GetAllInstances<THandler>(); var messageType = typeof(THandler).GenericTypeArguments[0].FullName; if(!handlers.Any()) throw new DispatcherException($"No handler for '{messageType}'."); if(handlers.Count() > 1) throw new DispatcherException($"Multiple handler for '{messageType}'."); return handlers; } } }
mit
C#
87bf5c575990c0a9515d931e9699b686cd01ae53
Fix insights id.
bordoley/FacebookPagesApp
FacebookPagesApp/FacebookPagesApplication.cs
FacebookPagesApp/FacebookPagesApplication.cs
using System; using System.Collections.Generic; using System.IO; using System.Reactive.Disposables; using System.Reactive.Linq; using RxApp; using Android.App; using Android.Runtime; using Microsoft.FSharp.Core; using Xamarin; namespace FacebookPagesApp { [Application] public sealed class FacebookPagesApplication : RxApplication { public const string XAMARIN_INSIGHTS_KEY = "483137a8b42bc65cd39f3b649599093a6e09ce46"; public FacebookPagesApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public override Type GetActivityType(object model) { if (model is ILoginViewModel ) { return typeof(LoginActivity); } else if (model is IUnknownStateViewModel) { return typeof(UnknownStateActivity); } else if (model is IPagesViewModel ) { return typeof(PagesActivity); } else if (model is INewPostViewModel ) { return typeof(NewPostActivity); } throw new Exception("No view for view model"); } public override IApplication ProvideApplication() { return new FacebookPagesApplicationController( this.NavigationStack, FacebookSession.observe(this.ApplicationContext), FacebookSession.getManagerWithFunc(() => LoginActivity.Current)); } public override void OnCreate() { base.OnCreate(); Insights.Initialize(XAMARIN_INSIGHTS_KEY, this.ApplicationContext); } } }
using System; using System.Collections.Generic; using System.IO; using System.Reactive.Disposables; using System.Reactive.Linq; using RxApp; using Android.App; using Android.Runtime; using Microsoft.FSharp.Core; using Xamarin; namespace FacebookPagesApp { [Application] public sealed class FacebookPagesApplication : RxApplication { public const string XAMARIN_INSIGHTS_KEY = "483137a8b42bc65cd39f3b649599093a6e09ce46483137a8b42bc65cd39f3b649599093a6e09ce46"; public FacebookPagesApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public override Type GetActivityType(object model) { if (model is ILoginViewModel ) { return typeof(LoginActivity); } else if (model is IUnknownStateViewModel) { return typeof(UnknownStateActivity); } else if (model is IPagesViewModel ) { return typeof(PagesActivity); } else if (model is INewPostViewModel ) { return typeof(NewPostActivity); } throw new Exception("No view for view model"); } public override IApplication ProvideApplication() { return new FacebookPagesApplicationController( this.NavigationStack, FacebookSession.observe(this.ApplicationContext), FacebookSession.getManagerWithFunc(() => LoginActivity.Current)); } public override void OnCreate() { base.OnCreate(); Insights.Initialize(XAMARIN_INSIGHTS_KEY, this.ApplicationContext); } } }
mit
C#
07e9faa9d55f658cfc8a333f31f0cd37920eaaec
Fix BlockHelper for speed and concurrency
chraft/c-raft
Chraft/World/Blocks/BlockHelper.cs
Chraft/World/Blocks/BlockHelper.cs
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Chraft.World.Blocks.Interfaces; namespace Chraft.World.Blocks { public static class BlockHelper { private static ConcurrentDictionary<byte, byte> _growableBlocks; private static ConcurrentDictionary<byte, BlockBase> _blocks; static BlockHelper() { Init(); } private static void Init() { _blocks = new ConcurrentDictionary<byte, BlockBase>(); _growableBlocks = new ConcurrentDictionary<byte, byte>(); BlockBase block; foreach (Type t in from t in Assembly.GetExecutingAssembly().GetTypes() where t.GetInterfaces().Contains(typeof(IBlockBase)) && !t.IsAbstract select t) { block = (BlockBase) t.GetConstructor(Type.EmptyTypes).Invoke(null); _blocks.TryAdd((byte)block.Type, block); if (block is IBlockGrowable) _growableBlocks.TryAdd((byte)block.Type, (byte)block.Type); } } public static BlockBase Instance(byte blockId) { BlockBase block = null; if (_blocks.ContainsKey(blockId)) return _blocks[blockId]; return block; } public static bool IsGrowable(byte blockId) { return _growableBlocks.ContainsKey(blockId); } public static bool IsGrowable(BlockData.Blocks blockType) { return _growableBlocks.ContainsKey((byte)blockType); ; } } }
#region C#raft License // This file is part of C#raft. Copyright C#raft Team // // C#raft is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using Chraft.World.Blocks.Interfaces; namespace Chraft.World.Blocks { public static class BlockHelper { private static List<byte> _growableBlocks; private static Dictionary<byte, BlockBase> _blocks; static BlockHelper() { Init(); } private static void Init() { _blocks = new Dictionary<byte, BlockBase>(); _growableBlocks = new List<byte>(); BlockBase block; foreach (Type t in from t in Assembly.GetExecutingAssembly().GetTypes() where t.GetInterfaces().Contains(typeof(IBlockBase)) && !t.IsAbstract select t) { block = (BlockBase) t.GetConstructor(Type.EmptyTypes).Invoke(null); _blocks.Add((byte)block.Type, block); if (block is IBlockGrowable) _growableBlocks.Add((byte)block.Type); } } public static BlockBase Instance(byte blockId) { BlockBase block = null; if (_blocks.ContainsKey(blockId)) return _blocks[blockId]; return block; } public static bool IsGrowable(byte blockId) { return _growableBlocks.Contains(blockId); } public static bool IsGrowable(BlockData.Blocks blockType) { return _growableBlocks.Contains((byte)blockType); } } }
agpl-3.0
C#
fb74e096feacb78a1964deb6a0dcb67910f669e3
Add BlobStream.CreateStream() method
modulexcite/dnlib,kiootic/dnlib,ilkerhalil/dnlib,picrap/dnlib,ZixiangBoy/dnlib,jorik041/dnlib,Arthur2e5/dnlib,0xd4d/dnlib,yck1509/dnlib
src/DotNet/MD/BlobStream.cs
src/DotNet/MD/BlobStream.cs
using dot10.IO; namespace dot10.DotNet.MD { /// <summary> /// Represents the #Blob stream /// </summary> public class BlobStream : DotNetStream { static readonly byte[] noData = new byte[0]; /// <inheritdoc/> public BlobStream() { } /// <inheritdoc/> public BlobStream(IImageStream imageStream, StreamHeader streamHeader) : base(imageStream, streamHeader) { } /// <summary> /// Reads data /// </summary> /// <param name="offset">Offset of data</param> /// <returns>The data or <c>null</c> if invalid offset</returns> public byte[] Read(uint offset) { // The CLR has a special check for offset 0. It always interprets it as // 0-length data, even if that first byte isn't 0 at all. if (offset == 0) return noData; int compressedLen; int size = GetSize(offset, out compressedLen); if (size < 0) return null; return imageStream.ReadBytes(size); } /// <summary> /// Reads data just like <see cref="Read"/>, but returns an empty array if /// offset is invalid /// </summary> /// <param name="offset">Offset of data</param> /// <returns>The data</returns> public byte[] ReadNoNull(uint offset) { return Read(offset) ?? noData; } /// <summary> /// Creates a new sub stream of the #Blob stream that can access one blob /// </summary> /// <param name="offset">Offset of blob</param> /// <returns>A new stream</returns> public IImageStream CreateStream(uint offset) { int compressedLen; int size = GetSize(offset, out compressedLen); if (size < 0) return MemoryImageStream.CreateEmpty(); return imageStream.Create((FileOffset)((long)offset + compressedLen), size); } int GetSize(uint offset, out int compressedLen) { compressedLen = -1; if (!IsValidOffset(offset)) return -1; imageStream.Position = offset; uint length; if (!imageStream.ReadCompressedUInt32(out length)) return -1; if (imageStream.Position + length < length || imageStream.Position + length > imageStream.Length) return -1; compressedLen = (int)(imageStream.Position - offset); return (int)length; // length <= 0x1FFFFFFF so this cast does not make it negative } } }
using dot10.IO; namespace dot10.DotNet.MD { /// <summary> /// Represents the #Blob stream /// </summary> public class BlobStream : DotNetStream { static readonly byte[] noData = new byte[0]; /// <inheritdoc/> public BlobStream() { } /// <inheritdoc/> public BlobStream(IImageStream imageStream, StreamHeader streamHeader) : base(imageStream, streamHeader) { } /// <summary> /// Reads data /// </summary> /// <param name="offset">Offset of data</param> /// <returns>The data or <c>null</c> if invalid offset</returns> public byte[] Read(uint offset) { // The CLR has a special check for offset 0. It always interprets it as // 0-length data, even if that first byte isn't 0 at all. if (offset == 0) return noData; if (!IsValidOffset(offset)) return null; imageStream.Position = offset; uint length; if (!imageStream.ReadCompressedUInt32(out length)) return null; if (imageStream.Position + length < length || imageStream.Position + length > imageStream.Length) return null; return imageStream.ReadBytes((int)length); // length <= 0x1FFFFFFF so this cast does not make it negative } /// <summary> /// Reads data just like <see cref="Read"/>, but returns an empty array if /// offset is invalid /// </summary> /// <param name="offset">Offset of data</param> /// <returns>The data</returns> public byte[] ReadNoNull(uint offset) { return Read(offset) ?? noData; } } }
mit
C#
bee730200792b96d9d95e340779d340fbfdd600e
Update `PcscExcetpion` class. Assign the value of `Error` in constructor. Remove unused constructors.
Archie-Yang/PcscDotNet
src/PcscDotNet/PcscException.cs
src/PcscDotNet/PcscException.cs
using System; using System.ComponentModel; namespace PcscDotNet { public delegate void PcscExceptionHandler(PcscException error); public sealed class PcscException : Win32Exception { public SCardError Error { get; private set; } public bool ThrowIt { get; set; } = true; public PcscException(SCardError error) : base((int)error) { Error = error; } } }
using System; using System.ComponentModel; namespace PcscDotNet { public delegate void PcscExceptionHandler(PcscException error); public sealed class PcscException : Win32Exception { public SCardError Error => (SCardError)NativeErrorCode; public bool ThrowIt { get; set; } = true; public PcscException(int error) : base(error) { } public PcscException(SCardError error) : base((int)error) { } public PcscException(string message) : base(message) { } public PcscException(int error, string message) : base(error, message) { } public PcscException(string message, Exception innerException) : base(message, innerException) { } } }
mit
C#
dbffac2877efec923ede0512da1e4a696e81c011
Replace literals in order of key length, e.g. most-specific first.
brendanjbaker/StraightSQL
src/StraightSql/CommandPreparer.cs
src/StraightSql/CommandPreparer.cs
namespace StraightSql { using Npgsql; using System; using System.Linq; public class CommandPreparer : ICommandPreparer { public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query) { if (npgsqlCommand == null) throw new ArgumentNullException(nameof(npgsqlCommand)); if (query == null) throw new ArgumentNullException(nameof(query)); var queryText = query.Text; foreach (var literal in query.Literals.OrderByDescending(l => l.Key.Length)) { var moniker = $":{literal.Key}"; if (!queryText.Contains(moniker)) throw new LiteralNotFoundException(literal.Key); queryText = queryText.Replace(moniker, literal.Value); } npgsqlCommand.CommandText = queryText; foreach (var queryParameter in query.Parameters) { npgsqlCommand.Parameters.Add(queryParameter); } } } }
namespace StraightSql { using Npgsql; using System; public class CommandPreparer : ICommandPreparer { public void Prepare(NpgsqlCommand npgsqlCommand, IQuery query) { if (npgsqlCommand == null) throw new ArgumentNullException(nameof(npgsqlCommand)); if (query == null) throw new ArgumentNullException(nameof(query)); var queryText = query.Text; foreach (var literal in query.Literals) { var moniker = $":{literal.Key}"; if (!queryText.Contains(moniker)) throw new LiteralNotFoundException(literal.Key); queryText = queryText.Replace(moniker, literal.Value); } npgsqlCommand.CommandText = queryText; foreach (var queryParameter in query.Parameters) { npgsqlCommand.Parameters.Add(queryParameter); } } } }
mit
C#
31a91ec8a04fbdcfee699e373b3be2fc3847401f
Fix FormatIdentity bug
fluentmigrator/fluentmigrator,stsrki/fluentmigrator,fluentmigrator/fluentmigrator,stsrki/fluentmigrator
src/FluentMigrator.Runner.SQLite/Generators/SQLite/SQLiteColumn.cs
src/FluentMigrator.Runner.SQLite/Generators/SQLite/SQLiteColumn.cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator.Model; using FluentMigrator.Runner.Generators.Base; namespace FluentMigrator.Runner.Generators.SQLite { // ReSharper disable once InconsistentNaming internal class SQLiteColumn : ColumnBase { public SQLiteColumn() : base(new SQLiteTypeMap(), new SQLiteQuoter()) { } /// <inheritdoc /> public override string Generate(IEnumerable<ColumnDefinition> columns, string tableName) { var colDefs = columns.ToList(); var foreignKeyColumns = colDefs.Where(x => x.IsForeignKey && x.ForeignKey != null); var foreignKeyClauses = foreignKeyColumns .Select(x => ", " + FormatForeignKey(x.ForeignKey, GenerateForeignKeyName)); // Append foreign key definitions after all column definitions and the primary key definition return base.Generate(colDefs, tableName) + string.Concat(foreignKeyClauses); } /// <inheritdoc /> protected override string FormatIdentity(ColumnDefinition column) { if (column.IsIdentity) { // SQLite only supports the concept of Identity in combination with a single integer primary key // see: http://www.sqlite.org/syntaxdiagrams.html#column-constraint syntax details if (!column.IsPrimaryKey && (!column.Type.HasValue || GetTypeMap(column.Type.Value, null, null) != "INTEGER")) { throw new ArgumentException("SQLite only supports identity on a single integer, primary key coulmns"); } return "AUTOINCREMENT"; } return string.Empty; } /// <inheritdoc /> public override bool ShouldPrimaryKeysBeAddedSeparately(IEnumerable<ColumnDefinition> primaryKeyColumns) { //If there are no identity column then we can add as a separate constrint var pkColDefs = primaryKeyColumns.ToList(); return !pkColDefs.Any(x => x.IsIdentity) && pkColDefs.Any(x => x.IsPrimaryKey); } /// <inheritdoc /> protected override string FormatPrimaryKey(ColumnDefinition column) { return column.IsPrimaryKey ? "PRIMARY KEY" : string.Empty; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using FluentMigrator.Model; using FluentMigrator.Runner.Generators.Base; namespace FluentMigrator.Runner.Generators.SQLite { // ReSharper disable once InconsistentNaming internal class SQLiteColumn : ColumnBase { public SQLiteColumn() : base(new SQLiteTypeMap(), new SQLiteQuoter()) { } /// <inheritdoc /> public override string Generate(IEnumerable<ColumnDefinition> columns, string tableName) { var colDefs = columns.ToList(); var foreignKeyColumns = colDefs.Where(x => x.IsForeignKey && x.ForeignKey != null); var foreignKeyClauses = foreignKeyColumns .Select(x => ", " + FormatForeignKey(x.ForeignKey, GenerateForeignKeyName)); // Append foreign key definitions after all column definitions and the primary key definition return base.Generate(colDefs, tableName) + string.Concat(foreignKeyClauses); } /// <inheritdoc /> protected override string FormatIdentity(ColumnDefinition column) { // SQLite only supports the concept of Identity in combination with a single integer primary key // see: http://www.sqlite.org/syntaxdiagrams.html#column-constraint syntax details if (column.IsIdentity && !column.IsPrimaryKey && (!column.Type.HasValue || GetTypeMap(column.Type.Value, null, null) != "INTEGER")) { throw new ArgumentException("SQLite only supports identity on a single integer, primary key coulmns"); } return "AUTOINCREMENT"; } /// <inheritdoc /> public override bool ShouldPrimaryKeysBeAddedSeparately(IEnumerable<ColumnDefinition> primaryKeyColumns) { //If there are no identity column then we can add as a separate constrint var pkColDefs = primaryKeyColumns.ToList(); return !pkColDefs.Any(x => x.IsIdentity) && pkColDefs.Any(x => x.IsPrimaryKey); } /// <inheritdoc /> protected override string FormatPrimaryKey(ColumnDefinition column) { if (!column.IsPrimaryKey) { return string.Empty; } return column.IsIdentity ? "PRIMARY KEY AUTOINCREMENT" : string.Empty; } } }
apache-2.0
C#
a0bbd7f19962d41fd835210ad0f9ccc9af1264c9
stabilize test
adamabdelhamed/PowerArgs,adamabdelhamed/PowerArgs
PowerArgsTestCore/ConsoleApp/TextBoxTests.cs
PowerArgsTestCore/ConsoleApp/TextBoxTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PowerArgs.Cli; using PowerArgs; using System.Threading; namespace ArgsTests.CLI.Controls { [TestClass] [TestCategory(Categories.ConsoleApp)] public class TextBoxTests { public TestContext TestContext { get; set; } [TestMethod] public void Basic() { var testCli = new CliUnitTestConsole(80, 1); ConsoleProvider.Current = testCli; var app = new ConsoleApp(80, 1); app.LayoutRoot.Add(new TextBox()).Fill(); var task = app.Start(); testCli.Input.Enqueue(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false)); string result = null; app.Stopping.SubscribeForLifetime(() => { result = testCli.Buffer.ToString(); }, app); testCli.Input.Enqueue(new ConsoleKeyInfo('*', ConsoleKey.Escape, false, false, false)); task.Wait(); Assert.AreEqual(80, result.Length); Console.WriteLine(result); } [TestMethod] public void TestRenderTextBox() { var app = new CliTestHarness(this.TestContext, 9, 1); app.InvokeNextCycle(async () => { app.LayoutRoot.Add(new TextBox() { Value = "SomeText".ToWhite() }).Fill(); await app.Paint(); Assert.IsTrue(app.Find("SomeText".ToWhite()).HasValue); app.Stop(); }); app.Start().Wait(); app.AssertThisTestMatchesLKG(); } [TestMethod] public void TestTextBoxBlinkState() { var app = new CliTestHarness(this.TestContext, 9, 1); app.LayoutRoot.Add(new TextBox() { Value = "SomeText".ToWhite() }).Fill(); app.SetTimeout(()=> app.Stop(), TimeSpan.FromSeconds(1.2)); app.Start().Wait(); app.AssertThisTestMatchesLKG(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PowerArgs.Cli; using PowerArgs; using System.Threading; namespace ArgsTests.CLI.Controls { [TestClass] [TestCategory(Categories.ConsoleApp)] public class TextBoxTests { public TestContext TestContext { get; set; } [TestMethod] public void Basic() { var testCli = new CliUnitTestConsole(80, 1); ConsoleProvider.Current = testCli; var app = new ConsoleApp(80, 1); app.LayoutRoot.Add(new TextBox()).Fill(); var task = app.Start(); testCli.Input.Enqueue(new ConsoleKeyInfo('a', ConsoleKey.A, false, false, false)); string result = null; app.Stopping.SubscribeForLifetime(() => { result = testCli.Buffer.ToString(); }, app); testCli.Input.Enqueue(new ConsoleKeyInfo('*', ConsoleKey.Escape, false, false, false)); task.Wait(); Assert.AreEqual(80, result.Length); Console.WriteLine(result); } [TestMethod] public void TestRenderTextBox() { var app = new CliTestHarness(this.TestContext, 9, 1); app.InvokeNextCycle(async () => { app.LayoutRoot.Add(new TextBox() { Value = "SomeText".ToWhite() }).Fill(); await app.Paint(); app.Stop(); }); app.Start().Wait(); Assert.IsTrue(app.Find("SomeText".ToWhite()).HasValue); app.AssertThisTestMatchesLKG(); } [TestMethod] public void TestTextBoxBlinkState() { var app = new CliTestHarness(this.TestContext, 9, 1); app.LayoutRoot.Add(new TextBox() { Value = "SomeText".ToWhite() }).Fill(); app.SetTimeout(()=> app.Stop(), TimeSpan.FromSeconds(1.2)); app.Start().Wait(); app.AssertThisTestMatchesLKG(); } } }
mit
C#
1de58c0dda5037befc166fe41d727efcdfe65275
Make ID atomic
KodamaSakuno/Library
Sakuno.SystemInterop/TaskDialogButtonBase.cs
Sakuno.SystemInterop/TaskDialogButtonBase.cs
using System.Threading; namespace Sakuno.SystemInterop { public abstract class TaskDialogButtonBase { static int r_IDForNextButton = 19; public int ID { get; } public string Text { get; } public bool IsDefault { get; set; } protected TaskDialogButtonBase(string rpText) { ID = Interlocked.Increment(ref r_IDForNextButton) % 1024 + 19; Text = rpText; } protected TaskDialogButtonBase(int rpID, string rpText) { ID = rpID; Text = rpText; } protected TaskDialogButtonBase(TaskDialogCommonButton rpID, string rpText) : this((int)rpID, rpText) { } public override string ToString() => $"ID = {ID}, Text = {Text}"; } }
namespace Sakuno.SystemInterop { public abstract class TaskDialogButtonBase { static int r_IDForNextButton = 19; public int ID { get; } public string Text { get; } public bool IsDefault { get; set; } protected TaskDialogButtonBase(string rpText) { if (r_IDForNextButton == int.MaxValue) r_IDForNextButton = 19; ID = r_IDForNextButton++; Text = rpText; } protected TaskDialogButtonBase(int rpID, string rpText) { ID = rpID; Text = rpText; } protected TaskDialogButtonBase(TaskDialogCommonButton rpID, string rpText) : this((int)rpID, rpText) { } public override string ToString() => $"ID = {ID}, Text = {Text}"; } }
mit
C#
063fd2c99ddda6b7c0ea171ca4263d6cc2b5b287
Refactor UnaryOperation base definition
ajlopez/TensorSharp
Src/TensorSharp/Operations/UnaryOperation.cs
Src/TensorSharp/Operations/UnaryOperation.cs
namespace TensorSharp.Operations { using TensorSharp.Nodes; public abstract class UnaryOperation<T, R> : BaseNode<R> { private INode<T> node; public UnaryOperation(INode<T> node) { this.node = node; } public override int Rank { get { return this.node.Rank; } } public override int[] Shape { get { return this.node.Shape; } } public INode<T> Node { get { return this.node; } } public override INode<R> EvaluateValue() { T[] values = this.Node.Evaluate().Values; int l = values.Length; R[] newvalues = new R[l]; this.Calculate(newvalues, values); return new BaseValueNode<R>(this.Shape, newvalues); } public override bool ApplyContext(Context context) { var app = this.node.ApplyContext(context); if (app) this.ClearValue(); return app; } public abstract void Calculate(R[] newvalues, T[] values); } public abstract class UnaryOperation<T> : UnaryOperation<T, T> { public UnaryOperation(INode<T> node) : base(node) { } } }
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; using TensorSharp.Nodes; public abstract class UnaryOperation<T> : BaseNode<T> { private INode<T> node; public UnaryOperation(INode<T> node) { this.node = node; } public override int Rank { get { return this.node.Rank; } } public override int[] Shape { get { return this.node.Shape; } } public INode<T> Node { get { return this.node; } } public override INode<T> EvaluateValue() { T[] values = this.Node.Evaluate().Values; int l = values.Length; T[] newvalues = new T[l]; this.Calculate(newvalues, values); return new BaseValueNode<T>(this.Shape, newvalues); } public override bool ApplyContext(Context context) { var app = this.node.ApplyContext(context); if (app) this.ClearValue(); return app; } public abstract void Calculate(T[] newvalues, T[] values); } }
mit
C#
9bfb22098fd6f4e4874db9248a437e22505a5ab9
add description and format for errorcode
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework/SysExceptions/SysException.cs
Src/iFramework/SysExceptions/SysException.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using IFramework.Infrastructure; using System.ComponentModel; namespace IFramework.SysExceptions { public class ErrorCodeDictionary { private static Dictionary<object, string> errorcodeDic = new Dictionary<object, string>(); public static string GetErrorMessage(object errorcode, params object[] args) { string errorMessage = errorcodeDic.TryGetValue(errorcode, string.Empty); if (string.IsNullOrEmpty(errorMessage)) { errorMessage = errorcode.GetCustomAttribute<DescriptionAttribute>()?.Description; if (string.IsNullOrEmpty(errorMessage)) { errorMessage = errorcode.ToString(); } } if (args != null && args.Length > 0) { return string.Format(errorMessage, args); } return errorMessage; } public static void InitErrorCodeDictionary(IDictionary<object, string> dictionary) { errorcodeDic = new Dictionary<object, string>(dictionary); } } public class SysException : DomainException { public object ErrorCode { get; set; } public SysException() { } protected SysException(SerializationInfo info, StreamingContext context) : base(info, context) { ErrorCode = info.GetValue("ErrorCode", typeof(object)); } public SysException(object errorCode, string message = null) : base(message ?? ErrorCodeDictionary.GetErrorMessage(errorCode)) { ErrorCode = errorCode; } public SysException(object errorCode, object[] args) : base(ErrorCodeDictionary.GetErrorMessage(errorCode, args)) { ErrorCode = errorCode; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("ErrorCode", this.ErrorCode); base.GetObjectData(info, context); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using IFramework.Infrastructure; namespace IFramework.SysExceptions { public class ErrorCodeDictionary { private static Dictionary<object, string> errorcodeDic = new Dictionary<object, string>(); public static string GetErrorMessage(object errorcode) { string errorMessage = errorcodeDic.TryGetValue(errorcode, string.Empty); if (String.IsNullOrEmpty(errorMessage)) errorMessage = errorcode.ToString(); return errorMessage; } public static void InitErrorCodeDictionary(IDictionary<object, string> dictionary) { errorcodeDic = new Dictionary<object, string>(dictionary); } } public class SysException : DomainException { public object ErrorCode { get; set; } public SysException() { } protected SysException(SerializationInfo info, StreamingContext context) : base(info, context) { ErrorCode = info.GetValue("ErrorCode", typeof(object)); } public SysException(object errorCode, string message = null) : base(message ?? ErrorCodeDictionary.GetErrorMessage(errorCode)) { ErrorCode = errorCode; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("ErrorCode", this.ErrorCode); base.GetObjectData(info, context); } } }
mit
C#
20d6e98a06fd51fbc3011fac538b748cd136f2f3
Update Draw-Line.csx
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
scripts/Draw-Line.csx
scripts/Draw-Line.csx
// Draw Line #r "Core2D" using Core2D.Editor; using Core2D.Editor.Input; Editor.OnToolLine(); var p0 = new InputArgs(30, 30, ModifierFlags.None); Editor.CurrentTool.LeftDown(p0); Editor.CurrentTool.LeftUp(p0); var p1 = new InputArgs(300, 30, ModifierFlags.None); Editor.CurrentTool.LeftDown(p1); Editor.CurrentTool.LeftUp(p1);
// Draw Line #r "Core2D.Editor" using Core2D.Editor; using Core2D.Editor.Input; Editor.OnToolLine(); var p0 = new InputArgs(30, 30, ModifierFlags.None); Editor.LeftDown(p0); Editor.LeftUp(p0); var p1 = new InputArgs(300, 30, ModifierFlags.None); Editor.LeftDown(p1); Editor.LeftUp(p1);
mit
C#