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
abe10068242fa366fd82c933ba8201d76a70ba0d
Set trust token in instance method
sillsdev/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge
src/LfMerge.Core/Actions/Infrastructure/ChorusHelper.cs
src/LfMerge.Core/Actions/Infrastructure/ChorusHelper.cs
// Copyright (c) 2016-2018 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using Autofac; using SIL.Network; using LfMerge.Core.Settings; using SIL.LCModel; using System.Web; namespace LfMerge.Core.Actions.Infrastructure { public class ChorusHelper { static ChorusHelper() { Username = "x"; Password = System.Environment.GetEnvironmentVariable("LD_TRUST_TOKEN") ?? "x"; } public virtual string GetSyncUri(ILfProject project) { var settings = MainClass.Container.Resolve<LfMergeSettings>(); if (!string.IsNullOrEmpty(settings.LanguageDepotRepoUri)) return settings.LanguageDepotRepoUri; var uriBldr = new UriBuilder(project.LanguageDepotProjectUri) { UserName = Username, Password = System.Environment.GetEnvironmentVariable("LD_TRUST_TOKEN") ?? Password, Path = HttpUtility.UrlEncode(project.LanguageDepotProject.Identifier) }; return uriBldr.Uri.ToString(); } public int ModelVersion { get; private set; } public static void SetModelVersion(int modelVersion) { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); chorusHelper.ModelVersion = modelVersion; } public static bool RemoteDataIsForDifferentModelVersion { get { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); return chorusHelper.ModelVersion > 0 && chorusHelper.ModelVersion != LcmCache.ModelVersion; } } public static string Username { get; set; } public static string Password { get; set; } } }
// Copyright (c) 2016-2018 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using Autofac; using SIL.Network; using LfMerge.Core.Settings; using SIL.LCModel; using System.Web; namespace LfMerge.Core.Actions.Infrastructure { public class ChorusHelper { static ChorusHelper() { Username = "x"; Password = System.Environment.GetEnvironmentVariable("LD_TRUST_TOKEN") ?? "x"; } public virtual string GetSyncUri(ILfProject project) { var settings = MainClass.Container.Resolve<LfMergeSettings>(); if (!string.IsNullOrEmpty(settings.LanguageDepotRepoUri)) return settings.LanguageDepotRepoUri; var uriBldr = new UriBuilder(project.LanguageDepotProjectUri) { UserName = Username, Password = Password, Path = HttpUtility.UrlEncode(project.LanguageDepotProject.Identifier) }; return uriBldr.Uri.ToString(); } public int ModelVersion { get; private set; } public static void SetModelVersion(int modelVersion) { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); chorusHelper.ModelVersion = modelVersion; } public static bool RemoteDataIsForDifferentModelVersion { get { var chorusHelper = MainClass.Container.Resolve<ChorusHelper>(); return chorusHelper.ModelVersion > 0 && chorusHelper.ModelVersion != LcmCache.ModelVersion; } } public static string Username { get; set; } public static string Password { get; set; } } }
mit
C#
d596d531a89eba777ed3cf725f5251c3e19fc450
Change border size
noahmorrison/genodf
src/Properties/TableCellProperties.cs
src/Properties/TableCellProperties.cs
using System.Xml; public interface ITableCellProperties { string Bg {get; set;} bool Border {get; set;} bool BorderTop {get; set;} bool BorderBottom {get; set;} bool BorderLeft {get; set;} bool BorderRight {get; set;} } public static class TableCellPropertiesExtension { public static void WriteTableCellProps(this ITableCellProperties props, XmlWriter xml) { xml.WriteStartElement("style:table-cell-properties"); if (props.Bg != null) xml.WriteAttributeString("fo:background-color", props.Bg); if (props.Border) xml.WriteAttributeString("fo:border", "0.3pt solid #000000"); if (props.BorderTop) xml.WriteAttributeString("fo:border-top", "0.3pt solid #000000"); if (props.BorderBottom) xml.WriteAttributeString("fo:border-bottom", "0.3pt solid #000000"); if (props.BorderLeft) xml.WriteAttributeString("fo:border-left", "0.3pt solid #000000"); if (props.BorderRight) xml.WriteAttributeString("fo:border-right", "0.3pt solid #000000"); xml.WriteEndElement(); } public static bool TableCellIsStyled(this ITableCellProperties props) { return props.Bg != null || props.Border || props.BorderTop || props.BorderBottom || props.BorderLeft || props.BorderRight; } }
using System.Xml; public interface ITableCellProperties { string Bg {get; set;} bool Border {get; set;} bool BorderTop {get; set;} bool BorderBottom {get; set;} bool BorderLeft {get; set;} bool BorderRight {get; set;} } public static class TableCellPropertiesExtension { public static void WriteTableCellProps(this ITableCellProperties props, XmlWriter xml) { xml.WriteStartElement("style:table-cell-properties"); if (props.Bg != null) xml.WriteAttributeString("fo:background-color", props.Bg); if (props.Border) xml.WriteAttributeString("fo:border", "00.6pt solid #000000"); if (props.BorderTop) xml.WriteAttributeString("fo:border-top", "00.6pt solid #000000"); if (props.BorderBottom) xml.WriteAttributeString("fo:border-bottom", "00.6pt solid #000000"); if (props.BorderLeft) xml.WriteAttributeString("fo:border-left", "00.6pt solid #000000"); if (props.BorderRight) xml.WriteAttributeString("fo:border-right", "00.6pt solid #000000"); xml.WriteEndElement(); } public static bool TableCellIsStyled(this ITableCellProperties props) { return props.Bg != null || props.Border || props.BorderTop || props.BorderBottom || props.BorderLeft || props.BorderRight; } }
mit
C#
6f949b5497dcc645f75da4e830f61896cb717135
Fix build failure casued by wrong namespace of Assert
mysticfall/Alensia
Assets/Alensia/Core/I18n/Translator.cs
Assets/Alensia/Core/I18n/Translator.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using UnityEngine.Assertions; using Zenject; namespace Alensia.Core.I18n { public abstract class Translator : ITranslator, IInitializable, IDisposable { public ILocaleService LocaleService { get; } public IMessages Messages { get; private set; } protected Translator(ILocaleService localeService) { Assert.IsNotNull(localeService, "localeService != null"); LocaleService = localeService; } public virtual void Initialize() { Messages = Load(LocaleService.CurrentLocale); LocaleService.LocaleChanged.Listen(OnLocaleChange); } public virtual void Dispose() { LocaleService.LocaleChanged.Unlisten(OnLocaleChange); Messages = null; } protected virtual void OnLocaleChange(CultureInfo locale) => Messages = Load(locale); public bool Contains(string key) => Messages?.Contains(key) ?? false; public virtual string this[string key] => Messages?[key]; public virtual string Translate(string key, params object[] args) { var message = Messages?[key]; return message == null ? key : string.Format(message, args); } protected abstract IMessages Load(CultureInfo locale, IMessages parent); protected IMessages Load(CultureInfo locale) { Assert.IsNotNull(locale, "locale != null"); return GetFallbackLocaleHierarchy(locale) .Reverse() .Aggregate<CultureInfo, IMessages>(null, (chain, loc) => Load(loc, chain) ?? chain); } protected virtual IList<CultureInfo> GetFallbackLocaleHierarchy(CultureInfo locale) { Assert.IsNotNull(locale, "locale != null"); var parent = locale; var locales = new List<CultureInfo>(); while (!Equals(parent, CultureInfo.InvariantCulture) && !Equals(parent, LocaleService.DefaultLocale)) { locales.Add(parent); parent = parent.Parent; } locales.Add(LocaleService.DefaultLocale); return locales; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using NUnit.Framework; using Zenject; namespace Alensia.Core.I18n { public abstract class Translator : ITranslator, IInitializable, IDisposable { public ILocaleService LocaleService { get; } public IMessages Messages { get; private set; } protected Translator(ILocaleService localeService) { Assert.IsNotNull(localeService, "localeService != null"); LocaleService = localeService; } public virtual void Initialize() { Messages = Load(LocaleService.CurrentLocale); LocaleService.LocaleChanged.Listen(OnLocaleChange); } public virtual void Dispose() { LocaleService.LocaleChanged.Unlisten(OnLocaleChange); Messages = null; } protected virtual void OnLocaleChange(CultureInfo locale) => Messages = Load(locale); public bool Contains(string key) => Messages?.Contains(key) ?? false; public virtual string this[string key] => Messages?[key]; public virtual string Translate(string key, params object[] args) { var message = Messages?[key]; return message == null ? key : string.Format(message, args); } protected abstract IMessages Load(CultureInfo locale, IMessages parent); protected IMessages Load(CultureInfo locale) { Assert.IsNotNull(locale, "locale != null"); return GetFallbackLocaleHierarchy(locale) .Reverse() .Aggregate<CultureInfo, IMessages>(null, (chain, loc) => Load(loc, chain) ?? chain); } protected virtual IList<CultureInfo> GetFallbackLocaleHierarchy(CultureInfo locale) { Assert.IsNotNull(locale, "locale != null"); var parent = locale; var locales = new List<CultureInfo>(); while (!Equals(parent, CultureInfo.InvariantCulture) && !Equals(parent, LocaleService.DefaultLocale)) { locales.Add(parent); parent = parent.Parent; } locales.Add(LocaleService.DefaultLocale); return locales; } } }
apache-2.0
C#
dd1ab4d0389fe82ad851e9e62d1e9ef0d1230946
Fix game menu problem with UMA demo
mysticfall/Alensia
Assets/Alensia/Demo/MainMenuHandler.cs
Assets/Alensia/Demo/MainMenuHandler.cs
using System; using System.Linq; using Alensia.Core.Control; using Alensia.Core.Game; using Alensia.Core.I18n; using Alensia.Core.UI; using UniRx; using Zenject; namespace Alensia.Demo { public class MainMenuHandler : UIHandler<Panel> { [Inject, NonSerialized] public IGame Game; [Inject, NonSerialized] public IPlayerController Controller; [Inject, NonSerialized] public ILocaleService LocaleService; public Dropdown ChoiceLanguage; public Button ButtonResume; public Button ButtonQuit; private bool _playerControlEnabled; public override void Initialize(IUIContext context) { base.Initialize(context); ButtonResume.OnClick .Subscribe(_ => Close()) .AddTo(this); ButtonQuit.OnClick .Subscribe(_ => Game.Quit()) .AddTo(this); OnClose .Where(_ => Controller.Active) .Subscribe(_ => ResumeGame(_playerControlEnabled)); LocaleService.OnLocaleChange .Select(_ => LocaleService.SupportedLocales) .Select(l => l.Select(i => new DropdownItem(i.ToString(), i.NativeName))) .Subscribe(i => ChoiceLanguage.Items = i.ToList()) .AddTo(this); ChoiceLanguage.Value = LocaleService.CurrentLocale.ToString(); ChoiceLanguage.OnValueChange .Select(k => new LanguageTag(k).ToCulture()) .Subscribe(l => LocaleService.CurrentLocale = l) .AddTo(this); _playerControlEnabled = Controller.PlayerControlEnabled; PauseGame(); } protected virtual void PauseGame() { Game.Pause(); Controller.DisablePlayerControl(); } protected virtual void ResumeGame(bool enableControls) { if (enableControls) { Controller.EnablePlayerControl(); } Game.Resume(); } } }
using System; using System.Linq; using Alensia.Core.Control; using Alensia.Core.Game; using Alensia.Core.I18n; using Alensia.Core.UI; using UniRx; using Zenject; namespace Alensia.Demo { public class MainMenuHandler : UIHandler<Panel> { [Inject, NonSerialized] public IGame Game; [Inject, NonSerialized] public IPlayerController Controller; [Inject, NonSerialized] public ILocaleService LocaleService; public Dropdown ChoiceLanguage; public Button ButtonResume; public Button ButtonQuit; public override void Initialize(IUIContext context) { base.Initialize(context); ButtonResume.OnClick.Subscribe(_ => Close()).AddTo(this); ButtonQuit.OnClick.Subscribe(_ => Game.Quit()).AddTo(this); OnClose.Where(_ => Controller.Active).Subscribe(_ => EnableControls()); LocaleService.OnLocaleChange .Select(_ => LocaleService.SupportedLocales) .Select(l => l.Select(i => new DropdownItem(i.ToString(), i.NativeName))) .Subscribe(i => ChoiceLanguage.Items = i.ToList()) .AddTo(this); ChoiceLanguage.Value = LocaleService.CurrentLocale.ToString(); ChoiceLanguage.OnValueChange .Select(k => new LanguageTag(k).ToCulture()) .Subscribe(l => LocaleService.CurrentLocale = l) .AddTo(this); DisableControls(); } protected virtual void DisableControls() { Game.Pause(); Controller.DisablePlayerControl(); } protected virtual void EnableControls() { Controller.EnablePlayerControl(); Game.Resume(); } } }
apache-2.0
C#
5a586ff986161f11549b0ded187b37bbea0e77a1
Fix drops
Endure-Game/Endure
Assets/Scripts/Health.cs
Assets/Scripts/Health.cs
using UnityEngine; using System.Collections; public class Health : MonoBehaviour { public int maxHealth = 10; [System.Serializable] public class Drop { public int chance; public GameObject item; } public Drop[] drops; private GameObject healthChangeDisplay; private int currentHealth; public int CurrentHealth { get { return currentHealth; } } private bool blocking = false; public bool Block { get { return this.blocking; } set { this.blocking = value; } } // Use this for initialization void Start () { this.currentHealth = this.maxHealth; this.healthChangeDisplay = Resources.Load ("HealthChange", typeof(GameObject)) as GameObject; } public void ChangeHealth (int delta) { if (this.currentHealth + delta < 0) { delta = -this.currentHealth; } else if (this.currentHealth + delta > this.maxHealth) { delta = this.maxHealth - this.currentHealth; } if (!this.Block || delta >= 0) { Vector3 startPos = new Vector3 (this.transform.position.x, this.transform.position.y + 0.75f, 0); GameObject change = Instantiate (healthChangeDisplay, startPos, Quaternion.identity) as GameObject; change.GetComponent<HealthAnimation> ().healthChange = delta; this.currentHealth += delta; if (this.currentHealth <= 0) { this.DropAndDestroy (); } } } void DropAndDestroy () { var position = this.transform.position; Destroy (this.gameObject); var max = 0; foreach (var drop in this.drops) { max += drop.chance; } var current = 0; var selected = Random.Range (0, max + 1); foreach (var drop in this.drops) { current += drop.chance; if (current >= selected) { Instantiate (drop.item, position, Quaternion.identity); break; } } } }
using UnityEngine; using System.Collections; public class Health : MonoBehaviour { public int maxHealth = 10; [System.Serializable] public class Drop { public int chance; public GameObject item; } public Drop[] drops; private GameObject healthChangeDisplay; private int currentHealth; public int CurrentHealth { get { return currentHealth; } } private bool blocking = false; public bool Block { get { return this.blocking; } set { this.blocking = value; } } // Use this for initialization void Start () { this.currentHealth = this.maxHealth; this.healthChangeDisplay = Resources.Load ("HealthChange", typeof(GameObject)) as GameObject; } public void ChangeHealth (int delta) { if (this.currentHealth + delta < 0) { delta = -this.currentHealth; } else if (this.currentHealth + delta > this.maxHealth) { delta = this.maxHealth - this.currentHealth; } if (!this.Block || delta >= 0) { Vector3 startPos = new Vector3 (this.transform.position.x, this.transform.position.y + 0.75f, 0); GameObject change = Instantiate (healthChangeDisplay, startPos, Quaternion.identity) as GameObject; change.GetComponent<HealthAnimation> ().healthChange = delta; this.currentHealth += delta; if (this.currentHealth <= 0) { this.DropAndDestroy (); } } } void DropAndDestroy () { var position = this.transform.position; Destroy (this.gameObject); var max = 0; foreach (var drop in this.drops) { max += drop.chance; } var current = 0; var selected = Random.Range (0, max); foreach (var drop in this.drops) { current += drop.chance; if (current >= selected) { Instantiate (drop.item, position, Quaternion.identity); break; } } } }
mit
C#
7b68c0286ebef3417d5237d25b9f1514a61d1768
make autofac container visible
ZocDoc/ServiceStack,ZocDoc/ServiceStack,ZocDoc/ServiceStack,ZocDoc/ServiceStack
src/ServiceStack/Funke/Container.cs
src/ServiceStack/Funke/Container.cs
using System; using System.Collections.Generic; using Autofac; using Autofac.Core; namespace Funke { public interface IHasContainer { Container Container { get; } } public class Container : IDisposable { private readonly static ContainerBuilder _builder = new ContainerBuilder(); public IContainer AutofacContainer { get; set; } public Container() { AutofacContainer = _builder.Build(); } public void AutoWire(object instance){ } public void RegisterAutoWired<T>() { } public void RegisterAutoWired<T, TAs>() { } public void RegisterAutoWiredAs<T, TAs>() { } public void RegisterAutoWiredType(Type type) { } public void RegisterAutoWiredTypes(HashSet<Type> types) { } public void RegisterAutoWiredTypes(IEnumerable<Type> serviceTypes, ReuseScope scope) { } public void RegisterAutoWiredType(Type serviceType, Type inFunqAsType, ReuseScope scope) { } public void Register<T>(T instance) { } public void Register(Func<Container, object> f) { } public T TryResolve<T>() { throw new NotImplementedException(); } public T Resolve<T>() { throw new NotImplementedException(); } public Owner DefaultOwner { get; set; } public void Dispose() { } } public enum Owner { Container, External, Default, } public interface IFunkelet { void Configure(Container container); } public enum ReuseScope { Hierarchy, Container, None, Request, Default = Hierarchy, } }
using System; using System.Collections.Generic; using Autofac; using Autofac.Core; namespace Funke { public interface IHasContainer { Container Container { get; } } public class Container : IDisposable { private static ContainerBuilder _builder = new ContainerBuilder(); private IContainer _autofacContainer; public Container() { _autofacContainer = _builder.Build(); } public void AutoWire(object instance){ } public void RegisterAutoWired<T>() { } public void RegisterAutoWired<T, TAs>() { } public void RegisterAutoWiredAs<T, TAs>() { } public void RegisterAutoWiredType(Type type) { } public void RegisterAutoWiredTypes(HashSet<Type> types) { } public void RegisterAutoWiredTypes(IEnumerable<Type> serviceTypes, ReuseScope scope) { } public void RegisterAutoWiredType(Type serviceType, Type inFunqAsType, ReuseScope scope) { } public void Register<T>(T instance) { } public void Register(Func<Container, object> f) { } public T TryResolve<T>() { throw new NotImplementedException(); } public T Resolve<T>() { throw new NotImplementedException(); } public Owner DefaultOwner { get; set; } public void Dispose() { } } public enum Owner { Container, External, Default, } public interface IFunkelet { void Configure(Container container); } public enum ReuseScope { Hierarchy, Container, None, Request, Default = Hierarchy, } }
bsd-3-clause
C#
60334046e4dd7dface21e505d9ea929627993433
Revert `UserTrackingScrollContainer` changes
ppy/osu,peppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Graphics/Containers/UserTrackingScrollContainer.cs
osu.Game/Graphics/Containers/UserTrackingScrollContainer.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.Graphics; namespace osu.Game.Graphics.Containers { public class UserTrackingScrollContainer : UserTrackingScrollContainer<Drawable> { public UserTrackingScrollContainer() { } public UserTrackingScrollContainer(Direction direction) : base(direction) { } } public class UserTrackingScrollContainer<T> : OsuScrollContainer<T> where T : Drawable { /// <summary> /// Whether the last scroll event was user triggered, directly on the scroll container. /// </summary> public bool UserScrolling { get; private set; } public void CancelUserScroll() => UserScrolling = false; public UserTrackingScrollContainer() { } public UserTrackingScrollContainer(Direction direction) : base(direction) { } protected override void OnUserScroll(float value, bool animated = true, double? distanceDecay = default) { UserScrolling = true; base.OnUserScroll(value, animated, distanceDecay); } public new void ScrollIntoView(Drawable target, bool animated = true) { UserScrolling = false; base.ScrollIntoView(target, animated); } public new void ScrollTo(float value, bool animated = true, double? distanceDecay = null) { UserScrolling = false; base.ScrollTo(value, animated, distanceDecay); } public new void ScrollToEnd(bool animated = true, bool allowDuringDrag = false) { UserScrolling = false; base.ScrollToEnd(animated, allowDuringDrag); } } }
// 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.Graphics; namespace osu.Game.Graphics.Containers { public class UserTrackingScrollContainer : UserTrackingScrollContainer<Drawable> { public UserTrackingScrollContainer() { } public UserTrackingScrollContainer(Direction direction) : base(direction) { } } public class UserTrackingScrollContainer<T> : OsuScrollContainer<T> where T : Drawable { /// <summary> /// Whether the last scroll event was user triggered, directly on the scroll container. /// </summary> public bool UserScrolling { get; private set; } public UserTrackingScrollContainer() { } public UserTrackingScrollContainer(Direction direction) : base(direction) { } protected override void OnUserScroll(float value, bool animated = true, double? distanceDecay = default) { base.OnUserScroll(value, animated, distanceDecay); OnScrollChange(true); } public new void ScrollIntoView(Drawable target, bool animated = true) { base.ScrollIntoView(target, animated); OnScrollChange(false); } public new void ScrollTo(float value, bool animated = true, double? distanceDecay = null) { base.ScrollTo(value, animated, distanceDecay); OnScrollChange(false); } public new void ScrollToStart(bool animated = true, bool allowDuringDrag = false) { base.ScrollToStart(animated, allowDuringDrag); OnScrollChange(false); } public new void ScrollToEnd(bool animated = true, bool allowDuringDrag = false) { base.ScrollToEnd(animated, allowDuringDrag); OnScrollChange(false); } /// <summary> /// Invoked when any scroll has been performed either programmatically or by user. /// </summary> protected virtual void OnScrollChange(bool byUser) => UserScrolling = byUser; } }
mit
C#
773bb4717987bbdaf48cf7ccb421715bfdb99ba7
Refactor VkVersion
rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary
CSGL.Vulkan/VkVersion.cs
CSGL.Vulkan/VkVersion.cs
using System; using System.Text; namespace CSGL.Vulkan { public struct VkVersion { uint version; public VkVersion(int major, int minor, int revision) { version = 0; Major = major; Minor = minor; Revision = revision; } public VkVersion(uint version) { this.version = version; } public static implicit operator uint(VkVersion v) { return v.version; } public static implicit operator VkVersion(uint v) { return new VkVersion(v); } public int Major { get { return (int)(version >> 22); } set { version &= ~0xffc00000; version |= ((uint)value << 22); } } public int Minor { get { return (int)(version >> 12) & 0x3ff; } set { version &= ~((uint)0x3ff000); version |= (((uint)value << 12) & 0x3ff000); } } public int Revision { get { return (int)(version) & 0xfff; } set { version &= ~((uint)0xfff); version |= ((uint)value & 0xfff); } } public override string ToString() { return string.Format("{0}.{1}.{2}", Major, Minor, Revision); } } }
using System; using System.Text; namespace CSGL.Vulkan { public struct VkVersion { uint version; public VkVersion(uint major, uint minor, uint revision) { version = 0; Major = major; Minor = minor; Revision = revision; } public VkVersion(uint version) { this.version = version; } public static implicit operator uint(VkVersion v) { return v.version; } public static implicit operator VkVersion(uint v) { return new VkVersion(v); } public uint Major { get { return (version >> 22); } set { version &= ~0xffc00000; version |= (value << 22); } } public uint Minor { get { return (version >> 12) & 0x3ff; } set { version &= ~((uint)0x3ff000); version |= ((value << 12) & 0x3ff000); } } public uint Revision { get { return (version) & 0xfff; } set { version &= ~((uint)0xfff); version |= (value & 0xfff); } } public override string ToString() { return string.Format("{0}.{1}.{2}", Major, Minor, Revision); } } }
mit
C#
40bcf1b173cd0c7f146e64d244d5811e8fd00b38
correct environment
modulexcite/lokad-cqrs
Cqrs.Azure.Tests/ConnectionConfig.cs
Cqrs.Azure.Tests/ConnectionConfig.cs
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using Microsoft.WindowsAzure; namespace Cqrs.Azure.Tests { public static class ConnectionConfig { public static CloudStorageAccount GetAzureConnnectionString() { if (Environment.GetEnvironmentVariable("Data_Store") != null) return CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("Data_Store")); return CloudStorageAccount.DevelopmentStorageAccount; } static readonly Lazy<CloudStorageAccount> Connection = new Lazy<CloudStorageAccount>(GetAzureConnnectionString); public static CloudStorageAccount StorageAccount { get { return Connection.Value; } } } }
#region (c) 2010-2011 Lokad - CQRS for Windows Azure - New BSD License // Copyright (c) Lokad 2010-2011, http://www.lokad.com // This code is released as Open Source under the terms of the New BSD Licence #endregion using System; using Microsoft.WindowsAzure; namespace Cqrs.Azure.Tests { public static class ConnectionConfig { public static CloudStorageAccount GetAzureConnnectionString() { if (Environment.GetEnvironmentVariable("env.Data_Store") != null) return CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("env.Data_Store")); return CloudStorageAccount.DevelopmentStorageAccount; } static readonly Lazy<CloudStorageAccount> Connection = new Lazy<CloudStorageAccount>(GetAzureConnnectionString); public static CloudStorageAccount StorageAccount { get { return Connection.Value; } } } }
bsd-3-clause
C#
b93049dc89d18bf7936fdf8794fc02a2807a2cac
Update Unit.cs And Converter.csproj
zonetrooper32/UnitConverter
Converter/Models/Unit.cs
Converter/Models/Unit.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Converter.Models { public class Unit { public string UnitName { get; set; } public string ChineseUnitName { get; set; } public double ConvertingValue { get; set; } //ConvertingValue is a double that multiply one unit equal to one meters. //For example: //1 centimeter * 100 = 1 meter //"100" is the ConvertingValue. //1 kilometer * 0.001 = 1 meter //"0.001"is the ConvertingValue. } //This Method Reference github.com/gncvt/UnitConverter public class ConvertMethod { public double BasicUnitConvert(double ToConvert, double ToConvertUnitConvertingValue, double ConvertedUnitConvertingValue ) { double result = (ToConvert / ToConvertUnitConvertingValue * ConvertedUnitConvertingValue); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Converter.Models { public class Unit { public string unitname { get; set; } public double convertingvalue { get; set; } //ConvertingValue is a double that multiply one unit equal to one meters. //For example: //1 centimeter * 100 = 1 meter //"100" is the ConvertingValue. //1 kilometer * 0.001 = 1 meter //"0.001"is the ConvertingValue. } public class convertmethod { public double dimensionconvert(double toconvert, double toconvertUnitConvertingValue, double convertedUnitConvertingValue ) { double result = (toconvert / toconvertUnitConvertingValue * convertedUnitConvertingValue); return result; } } }
mit
C#
02663c997657f2fe59bdc5b0fdf92532bee5e2ec
FIx autofac registarion
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/ExampleTests/IoC/IoC_Example_Installers/AutofacRegistrar.cs
src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/ExampleTests/IoC/IoC_Example_Installers/AutofacRegistrar.cs
using System; using System.Data; using Autofac; using Smooth.IoC.UnitOfWork; namespace Smooth.IoC.Repository.UnitOfWork.Tests.ExampleTests.IoC.IoC_Example_Installers { public class AutofacRegistrar { public void Register(ContainerBuilder builder) { builder.Register(c=> new DbFactory(c.Resolve<IComponentContext>())).As<IDbFactory>().SingleInstance(); builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>)); builder.RegisterType<UnitOfWork>().As<IUnitOfWork>(); } sealed class DbFactory : IDbFactory { private readonly IComponentContext _container; public AutofacDbFactory(IComponentContext container) { _container = container; } public T Create<T>() where T : class, ISession { return _container.Resolve<T>(); } public TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel = IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession { return _container.Resolve<TUnitOfWork>(new NamedParameter("factory", _container.Resolve <IDbFactory>()), new NamedParameter("session", Create<TSession>()), new NamedParameter("isolationLevel", isolationLevel) , new NamedParameter("sessionOnlyForThisUnitOfWork", true)); } public T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork { return _container.Resolve<T>(new NamedParameter("factory", factory), new NamedParameter("session", session), new NamedParameter("isolationLevel", isolationLevel)); } public void Release(IDisposable instance) { instance.Dispose(); } } } }
using System; using System.Data; using Autofac; using Smooth.IoC.UnitOfWork; namespace Smooth.IoC.Repository.UnitOfWork.Tests.ExampleTests.IoC.IoC_Example_Installers { public class AutofacRegistrar { public void Register(ContainerBuilder builder) { builder.Register(c=> new AutofacDbFactory(c)).As<IDbFactory>().SingleInstance(); builder.RegisterType<Smooth.IoC.UnitOfWork.UnitOfWork>().As<IUnitOfWork>(); } sealed class AutofacDbFactory : IDbFactory { private readonly IComponentContext _container; public AutofacDbFactory(IComponentContext container) { _container = container; } public T Create<T>() where T : class, ISession { return _container.Resolve<T>(); } public TUnitOfWork Create<TUnitOfWork, TSession>(IsolationLevel isolationLevel = IsolationLevel.Serializable) where TUnitOfWork : class, IUnitOfWork where TSession : class, ISession { return _container.Resolve<TUnitOfWork>(new NamedParameter("factory", _container.Resolve <IDbFactory>()), new NamedParameter("session", Create<TSession>()), new NamedParameter("isolationLevel", isolationLevel) , new NamedParameter("sessionOnlyForThisUnitOfWork", true)); } public T Create<T>(IDbFactory factory, ISession session, IsolationLevel isolationLevel = IsolationLevel.Serializable) where T : class, IUnitOfWork { return _container.Resolve<T>(new NamedParameter("factory", factory), new NamedParameter("session", session), new NamedParameter("isolationLevel", isolationLevel)); } public void Release(IDisposable instance) { instance.Dispose(); } } } }
mit
C#
d0fa35e851f13fb00b4789d0151f3a6c8c378e26
Set the artist to the username
flagbug/Espera,punker76/Espera
Espera/Espera.Core/SoundCloudSong.cs
Espera/Espera.Core/SoundCloudSong.cs
using Espera.Network; using Newtonsoft.Json; using System; namespace Espera.Core { public class SoundCloudSong : Song { private User user; public SoundCloudSong() : base(String.Empty, TimeSpan.Zero) { } [JsonProperty("artwork_url")] public Uri ArtworkUrl { get; set; } public string Description { get; set; } [JsonProperty("duration")] public int DurationMilliseconds { get { return (int)this.Duration.TotalMilliseconds; } set { this.Duration = TimeSpan.FromMilliseconds(value); } } public int Id { get; set; } [JsonProperty("streamable")] public bool IsStreamable { get; set; } public override bool IsVideo { get { return false; } } public override NetworkSongSource NetworkSongSource { get { return NetworkSongSource.Youtube; } } [JsonProperty("permalink_url")] public Uri PermaLinkUrl { get { return new Uri(this.OriginalPath); } set { this.OriginalPath = value.ToString(); } } [JsonProperty("stream_url")] public Uri StreamUrl { get { return new Uri(this.PlaybackPath); } set { this.PlaybackPath = value.ToString(); } } public User User { get { return this.user; } set { this.user = value; this.Artist = value.Username; } } } public class User { public string Username { get; set; } } }
using Espera.Network; using Newtonsoft.Json; using System; namespace Espera.Core { public class SoundCloudSong : Song { public SoundCloudSong() : base(String.Empty, TimeSpan.Zero) { } [JsonProperty("artwork_url")] public Uri ArtworkUrl { get; set; } public string Description { get; set; } [JsonProperty("duration")] public int DurationMilliseconds { get { return (int)this.Duration.TotalMilliseconds; } set { this.Duration = TimeSpan.FromMilliseconds(value); } } public int Id { get; set; } [JsonProperty("streamable")] public bool IsStreamable { get; set; } public override bool IsVideo { get { return false; } } public override NetworkSongSource NetworkSongSource { get { return NetworkSongSource.Youtube; } } [JsonProperty("permalink_url")] public Uri PermaLinkUrl { get { return new Uri(this.OriginalPath); } set { this.OriginalPath = value.ToString(); } } [JsonProperty("stream_url")] public Uri StreamUrl { get { return new Uri(this.PlaybackPath); } set { this.PlaybackPath = value.ToString(); } } public User User { get; set; } } public class User { public string Username { get; set; } } }
mit
C#
8db36102390e55ace9d425e3d648d5203e5ac72a
change CubesGenerator
RicardoEPRodrigues/Bichux
Assets/Scripts/CubesGenerator.cs
Assets/Scripts/CubesGenerator.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CubesGenerator : MonoBehaviour { //standard prefab [SerializeField] private GameObject defaultCube; //cubes number public int numberCubes; //refernece to manager private GameManager manager; //cubes container private List<Cube> cubes = null; void Start () { //init moving cubes cubes = new List<Cube>(); createCubes(); //reference to manager manager = GameManager.GetInstance(); } void Update () { foreach (Cube cube in cubes) { cube.lifeCycle(manager.generator.Speed); } } private void createCubes() { float x, y, z; for (int i = 0; i < numberCubes; i++) { x = Random.Range(-45, 72); y = Random.Range(-20, 47); z = Random.Range(20, 40); cubes.Add(new Cube(defaultCube, new Vector3(x, y, z))); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class CubesGenerator : MonoBehaviour { //standard configs [SerializeField] private GameObject defaultCube; [SerializeField] private float speed; public bool cubesEnable; public int numberCubes; //cubes container private List<Cube> cubes = null; void Start () { cubes = new List<Cube>(); createCubes(); } void Update () { if (cubesEnable) { foreach (Cube cube in cubes) { cube.lifeCycle(speed); } } } private void createCubes() { float x, y, z; for (int i = 0; i < numberCubes; i++) { x = Random.Range(-45, 72); y = Random.Range(-20, 47); z = Random.Range(20, 40); cubes.Add(new Cube(defaultCube, new Vector3(x, y, z))); } } }
mit
C#
1a550d449b5c4ff7ab3b5f38946bfab9780e55a0
Comment Title
karitasolafs/TextDoc,karitasolafs/TextDoc
TextDuck/Views/Home/Subtitle.cshtml
TextDuck/Views/Home/Subtitle.cshtml
@model IQueryable<TextDuck.Models.srtFiles> <h1>Skjátextar</h1> <div> @Html.ActionLink("Bæta við skjátexta", "Create", "Home") </div> <table class="table table-hover"> <tr> <th> Nafn </th> <th> Tungumal </th> <th> Flokkur </th> <th> Tegund </th> <th> Dagsetning </th> <th> </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.ActionLink(item.Title, "ViewSrt", new { Id = item.Id,}) </td> <td> @Html.DisplayFor(modelItem => item.Language) </td> <td> @Html.DisplayFor(modelItem => item.Category) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> <td> @Html.ActionLink("Breyta skrá", "TextBoxSrt", new { Id = item.Id }, null) | @Html.ActionLink("Breyta upplýsingum", "FileAppearanceChanges", new { Id = item.Id }, null) | @Html.ActionLink("Commenta", "AddComment", new { Id = item.Id, Title = item.Title }, null) </td> </tr> } </table> <div> @Html.ActionLink("Back to List", "Index") </div>
@model IQueryable<TextDuck.Models.srtFiles> <h1>Skjátextar</h1> <div> @Html.ActionLink("Bæta við skjátexta", "Create", "Home") </div> <table class="table table-hover"> <tr> <th> Nafn </th> <th> Tungumal </th> <th> Flokkur </th> <th> Tegund </th> <th> Dagsetning </th> <th> </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.ActionLink(item.Title, "ViewSrt", new { Id = item.Id }) </td> <td> @Html.DisplayFor(modelItem => item.Language) </td> <td> @Html.DisplayFor(modelItem => item.Category) </td> <td> @Html.DisplayFor(modelItem => item.Genre) </td> <td> @Html.DisplayFor(modelItem => item.Date) </td> <td> @Html.ActionLink("Breyta skrá", "TextBoxSrt", new { Id = item.Id }, null) | @Html.ActionLink("Breyta upplýsingum", "FileAppearanceChanges", new { Id = item.Id }, null) | @Html.ActionLink("Commenta", "AddComment", new { Id = item.Id }, null) </td> </tr> } </table> <div> @Html.ActionLink("Back to List", "Index") </div>
mit
C#
b6188809c7169112b3a28fbe67ad294185b8853f
Fix not to create instance of AppLovinSdk class. This class is abstract class.
googleads/googleads-mobile-unity,googleads/googleads-mobile-unity
mediation/AppLovin/source/plugin/Assets/GoogleMobileAds/Platforms/Android/Mediation/AppLovin/AppLovinClient.cs
mediation/AppLovin/source/plugin/Assets/GoogleMobileAds/Platforms/Android/Mediation/AppLovin/AppLovinClient.cs
// Copyright (C) 2017 Google, Inc. // // 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. #if UNITY_ANDROID using System.Reflection; using UnityEngine; using GoogleMobileAds.Common.Mediation.AppLovin; namespace GoogleMobileAds.Android.Mediation.AppLovin { public class AppLovinClient : IAppLovinClient { private static AppLovinClient instance = new AppLovinClient(); private AppLovinClient() { } public static AppLovinClient Instance { get { return instance; } } public void Initialize() { MonoBehaviour.print("AppLovin intialize received"); AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); AndroidJavaClass appLovin = new AndroidJavaClass("com.applovin.sdk.AppLovinSdk"); appLovin.CallStatic("initializeSdk", currentActivity); } } } #endif
// Copyright (C) 2017 Google, Inc. // // 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. #if UNITY_ANDROID using System.Reflection; using UnityEngine; using GoogleMobileAds.Common.Mediation.AppLovin; namespace GoogleMobileAds.Android.Mediation.AppLovin { public class AppLovinClient : IAppLovinClient { private static AppLovinClient instance = new AppLovinClient(); private AppLovinClient() { } public static AppLovinClient Instance { get { return instance; } } public void Initialize() { MonoBehaviour.print("AppLovin intialize received"); AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); AndroidJavaObject appLovin = new AndroidJavaObject("com.applovin.sdk.AppLovinSdk"); appLovin.CallStatic("initializeSdk", currentActivity); } } } #endif
apache-2.0
C#
17102b7283bbde0b1f79a217a47fc2217fc41a52
Change WM_DEVICECHANGE value to hexadecimal
ggobbe/WinUsbInit
WinUsbInit/DeviceArrivalListener.cs
WinUsbInit/DeviceArrivalListener.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinUsbInit { class DeviceArrivalListener : NativeWindow { // Constant values was found in the "windows.h" header file. private const int WM_DEVICECHANGE = 0x219; private const int DBT_DEVICEARRIVAL = 0x8000; private readonly WinUsbInitForm _parent; public DeviceArrivalListener(WinUsbInitForm parent) { parent.HandleCreated += OnHandleCreated; parent.HandleDestroyed += OnHandleDestroyed; _parent = parent; } // Listen for the control's window creation and then hook into it. internal void OnHandleCreated(object sender, EventArgs e) { // Window is now created, assign handle to NativeWindow. AssignHandle(((WinUsbInitForm)sender).Handle); } internal void OnHandleDestroyed(object sender, EventArgs e) { // Window was destroyed, release hook. ReleaseHandle(); } protected override void WndProc(ref Message m) { // Listen for operating system messages if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL) { // Notify the form that this message was received. _parent.DeviceInserted(); } base.WndProc(ref m); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinUsbInit { class DeviceArrivalListener : NativeWindow { // Constant value was found in the "windows.h" header file. private const int WM_DEVICECHANGE = 537; private const int DBT_DEVICEARRIVAL = 0x8000; private readonly WinUsbInitForm _parent; public DeviceArrivalListener(WinUsbInitForm parent) { parent.HandleCreated += OnHandleCreated; parent.HandleDestroyed += OnHandleDestroyed; _parent = parent; } // Listen for the control's window creation and then hook into it. internal void OnHandleCreated(object sender, EventArgs e) { // Window is now created, assign handle to NativeWindow. AssignHandle(((WinUsbInitForm)sender).Handle); } internal void OnHandleDestroyed(object sender, EventArgs e) { // Window was destroyed, release hook. ReleaseHandle(); } protected override void WndProc(ref Message m) { // Listen for operating system messages if (m.Msg == WM_DEVICECHANGE && (int) m.WParam == DBT_DEVICEARRIVAL) { // Notify the form that this message was received. _parent.DeviceInserted(); } base.WndProc(ref m); } } }
mit
C#
43666fdd6241c709cc30dbf30770bb7903be3b7b
Remove workaround for ApplicationInsights
martincostello/website,martincostello/website,martincostello/website,martincostello/website
tests/Website.Tests/Integration/TestServerCollection.cs
tests/Website.Tests/Integration/TestServerCollection.cs
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website.Integration { using Xunit; /// <summary> /// A class representing the collection fixture for a test server. This class cannot be inherited. /// </summary> [CollectionDefinition(Name)] public sealed class TestServerCollection : ICollectionFixture<TestServerFixture> { /// <summary> /// The name of the test fixture. /// </summary> public const string Name = "Test server collection"; } }
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website.Integration { using Xunit; /// <summary> /// A class representing the collection fixture for a test server. This class cannot be inherited. /// </summary> [CollectionDefinition(Name, DisableParallelization = true)] // Causes issues with ApplicationInsights if not disabled public sealed class TestServerCollection : ICollectionFixture<TestServerFixture> { /// <summary> /// The name of the test fixture. /// </summary> public const string Name = "Test server collection"; } }
apache-2.0
C#
b4746be3057fc7620d262776f154f1b5432ad0cc
Add doc
ErikSchierboom/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,davkean/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,physhi/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,reaction1989/roslyn,tmat/roslyn,dotnet/roslyn,bartdesmet/roslyn,gafter/roslyn,sharwell/roslyn,gafter/roslyn,KevinRansom/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,tannergooding/roslyn,brettfo/roslyn,mavasani/roslyn,heejaechang/roslyn,eriawan/roslyn,tannergooding/roslyn,jmarolf/roslyn,wvdd007/roslyn,sharwell/roslyn,genlu/roslyn,bartdesmet/roslyn,jmarolf/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,mavasani/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,brettfo/roslyn,diryboy/roslyn,wvdd007/roslyn,AmadeusW/roslyn,tannergooding/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,dotnet/roslyn,stephentoub/roslyn,eriawan/roslyn,AlekseyTs/roslyn,gafter/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,eriawan/roslyn,davkean/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,genlu/roslyn,tmat/roslyn,weltkante/roslyn,diryboy/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,reaction1989/roslyn,tmat/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,physhi/roslyn,aelij/roslyn,panopticoncentral/roslyn
src/Workspaces/Remote/ServiceHub/Services/DesignerAttribute/RemoteDesignerAttributeIncrementalAnalyzerProvider.cs
src/Workspaces/Remote/ServiceHub/Services/DesignerAttribute/RemoteDesignerAttributeIncrementalAnalyzerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal class RemoteDesignerAttributeIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteEndPoint _endPoint; public RemoteDesignerAttributeIncrementalAnalyzerProvider(RemoteEndPoint endPoint) { _endPoint = endPoint; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteDesignerAttributeIncrementalAnalyzer(_endPoint, workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using Microsoft.CodeAnalysis.SolutionCrawler; namespace Microsoft.CodeAnalysis.Remote { internal class RemoteDesignerAttributeIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteEndPoint _endPoint; public RemoteDesignerAttributeIncrementalAnalyzerProvider(RemoteEndPoint endPoint) { _endPoint = endPoint; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteDesignerAttributeIncrementalAnalyzer(_endPoint, workspace); } }
mit
C#
087b5af8fe484beb179ae3dc2b22d91930d4c43a
add last site config modified time to environment api
uQr/kudu,barnyp/kudu,MavenRain/kudu,barnyp/kudu,oliver-feng/kudu,oliver-feng/kudu,badescuga/kudu,bbauya/kudu,juoni/kudu,chrisrpatterson/kudu,juvchan/kudu,sitereactor/kudu,badescuga/kudu,chrisrpatterson/kudu,oliver-feng/kudu,badescuga/kudu,duncansmart/kudu,mauricionr/kudu,sitereactor/kudu,projectkudu/kudu,dev-enthusiast/kudu,projectkudu/kudu,kenegozi/kudu,juvchan/kudu,YOTOV-LIMITED/kudu,MavenRain/kudu,duncansmart/kudu,dev-enthusiast/kudu,shibayan/kudu,kali786516/kudu,projectkudu/kudu,shrimpy/kudu,juoni/kudu,bbauya/kudu,YOTOV-LIMITED/kudu,EricSten-MSFT/kudu,bbauya/kudu,uQr/kudu,kali786516/kudu,shrimpy/kudu,mauricionr/kudu,badescuga/kudu,puneet-gupta/kudu,chrisrpatterson/kudu,kali786516/kudu,kenegozi/kudu,puneet-gupta/kudu,oliver-feng/kudu,bbauya/kudu,shibayan/kudu,shibayan/kudu,badescuga/kudu,juvchan/kudu,EricSten-MSFT/kudu,juvchan/kudu,sitereactor/kudu,mauricionr/kudu,dev-enthusiast/kudu,sitereactor/kudu,uQr/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,MavenRain/kudu,YOTOV-LIMITED/kudu,kenegozi/kudu,EricSten-MSFT/kudu,projectkudu/kudu,shibayan/kudu,duncansmart/kudu,dev-enthusiast/kudu,kenegozi/kudu,kali786516/kudu,juvchan/kudu,shrimpy/kudu,chrisrpatterson/kudu,mauricionr/kudu,EricSten-MSFT/kudu,duncansmart/kudu,uQr/kudu,juoni/kudu,shibayan/kudu,MavenRain/kudu,projectkudu/kudu,barnyp/kudu,YOTOV-LIMITED/kudu,barnyp/kudu,sitereactor/kudu,puneet-gupta/kudu,puneet-gupta/kudu,shrimpy/kudu,juoni/kudu
Kudu.Services/EnvironmentController.cs
Kudu.Services/EnvironmentController.cs
using System.IO; using System.Net; using System.Net.Http; using System.Web.Http; using Kudu.Core; using Newtonsoft.Json.Linq; namespace Kudu.Services { public class EnvironmentController : ApiController { private static readonly string _version = typeof(EnvironmentController).Assembly.GetName().Version.ToString(); /// <summary> /// Get the Kudu version /// </summary> /// <returns></returns> [HttpGet] public HttpResponseMessage Get() { // Return the version and other api information (in the end) // { // "version" : "1.0.0", // "siteLastModified" : "2015-02-11T18:27:22.7270000Z", // } var obj = new JObject(new JProperty("version", _version)); // this file is written by dwas to communicate the last site configuration modified time var lastModifiedFile = Path.Combine( Path.GetDirectoryName(System.Environment.GetEnvironmentVariable("TMP")), @"config\SiteLastModifiedTime.txt"); if (File.Exists(lastModifiedFile)) { obj["siteLastModified"] = File.ReadAllText(lastModifiedFile); } return Request.CreateResponse(HttpStatusCode.OK, obj); } } }
using System.Net; using System.Net.Http; using System.Web.Http; using Newtonsoft.Json.Linq; namespace Kudu.Services { public class EnvironmentController : ApiController { private static readonly string _version = typeof(EnvironmentController).Assembly.GetName().Version.ToString(); /// <summary> /// Get the Kudu version /// </summary> /// <returns></returns> [HttpGet] public HttpResponseMessage Get() { // Return the version and other api information (in the end) // { // "version" : "1.0.0" // } var obj = new JObject(new JProperty("version", _version)); return Request.CreateResponse(HttpStatusCode.OK, obj); } } }
apache-2.0
C#
e9c44438d6256604d8c4b53012eaec67e35c19ee
Use $ for hex symbol to match wla
Drenn1/LynnaLab,Drenn1/LynnaLab
LynnaLab/UI/SpinButtonHexadecimal.cs
LynnaLab/UI/SpinButtonHexadecimal.cs
using System; using Gtk; namespace LynnaLab { [System.ComponentModel.ToolboxItem(true)] public partial class SpinButtonHexadecimal : Gtk.SpinButton { public SpinButtonHexadecimal() : base(0,100,1) { this.Numeric = false; } protected override int OnOutput() { this.Numeric = false; Text = "$" + ValueAsInt.ToString("X" + Digits); return 1; } protected override int OnInput(out double value) { string text = Text.Trim(); bool success = false; value = Value; try { value = Convert.ToInt32(text); success = true; } catch (Exception e) { } try { if (text.Length > 0 && text[0] == '$') { value = Convert.ToInt32(text.Substring(1),16); success = true; } } catch (Exception) { } if (!success) value = Value; return 1; } } }
using System; using Gtk; namespace LynnaLab { [System.ComponentModel.ToolboxItem(true)] public partial class SpinButtonHexadecimal : Gtk.SpinButton { public SpinButtonHexadecimal() : base(0,100,1) { this.Numeric = false; } protected override int OnOutput() { this.Numeric = false; Text = "0x" + ValueAsInt.ToString("X" + Digits); return 1; } protected override int OnInput(out double value) { try { value = Convert.ToInt32(Text); } catch (Exception e) { try { value = Convert.ToInt32(Text.Substring(2),16); } catch (Exception) { value = Value; } } return 1; } } }
mit
C#
f68541e4aac5906a7911d350705dccc2f9c6fcca
Fix signature of undirected edge
DasAllFolks/SharpGraphs
Graph/IUndirectedEdge.cs
Graph/IUndirectedEdge.cs
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IComparable<W>, IEquatable<W> { } }
using System; using System.Collections.Generic; namespace Graph { /// <summary> /// Represents an undirected edge (link) in a labeled <see cref="IGraph"/>. /// </summary> /// <typeparam name="V"> /// The type used to create vertex (node) labels. /// </typeparam> /// <typeparam name="W"> /// The type used for the edge weight. /// </typeparam> public interface IUndirectedEdge<V, W> : IEdge<V, W>, IEquatable<IUndirectedEdge<V, W>> where V : struct, IEquatable<V> where W : struct, IComparable<W>, IEquatable<W> { /// <summary> /// The vertices comprising the <see cref="IUndirectedEdge{V}"/>. /// </summary> ISet<V> Vertices { get; } } }
apache-2.0
C#
4d9eef4e7e014f0e84825db62368efa916a4612b
Update versioninfo
vnbaaij/ImageProcessor.Web.Episerver,vnbaaij/ImageProcessor.Web.Episerver,vnbaaij/ImageProcessor.Web.Episerver
src/ImageProcessor.Web.Episerver/Properties/AssemblyInfo.cs
src/ImageProcessor.Web.Episerver/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("ImageProcessor.Web.Episerver")] [assembly: AssemblyDescription("Use ImageProcessor in Episerver. Fluent API to manipulate images and generate progressive lazy loading responsive images using picture element")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Vincent Baaij")] [assembly: AssemblyProduct("ImageProcessor.Web.Episerver")] [assembly: AssemblyCopyright("Copyright 2019")] [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("2edae29a-d622-4b01-8853-d26f4d1c0fd8")] // 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.0.0")] [assembly: AssemblyVersion("5.3.2.*")] [assembly: AssemblyFileVersion("5.3.2.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("ImageProcessor.Web.Episerver")] [assembly: AssemblyDescription("Use ImageProcessor in Episerver. Fluent API to manipulate images and generate progressive lazy loading responsive images using picture element")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Vincent Baaij")] [assembly: AssemblyProduct("ImageProcessor.Web.Episerver")] [assembly: AssemblyCopyright("Copyright 2019")] [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("2edae29a-d622-4b01-8853-d26f4d1c0fd8")] // 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.0.0")] [assembly: AssemblyVersion("5.3.1.*")] [assembly: AssemblyFileVersion("5.3.1.0")]
mit
C#
8dead6e837f9c6ef0ef8cd873b0f808e897634ed
add example
corngood/omnisharp-server,svermeulen/omnisharp-server,x335/omnisharp-server,corngood/omnisharp-server,x335/omnisharp-server,syl20bnr/omnisharp-server,OmniSharp/omnisharp-server,syl20bnr/omnisharp-server,mispencer/OmniSharpServer
OmniSharp/Solution/StringExtensions.cs
OmniSharp/Solution/StringExtensions.cs
using System; using System.IO; using System.Text.RegularExpressions; namespace OmniSharp.Solution { public static class StringExtensions { /// <example> /// " " -> " ". /// "foo \n bar" -> "foo bar". /// </example> public static string MultipleWhitespaceCharsToSingleSpace (this string stringToTrim) { return Regex.Replace(stringToTrim, @"\s+", " "); } /// <summary> /// Changes a path's directory separator from Windows-style to the native /// separator if necessary and expands it to the full path name. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string FixPath(this string path) { if (Path.DirectorySeparatorChar != '\\') path = path.Replace('\\', Path.DirectorySeparatorChar); else // TODO: fix hack - vim sends drive letter as uppercase. usually lower case in project files return path.Replace(@"C:\", @"c:\").Replace(@"D:\", @"d:\"); return Path.GetFullPath(path); } /// <summary> /// Returns the relative path of a file to another file /// </summary> /// <param name="path">Base path to create relative path</param> /// <param name="pathToMakeRelative">Path of file to make relative against path</param> /// <returns></returns> public static string GetRelativePath(this string path, string pathToMakeRelative) { return new Uri(path).MakeRelativeUri(new Uri(pathToMakeRelative)).ToString().Replace("/", @"\"); } } }
using System; using System.IO; using System.Text.RegularExpressions; namespace OmniSharp.Solution { public static class StringExtensions { public static string MultipleWhitespaceCharsToSingleSpace (this string stringToTrim) { return Regex.Replace(stringToTrim, @"\s+", " "); } /// <summary> /// Changes a path's directory separator from Windows-style to the native /// separator if necessary and expands it to the full path name. /// </summary> /// <param name="path"></param> /// <returns></returns> public static string FixPath(this string path) { if (Path.DirectorySeparatorChar != '\\') path = path.Replace('\\', Path.DirectorySeparatorChar); else // TODO: fix hack - vim sends drive letter as uppercase. usually lower case in project files return path.Replace(@"C:\", @"c:\").Replace(@"D:\", @"d:\"); return Path.GetFullPath(path); } /// <summary> /// Returns the relative path of a file to another file /// </summary> /// <param name="path">Base path to create relative path</param> /// <param name="pathToMakeRelative">Path of file to make relative against path</param> /// <returns></returns> public static string GetRelativePath(this string path, string pathToMakeRelative) { return new Uri(path).MakeRelativeUri(new Uri(pathToMakeRelative)).ToString().Replace("/", @"\"); } } }
mit
C#
55aec0bf07a1075f06e61424c177404a1b5d2e1f
Make sure the install doesn't fail if the user opts out of a custom machine key
umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,NikRimington/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS
src/Umbraco.Web/Install/InstallSteps/ConfigureMachineKey.cs
src/Umbraco.Web/Install/InstallSteps/ConfigureMachineKey.cs
using System.Linq; using System.Threading.Tasks; using System.Web.Configuration; using System.Xml.Linq; using Umbraco.Core.IO; using Umbraco.Core.Security; using Umbraco.Web.Install.Models; namespace Umbraco.Web.Install.InstallSteps { [InstallSetupStep(InstallationType.NewInstall, "ConfigureMachineKey", "machinekey", 2, "Updating some security settings...", PerformsAppRestart = true)] internal class ConfigureMachineKey : InstallSetupStep<bool?> { public override string View => HasMachineKey() == false ? base.View : ""; /// <summary> /// Don't display the view or execute if a machine key already exists /// </summary> /// <returns></returns> private static bool HasMachineKey() { var section = (MachineKeySection) WebConfigurationManager.GetSection("system.web/machineKey"); return section.ElementInformation.Source != null; } /// <summary> /// The step execution method /// </summary> /// <param name="model"></param> /// <returns></returns> public override Task<InstallSetupResult> ExecuteAsync(bool? model) { if (model.HasValue && model.Value == false) return Task.FromResult<InstallSetupResult>(null); //install the machine key var fileName = IOHelper.MapPath($"{SystemDirectories.Root}/web.config"); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var systemWeb = xml.Root.DescendantsAndSelf("system.web").Single(); // Update appSetting if it exists, or else create a new appSetting for the given key and value var machineKey = systemWeb.Descendants("machineKey").FirstOrDefault(); if (machineKey != null) return Task.FromResult<InstallSetupResult>(null); var generator = new MachineKeyGenerator(); var generatedSection = generator.GenerateConfigurationBlock(); systemWeb.Add(XElement.Parse(generatedSection)); xml.Save(fileName, SaveOptions.DisableFormatting); return Task.FromResult<InstallSetupResult>(null); } public override bool RequiresExecution(bool? model) { return HasMachineKey() == false; } } }
using System.Linq; using System.Threading.Tasks; using System.Web.Configuration; using System.Xml.Linq; using Umbraco.Core.IO; using Umbraco.Core.Security; using Umbraco.Web.Install.Models; namespace Umbraco.Web.Install.InstallSteps { [InstallSetupStep(InstallationType.NewInstall, "ConfigureMachineKey", "machinekey", 2, "Updating some security settings...", PerformsAppRestart = true)] internal class ConfigureMachineKey : InstallSetupStep<bool?> { public override string View => HasMachineKey() == false ? base.View : ""; /// <summary> /// Don't display the view or execute if a machine key already exists /// </summary> /// <returns></returns> private static bool HasMachineKey() { var section = (MachineKeySection) WebConfigurationManager.GetSection("system.web/machineKey"); return section.ElementInformation.Source != null; } /// <summary> /// The step execution method /// </summary> /// <param name="model"></param> /// <returns></returns> public override Task<InstallSetupResult> ExecuteAsync(bool? model) { if (model.HasValue && model.Value == false) return null; //install the machine key var fileName = IOHelper.MapPath($"{SystemDirectories.Root}/web.config"); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var systemWeb = xml.Root.DescendantsAndSelf("system.web").Single(); // Update appSetting if it exists, or else create a new appSetting for the given key and value var machineKey = systemWeb.Descendants("machineKey").FirstOrDefault(); if (machineKey != null) return null; var generator = new MachineKeyGenerator(); var generatedSection = generator.GenerateConfigurationBlock(); systemWeb.Add(XElement.Parse(generatedSection)); xml.Save(fileName, SaveOptions.DisableFormatting); return Task.FromResult<InstallSetupResult>(null); } public override bool RequiresExecution(bool? model) { return HasMachineKey() == false; } } }
mit
C#
6e56c0daabf15463328bdccadf23dfd19f2d2e93
Bump version to 0.13.0.0
github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,mpOzelot/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")] [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.13.0.0"; } }
#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")] [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.12.0.0"; } }
mit
C#
36dc83641e0f8e8e36235d40bef291c7f43924a3
Set module group to use a nested path, Thirdparty/TinyXML2
markfinal/bam-xml,markfinal/bam-xml,markfinal/bam-xml
packages/tinyxml2-3.0.0/bam/Scripts/TinyXML2.cs
packages/tinyxml2-3.0.0/bam/Scripts/TinyXML2.cs
#region License // Copyright (c) 2010-2015, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace TinyXML2 { [Bam.Core.ModuleGroup("Thirdparty/TinyXML2")] sealed class TinyXML2Static : C.StaticLibrary { protected override void Init( Bam.Core.Module parent) { base.Init(parent); this.CreateHeaderContainer("$(packagedir)/*.h"); this.CreateCxxSourceContainer("$(packagedir)/tinyxml2.cpp"); this.PublicPatch((settings, appliedTo) => { var compiler = settings as C.ICommonCompilerSettings; if (null != compiler) { compiler.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)")); } }); } } }
#region License // Copyright (c) 2010-2015, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace TinyXML2 { [Bam.Core.ModuleGroup("Thirdparty")] sealed class TinyXML2Static : C.StaticLibrary { protected override void Init( Bam.Core.Module parent) { base.Init(parent); this.CreateHeaderContainer("$(packagedir)/*.h"); this.CreateCxxSourceContainer("$(packagedir)/tinyxml2.cpp"); this.PublicPatch((settings, appliedTo) => { var compiler = settings as C.ICommonCompilerSettings; if (null != compiler) { compiler.IncludePaths.AddUnique(this.CreateTokenizedString("$(packagedir)")); } }); } } }
bsd-3-clause
C#
04b2b56690a55852f61e02c498c40df749359369
Fix temporary models for relations.
peeedge/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,peeedge/mobile
Phoebe/Data/ForeignKeyJsonConverter.cs
Phoebe/Data/ForeignKeyJsonConverter.cs
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
bsd-3-clause
C#
46e684904cdcb325ef07ed47c82fe7dc179c987f
Fix Message Handler
quasar/QuasarRAT,quasar/QuasarRAT
Quasar.Common/Messages/MessageHandler.cs
Quasar.Common/Messages/MessageHandler.cs
using Quasar.Common.Networking; using System.Collections.Generic; using System.Linq; namespace Quasar.Common.Messages { /// <summary> /// Handles registration of <see cref="IMessageProcessor"/>s and processing of <see cref="IMessage"/>s. /// </summary> public static class MessageHandler { /// <summary> /// Thread-safe list of registered <see cref="IMessageProcessor"/>s. /// </summary> private static readonly List<IMessageProcessor> Processors = new List<IMessageProcessor>(); /// <summary> /// Used in lock statements to synchronize access between threads. /// </summary> private static readonly object SyncLock = new object(); /// <summary> /// Registers a <see cref="IMessageProcessor"/> to the available <see cref="Processors"/>. /// </summary> /// <param name="proc">The <see cref="IMessageProcessor"/> to register.</param> public static void Register(IMessageProcessor proc) { lock (SyncLock) { if (Processors.Contains(proc)) return; Processors.Add(proc); } } /// <summary> /// Unregisters a <see cref="IMessageProcessor"/> from the available <see cref="Processors"/>. /// </summary> /// <param name="proc"></param> public static void Unregister(IMessageProcessor proc) { lock (SyncLock) { Processors.Remove(proc); } } /// <summary> /// Forwards the received <see cref="IMessage"/> to the appropriate <see cref="IMessageProcessor"/>s to execute it. /// </summary> /// <param name="sender">The sender of the message.</param> /// <param name="msg">The received message.</param> public static void Process(ISender sender, IMessage msg) { IEnumerable<IMessageProcessor> availableProcessors; lock (SyncLock) { // select appropriate message processors availableProcessors = Processors.Where(x => x.CanExecute(msg) && x.CanExecuteFrom(sender)).ToList(); // ToList() is required to retrieve a thread-safe enumerator representing a moment-in-time snapshot of the message processors } foreach (var executor in availableProcessors) executor.Execute(sender, msg); } } }
using Quasar.Common.Networking; using System.Collections.Concurrent; using System.Linq; namespace Quasar.Common.Messages { /// <summary> /// Handles registration of <see cref="IMessageProcessor"/>s and processing of <see cref="IMessage"/>s. /// </summary> public static class MessageHandler { /// <summary> /// Unordered thread-safe list of registered <see cref="IMessageProcessor"/>s. /// </summary> private static readonly ConcurrentBag<IMessageProcessor> Processors = new ConcurrentBag<IMessageProcessor>(); /// <summary> /// Registers a <see cref="IMessageProcessor"/> to the available <see cref="Processors"/>. /// </summary> /// <param name="proc">The <see cref="IMessageProcessor"/> to register.</param> public static void Register(IMessageProcessor proc) { if (Processors.Contains(proc)) return; Processors.Add(proc); } /// <summary> /// Unregisters a <see cref="IMessageProcessor"/> from the available <see cref="Processors"/>. /// </summary> /// <param name="proc"></param> public static void Unregister(IMessageProcessor proc) { if (!Processors.Contains(proc)) return; Processors.TryTake(out proc); } /// <summary> /// Forwards the received <see cref="IMessage"/> to the appropriate <see cref="IMessageProcessor"/>s to execute it. /// </summary> /// <param name="sender">The sender of the message.</param> /// <param name="msg">The received message.</param> public static void Process(ISender sender, IMessage msg) { // select appropriate message processors var availableExecutors = Processors.Where(x => x.CanExecute(msg) && x.CanExecuteFrom(sender)); foreach (var executor in availableExecutors) executor.Execute(sender, msg); } } }
mit
C#
9c03b88419b086b728321db113da1031740c2339
Use explicit IEnumerable.
jesterret/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET,KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET
ReClass.NET/Forms/EnumSelectionForm.cs
ReClass.NET/Forms/EnumSelectionForm.cs
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Windows.Forms; using ReClassNET.Project; using ReClassNET.UI; namespace ReClassNET.Forms { public partial class EnumSelectionForm : IconForm { private readonly ReClassNetProject project; public EnumDescription SelectedItem => itemListBox.SelectedItem as EnumDescription; public EnumSelectionForm(ReClassNetProject project) { Contract.Requires(project != null); this.project = project; InitializeComponent(); ShowFilteredEnums(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GlobalWindowManager.AddWindow(this); } protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e); GlobalWindowManager.RemoveWindow(this); } private void filterNameTextBox_TextChanged(object sender, EventArgs e) { ShowFilteredEnums(); } private void itemListBox_SelectedIndexChanged(object sender, EventArgs e) { selectButton.Enabled = editEnumIconButton.Enabled = removeEnumIconButton.Enabled = SelectedItem != null; } private void editEnumIconButton_Click(object sender, EventArgs e) { var @enum = SelectedItem; if (@enum == null) { return; } using (var eef = new EnumEditorForm(@enum)) { eef.ShowDialog(); } } private void addEnumIconButton_Click(object sender, EventArgs e) { var @enum = new EnumDescription { Name = "Enum" }; using (var eef = new EnumEditorForm(@enum)) { if (eef.ShowDialog() == DialogResult.OK) { project.AddEnum(@enum); ShowFilteredEnums(); } } } private void removeEnumIconButton_Click(object sender, EventArgs e) { var @enum = SelectedItem; if (@enum == null) { return; } project.RemoveEnum(@enum); ShowFilteredEnums(); } private void ShowFilteredEnums() { IEnumerable<EnumDescription> enums = project.Enums; if (!string.IsNullOrEmpty(filterNameTextBox.Text)) { enums = enums.Where(c => c.Name.IndexOf(filterNameTextBox.Text, StringComparison.OrdinalIgnoreCase) >= 0); } itemListBox.DataSource = enums.ToList(); } } }
using System; using System.Diagnostics.Contracts; using System.Linq; using System.Windows.Forms; using ReClassNET.Project; using ReClassNET.UI; namespace ReClassNET.Forms { public partial class EnumSelectionForm : IconForm { private readonly ReClassNetProject project; public EnumDescription SelectedItem => itemListBox.SelectedItem as EnumDescription; public EnumSelectionForm(ReClassNetProject project) { Contract.Requires(project != null); this.project = project; InitializeComponent(); ShowFilteredEnums(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); GlobalWindowManager.AddWindow(this); } protected override void OnFormClosed(FormClosedEventArgs e) { base.OnFormClosed(e); GlobalWindowManager.RemoveWindow(this); } private void filterNameTextBox_TextChanged(object sender, EventArgs e) { ShowFilteredEnums(); } private void itemListBox_SelectedIndexChanged(object sender, EventArgs e) { selectButton.Enabled = editEnumIconButton.Enabled = removeEnumIconButton.Enabled = SelectedItem != null; } private void editEnumIconButton_Click(object sender, EventArgs e) { var @enum = SelectedItem; if (@enum == null) { return; } using (var eef = new EnumEditorForm(@enum)) { eef.ShowDialog(); } } private void addEnumIconButton_Click(object sender, EventArgs e) { var @enum = new EnumDescription { Name = "Enum" }; using (var eef = new EnumEditorForm(@enum)) { if (eef.ShowDialog() == DialogResult.OK) { project.AddEnum(@enum); ShowFilteredEnums(); } } } private void removeEnumIconButton_Click(object sender, EventArgs e) { var @enum = SelectedItem; if (@enum == null) { return; } project.RemoveEnum(@enum); ShowFilteredEnums(); } private void ShowFilteredEnums() { var enums = project.Enums; if (!string.IsNullOrEmpty(filterNameTextBox.Text)) { enums = enums.Where(c => c.Name.IndexOf(filterNameTextBox.Text, StringComparison.OrdinalIgnoreCase) >= 0); } itemListBox.DataSource = enums.ToList(); } } }
mit
C#
c9b7874c3eb26249767260740998ec50bf210b02
Update MultiDriverTests
YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata
src/Atata.Tests/MultiDriverTests.cs
src/Atata.Tests/MultiDriverTests.cs
using System; using FluentAssertions; using NUnit.Framework; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.IE; namespace Atata.Tests { [TestFixture(DriverAliases.Chrome)] [TestFixture(DriverAliases.InternetExplorer)] public class MultiDriverTests : UITestFixtureBase { private readonly string driverAlias; public MultiDriverTests(string driverAlias) { this.driverAlias = driverAlias; } [SetUp] public void SetUp() { ConfigureBaseAtataContext(). UseInternetExplorer(). #if NETCOREAPP2_0 WithFixOfCommandExecutionDelay(). WithLocalDriverPath(). #endif UseDriver(driverAlias). UseTestName(() => $"[{driverAlias}]{TestContext.CurrentContext.Test.Name}"). Build(); } [TestCase(4)] [TestCase(8)] public void MultiDriver_WithParameter(int parameter) { AtataContext.Current.Log.Info($"Driver alias: {driverAlias}"); AtataContext.Current.Log.Info($"Parameter value: {parameter}"); AtataContext.Current.DriverAlias.Should().Be(driverAlias); AtataContext.Current.Driver.Should().BeOfType(GetDriverTypeByAlias(driverAlias)); } private static Type GetDriverTypeByAlias(string driverAlias) { switch (driverAlias) { case DriverAliases.Chrome: return typeof(ChromeDriver); case DriverAliases.InternetExplorer: return typeof(InternetExplorerDriver); default: throw new ArgumentException($"Unexpected \"{driverAlias}\" value.", nameof(driverAlias)); } } } }
using NUnit.Framework; namespace Atata.Tests { [TestFixture(DriverAliases.Chrome)] [TestFixture(DriverAliases.InternetExplorer)] public class MultiDriverTests { private readonly string driverAlias; public MultiDriverTests(string driverAlias) { this.driverAlias = driverAlias; } [SetUp] public void SetUp() { AtataContext.Configure(). #if NETCOREAPP2_0 UseChrome(). WithFixOfCommandExecutionDelay(). WithLocalDriverPath(). UseInternetExplorer(). WithFixOfCommandExecutionDelay(). WithLocalDriverPath(). #endif UseDriver(driverAlias). UseTestName(() => $"[{driverAlias}]{TestContext.CurrentContext.Test.Name}"). AddNUnitTestContextLogging(). LogNUnitError(). Build(); } [TearDown] public void TearDown() { AtataContext.Current.CleanUp(); } [TestCase(4)] [TestCase(8)] public void MultiDriver_WithParameter(int parameter) { AtataContext.Current.Log.Info($"Driver alias: {driverAlias}"); AtataContext.Current.Log.Info($"Parameter value: {parameter}"); } } }
apache-2.0
C#
315abf4bb95661793aad9555d5144bdc9ef7a9b5
Fix OnReceiveMessage subscribe
Nirklav/ScreenshotPlugin
ScreenShotPlugin/ScreenClientPlugin.cs
ScreenShotPlugin/ScreenClientPlugin.cs
using Engine; using Engine.Model.Client; using Engine.Model.Common; using Engine.Model.Entities; using Engine.Model.Server; using Engine.Plugins; using Engine.Plugins.Client; using System; using System.Collections.Generic; using System.IO; namespace ScreenshotPlugin { public class ScreenClientPlugin : ClientPlugin { private List<ClientPluginCommand> commands; private IClientNotifierContext notifier; private static List<string> downloadingFiles; #region ClientPlugin protected override void Initialize() { downloadingFiles = new List<string>(); notifier = NotifierGenerator.MakeContext<IClientNotifierContext>(); notifier.ReceiveMessage += OnReceiveMessage; commands = new List<ClientPluginCommand> { new ClientMakeScreenCommand(), new ClientScreenDoneCommand() }; } public override void InvokeMenuHandler() { var dialog = new PluginDialog(); dialog.ShowDialog(); } public override string Name { get { return "ScreenClientPlugin"; } } public override string MenuCaption { get { return "Сделать скриншот"; } } public override CrossDomainObject NotifierContext { get { return (CrossDomainObject) notifier; } } public override List<ClientPluginCommand> Commands { get { return commands; } } #endregion private void OnReceiveMessage(object sender, ReceiveMessageEventArgs args) { if (args.Type != MessageType.File) return; var file = args.State as FileDescription; if (file == null) return; var downaladDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "downloads"); if (!Directory.Exists(downaladDirectory)) Directory.CreateDirectory(downaladDirectory); var path = Path.Combine(downaladDirectory, file.Name); if (ScreenClientPlugin.NeedDownload(file.Name)) { ScreenClientPlugin.RemoveFile(file.Name); ScreenClientPlugin.Model.API.DownloadFile(path, ServerModel.MainRoomName, file); } } public static void AddFile(string fileName) { lock (downloadingFiles) downloadingFiles.Add(fileName); } public static void RemoveFile(string fileName) { lock (downloadingFiles) downloadingFiles.Remove(fileName); } public static bool NeedDownload(string fileName) { lock (downloadingFiles) return downloadingFiles.Contains(fileName); } } }
using Engine; using Engine.Model.Client; using Engine.Model.Common; using Engine.Model.Entities; using Engine.Model.Server; using Engine.Plugins; using Engine.Plugins.Client; using System; using System.Collections.Generic; using System.IO; namespace ScreenshotPlugin { public class ScreenClientPlugin : ClientPlugin { private List<ClientPluginCommand> commands; private IClientNotifierContext notifier; private static List<string> downloadingFiles; #region ClientPlugin protected override void Initialize() { downloadingFiles = new List<string>(); notifier = NotifierGenerator.MakeContext<IClientNotifierContext>(); commands = new List<ClientPluginCommand> { new ClientMakeScreenCommand(), new ClientScreenDoneCommand() }; } public override void InvokeMenuHandler() { var dialog = new PluginDialog(); dialog.ShowDialog(); } public override string Name { get { return "ScreenClientPlugin"; } } public override string MenuCaption { get { return "Сделать скриншот"; } } public override CrossDomainObject NotifierContext { get { return (CrossDomainObject) notifier; } } public override List<ClientPluginCommand> Commands { get { return commands; } } #endregion private void OnReceiveMessage(ReceiveMessageEventArgs args) { if (args.Type != MessageType.File) return; var file = args.State as FileDescription; if (file == null) return; var downaladDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "downloads"); if (!Directory.Exists(downaladDirectory)) Directory.CreateDirectory(downaladDirectory); var path = Path.Combine(downaladDirectory, file.Name); if (ScreenClientPlugin.NeedDownload(file.Name)) { ScreenClientPlugin.RemoveFile(file.Name); ScreenClientPlugin.Model.API.DownloadFile(path, ServerModel.MainRoomName, file); } } public static void AddFile(string fileName) { lock (downloadingFiles) downloadingFiles.Add(fileName); } public static void RemoveFile(string fileName) { lock (downloadingFiles) downloadingFiles.Remove(fileName); } public static bool NeedDownload(string fileName) { lock (downloadingFiles) return downloadingFiles.Contains(fileName); } } }
mit
C#
4260a662abc3a9ef031913a354f7da547838f89f
Fix routes
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
src/LondonTravel.Site/SiteRoutes.cs
src/LondonTravel.Site/SiteRoutes.cs
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site; /// <summary> /// A class containing the names of the routes for the site. This class cannot be inherited. /// </summary> public static class SiteRoutes { public const string Account = nameof(Account); public const string AuthorizeAlexa = nameof(AuthorizeAlexa); public const string DeleteAccount = nameof(DeleteAccount); public const string ExternalSignIn = nameof(ExternalSignIn); public const string ExternalSignInCallback = nameof(ExternalSignInCallback); public const string Help = "/Help/Index"; public const string Home = nameof(Home); public const string LinkAccount = nameof(LinkAccount); public const string LinkAccountCallback = nameof(LinkAccountCallback); public const string Manage = nameof(Manage); public const string PrivacyPolicy = "/PrivacyPolicy/Index"; public const string Register = "/Account/Register"; public const string RemoveAccountLink = nameof(RemoveAccountLink); public const string RemoveAlexaLink = nameof(RemoveAlexaLink); public const string SignIn = nameof(SignIn); public const string SignOut = nameof(SignOut); public const string Technology = "/Technology/Index"; public const string TermsOfService = "/Terms/Index"; public const string UpdateLinePreferences = nameof(UpdateLinePreferences); }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site; /// <summary> /// A class containing the names of the routes for the site. This class cannot be inherited. /// </summary> public static class SiteRoutes { public const string Account = nameof(Account); public const string AuthorizeAlexa = nameof(AuthorizeAlexa); public const string DeleteAccount = nameof(DeleteAccount); public const string ExternalSignIn = nameof(ExternalSignIn); public const string ExternalSignInCallback = nameof(ExternalSignInCallback); public const string Help = "/Help"; public const string Home = nameof(Home); public const string LinkAccount = nameof(LinkAccount); public const string LinkAccountCallback = nameof(LinkAccountCallback); public const string Manage = nameof(Manage); public const string PrivacyPolicy = "/PrivacyPolicy"; public const string Register = "/Account/Register"; public const string RemoveAccountLink = nameof(RemoveAccountLink); public const string RemoveAlexaLink = nameof(RemoveAlexaLink); public const string SignIn = nameof(SignIn); public const string SignOut = nameof(SignOut); public const string Technology = "/Technology"; public const string TermsOfService = "/Terms"; public const string UpdateLinePreferences = nameof(UpdateLinePreferences); }
apache-2.0
C#
9ba37ffa9d79fd108c11bb2116688622d9bf4acc
Remove commented code.
affecto/dotnet-AuthenticationServer
Source/AuthenticationServer/Startup.cs
Source/AuthenticationServer/Startup.cs
using Affecto.AuthenticationServer.Configuration; using Affecto.Logging; using Autofac; using IdentityServer3.Core.Configuration; using IdentityServer3.Core.Services; using Owin; namespace Affecto.AuthenticationServer { public class Startup { public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterModule<AuthenticationServerModule>(); IContainer container = builder.Build(); ILoggerFactory loggerFactory = container.Resolve<ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(this); logger.LogVerbose("Initializing AuthenticationServer. This is required for IdentityServer logging to work. Do not remove this!"); app.Map("/core", coreApp => { IAuthenticationServerConfiguration configuration = container.Resolve<IAuthenticationServerConfiguration>(); var serviceFactory = new IdentityServerServiceFactory() .UseInMemoryClients(configuration.Clients.MapToIdentityServerClients()) .UseInMemoryScopes(configuration.Scopes.MapToIdentityServerScopes()); serviceFactory.UserService = new Registration<IUserService>(resolver => container.Resolve<IUserService>()); serviceFactory.CorsPolicyService = new Registration<ICorsPolicyService>(CorsPolicyServiceFactory.Create(configuration)); coreApp.UseIdentityServer(IdentityServerOptionsFactory.Create(configuration, serviceFactory)); }); } } }
using Affecto.AuthenticationServer.Configuration; using Affecto.Logging; using Autofac; using IdentityServer3.Core.Configuration; using IdentityServer3.Core.Services; using Owin; namespace Affecto.AuthenticationServer { public class Startup { public void Configuration(IAppBuilder app) { var builder = new ContainerBuilder(); builder.RegisterModule<AuthenticationServerModule>(); IContainer container = builder.Build(); ILoggerFactory loggerFactory = container.Resolve<ILoggerFactory>(); ILogger logger = loggerFactory.CreateLogger(this); logger.LogVerbose("Initializing AuthenticationServer. This is required for IdentityServer logging to work. Do not remove this!"); // todo: is this needed? Doesn't compile //app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.Map("/core", coreApp => { IAuthenticationServerConfiguration configuration = container.Resolve<IAuthenticationServerConfiguration>(); var serviceFactory = new IdentityServerServiceFactory() .UseInMemoryClients(configuration.Clients.MapToIdentityServerClients()) .UseInMemoryScopes(configuration.Scopes.MapToIdentityServerScopes()); serviceFactory.UserService = new Registration<IUserService>(resolver => container.Resolve<IUserService>()); serviceFactory.CorsPolicyService = new Registration<ICorsPolicyService>(CorsPolicyServiceFactory.Create(configuration)); coreApp.UseIdentityServer(IdentityServerOptionsFactory.Create(configuration, serviceFactory)); }); } } }
mit
C#
84542224655e4cca68987cf49c0ba317270eaa95
Add anomaly type
Kerbas-ad-astra/Orbital-Science,DMagic1/Orbital-Science
Source/Contracts/DMScienceContainer.cs
Source/Contracts/DMScienceContainer.cs
#region license /* DMagic Orbital Science - DMScienceContainer * Object to store experiment properties * * Copyright (c) 2014, David Grandy <david.grandy@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #endregion namespace DMagic { internal class DMScienceContainer { internal int sitMask, bioMask; internal DMScienceType type; internal ScienceExperiment exp; internal string sciPart, agent; internal DMScienceContainer(ScienceExperiment sciExp, int sciSitMask, int sciBioMask, DMScienceType Type, string sciPartID, string agentName) { sitMask = sciSitMask; bioMask = sciBioMask; exp = sciExp; sciPart = sciPartID; agent = agentName; type = Type; } } internal enum DMScienceType { None = 0, Surface = 1, Aerial = 2, Space = 4, Biological = 8, Asteroid = 16, Anomaly = 32, } }
#region license /* DMagic Orbital Science - DMScienceContainer * Object to store experiment properties * * Copyright (c) 2014, David Grandy <david.grandy@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #endregion namespace DMagic { internal class DMScienceContainer { internal int sitMask, bioMask; internal DMScienceType type; internal ScienceExperiment exp; internal string sciPart, agent; internal DMScienceContainer(ScienceExperiment sciExp, int sciSitMask, int sciBioMask, DMScienceType Type, string sciPartID, string agentName) { sitMask = sciSitMask; bioMask = sciBioMask; exp = sciExp; sciPart = sciPartID; agent = agentName; type = Type; } } internal enum DMScienceType { None = 0, Surface = 1, Aerial = 2, Space = 4, Biological = 8, Asteroid = 16, } }
bsd-3-clause
C#
3b9e8b3bb4b3ac2aab91c43b06856340ebe7e00e
Update CanonicalUrlAttribute.cs
Gibe/Gibe.DittoProcessors
Gibe.DittoProcessors/Processors/CanonicalUrlAttribute.cs
Gibe.DittoProcessors/Processors/CanonicalUrlAttribute.cs
using Umbraco.Core; using Umbraco.Web; namespace Gibe.DittoProcessors.Processors { public class CanonicalUrlAttribute : TestableDittoProcessorAttribute { private string _homeDocTypeAlias; public CanonicalUrlAttribute(string homeDocTypeAlias = "home") { _homeDocTypeAlias = homeDocTypeAlias; } public override object ProcessValue() => Context.Content.DocumentTypeAlias.InvariantEquals(_homeDocTypeAlias) ? Context.Content.UrlAbsolute().Replace(Context.Content.Url, "/") : Context.Content.UrlAbsolute(); } }
using Umbraco.Core; using Umbraco.Web; namespace Gibe.DittoProcessors.Processors { public class CanonicalUrlAttribute : TestableDittoProcessorAttribute { public override object ProcessValue() => Context.Content.DocumentTypeAlias.InvariantEquals("home") ? Context.Content.UrlAbsolute().Replace(Context.Content.Url, "/") : Context.Content.UrlAbsolute(); } }
mit
C#
96a9e1e6b95b456e614d8d3a2c6647bb0ce1bd5d
add in test for throwing property
Pondidum/Stronk,Pondidum/Stronk
src/Stronk.Tests/AcceptanceTests.cs
src/Stronk.Tests/AcceptanceTests.cs
using System; using System.Configuration; using Shouldly; using Stronk.Policies; using Xunit; #pragma warning disable 649 namespace Stronk.Tests { public class AcceptanceTests { [Fact] public void When_loading_the_configuration_to_private_setters() { var config = new ConfigWithPrivateSetters(); config.FromAppConfig(); var appSettings = ConfigurationManager.AppSettings; var connectionStrings = ConfigurationManager.ConnectionStrings; config.ShouldSatisfyAllConditions( () => config.Name.ShouldBe(appSettings["Name"]), () => config.Version.ShouldBe(Convert.ToInt32(appSettings["Version"])), () => config.Environment.ShouldBe((TargetEnvironment)Enum.Parse(typeof(TargetEnvironment), appSettings["Environment"], true)), () => config.Endpoint.ShouldBe(new Uri(appSettings["Endpoint"])), () => config.DefaultDB.ShouldBe(connectionStrings["DefaultDB"].ConnectionString) ); } [Fact] public void When_loading_the_configuration_to_backing_fields() { var config = new ConfigWithBackingFields(); config.FromAppConfig(); var appSettings = ConfigurationManager.AppSettings; var connectionStrings = ConfigurationManager.ConnectionStrings; config.ShouldSatisfyAllConditions( () => config.Name.ShouldBe(appSettings["Name"]), () => config.Version.ShouldBe(Convert.ToInt32(appSettings["Version"])), () => config.Environment.ShouldBe((TargetEnvironment)Enum.Parse(typeof(TargetEnvironment), appSettings["Environment"], true)), () => config.Endpoint.ShouldBe(new Uri(appSettings["Endpoint"])), () => config.DefaultDB.ShouldBe(connectionStrings["DefaultDB"].ConnectionString) ); } [Fact] public void When_loading_the_configuration_and_a_property_throws() { var config = new ThrowingSetter(); Should.Throw<ValueConversionException>(() => config.FromWebConfig()); } public class ThrowingSetter { private string _name; public string Name { get { return _name; } set { throw new NotFiniteNumberException(); } } } public class ConfigWithPrivateSetters { public string Name { get; private set; } public int Version { get; private set; } public Uri Endpoint { get; private set; } public TargetEnvironment Environment { get; private set; } public string DefaultDB { get; private set; } } public class ConfigWithBackingFields { private string _name; private int _version; private Uri _endpoint; private TargetEnvironment _environment; private string _defaultDB; public string Name => _name; public int Version => _version; public Uri Endpoint => _endpoint; public TargetEnvironment Environment => _environment; public string DefaultDB => _defaultDB; } public enum TargetEnvironment { Dev, Test, ExternalTest, QA, Production } } }
using System; using System.Configuration; using Shouldly; using Xunit; #pragma warning disable 649 namespace Stronk.Tests { public class AcceptanceTests { [Fact] public void When_loading_the_configuration_to_private_setters() { var config = new ConfigWithPrivateSetters(); config.FromAppConfig(); var appSettings = ConfigurationManager.AppSettings; var connectionStrings = ConfigurationManager.ConnectionStrings; config.ShouldSatisfyAllConditions( () => config.Name.ShouldBe(appSettings["Name"]), () => config.Version.ShouldBe(Convert.ToInt32(appSettings["Version"])), () => config.Environment.ShouldBe((TargetEnvironment)Enum.Parse(typeof(TargetEnvironment), appSettings["Environment"], true)), () => config.Endpoint.ShouldBe(new Uri(appSettings["Endpoint"])), () => config.DefaultDB.ShouldBe(connectionStrings["DefaultDB"].ConnectionString) ); } [Fact] public void When_loading_the_configuration_to_backing_fields() { var config = new ConfigWithBackingFields(); config.FromAppConfig(); var appSettings = ConfigurationManager.AppSettings; var connectionStrings = ConfigurationManager.ConnectionStrings; config.ShouldSatisfyAllConditions( () => config.Name.ShouldBe(appSettings["Name"]), () => config.Version.ShouldBe(Convert.ToInt32(appSettings["Version"])), () => config.Environment.ShouldBe((TargetEnvironment)Enum.Parse(typeof(TargetEnvironment), appSettings["Environment"], true)), () => config.Endpoint.ShouldBe(new Uri(appSettings["Endpoint"])), () => config.DefaultDB.ShouldBe(connectionStrings["DefaultDB"].ConnectionString) ); } public class ConfigWithPrivateSetters { public string Name { get; private set; } public int Version { get; private set; } public Uri Endpoint { get; private set; } public TargetEnvironment Environment { get; private set; } public string DefaultDB { get; private set; } } public class ConfigWithBackingFields { private string _name; private int _version; private Uri _endpoint; private TargetEnvironment _environment; private string _defaultDB; public string Name => _name; public int Version => _version; public Uri Endpoint => _endpoint; public TargetEnvironment Environment => _environment; public string DefaultDB => _defaultDB; } public enum TargetEnvironment { Dev, Test, ExternalTest, QA, Production } } }
lgpl-2.1
C#
702839b199a36d0aa69d27b6dd87d7e1ef0c14aa
fix method name (GetALlPOIs to GetAllPOIs)
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
MobileApp/smarttripsService/Controllers/POIController.cs
MobileApp/smarttripsService/Controllers/POIController.cs
using Microsoft.Azure.Mobile.Server; using MyTrips.DataObjects; using smarttripsService.Helpers; using smarttripsService.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; namespace smarttripsService.Controllers { public class POIController : TableController<POI> { private smarttripsContext _dbContext; protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); _dbContext = new smarttripsContext(); DomainManager = new EntityDomainManager<POI>(_dbContext, Request); } public IQueryable<POI> GetAllPOIs(string tripId) { return Query().Where(p => p.TripId == tripId); } } }
using Microsoft.Azure.Mobile.Server; using MyTrips.DataObjects; using smarttripsService.Helpers; using smarttripsService.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; namespace smarttripsService.Controllers { public class POIController : TableController<POI> { private smarttripsContext _dbContext; protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); _dbContext = new smarttripsContext(); DomainManager = new EntityDomainManager<POI>(_dbContext, Request); } public IQueryable<POI> GetALlPOIs(string tripId) { return Query().Where(p => p.TripId == tripId); } } }
mit
C#
f1f8d3fba8d56987154aaa097014e72b649870cf
Use new intent instead of reusing broadcast one.
eatskolnikov/mobile,masterrr/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile,eatskolnikov/mobile,eatskolnikov/mobile,masterrr/mobile,peeedge/mobile,peeedge/mobile
Joey/Net/GcmBroadcastReceiver.cs
Joey/Net/GcmBroadcastReceiver.cs
using System; using Android.App; using Android.Content; using Android.Support.V4.Content; namespace Toggl.Joey.Net { [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[]{ "com.toggl.timer" })] public class GcmBroadcastReceiver : WakefulBroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var serviceIntent = new Intent (context, typeof(GcmService)); serviceIntent.ReplaceExtras (intent.Extras); StartWakefulService (context, serviceIntent); ResultCode = Result.Ok; } } }
using System; using Android.App; using Android.Content; using Android.Support.V4.Content; namespace Toggl.Joey.Net { [BroadcastReceiver (Permission = "com.google.android.c2dm.permission.SEND")] [IntentFilter (new string[] { "com.google.android.c2dm.intent.RECEIVE" }, Categories = new string[]{ "com.toggl.timer" })] public class GcmBroadcastReceiver : WakefulBroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var comp = new ComponentName (context, Java.Lang.Class.FromType (typeof(GcmService))); StartWakefulService (context, (intent.SetComponent (comp))); ResultCode = Result.Ok; } } }
bsd-3-clause
C#
e58aa595249666dc954c93a7f6f0b61acccc31b7
Bump version
lars-erik/our-umbraco-forms-expressions,lars-erik/our-umbraco-forms-expressions,lars-erik/our-umbraco-forms-expressions
Our.Umbraco.Forms.Expressions/Properties/AssemblyInfo.cs
Our.Umbraco.Forms.Expressions/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("Our.Umbraco.Forms.Expressions")] [assembly: AssemblyDescription("An expression language for Umbraco Forms")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lars-Erik Aabech")] [assembly: AssemblyProduct("Our.Umbraco.Forms.Expressions")] [assembly: AssemblyCopyright("Copyright © Lars-Erik Aabech 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("8676536c-bd0a-4d83-8063-5db932cb61e3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyInformationalVersion("1.0.7-beta")]
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("Our.Umbraco.Forms.Expressions")] [assembly: AssemblyDescription("An expression language for Umbraco Forms")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Lars-Erik Aabech")] [assembly: AssemblyProduct("Our.Umbraco.Forms.Expressions")] [assembly: AssemblyCopyright("Copyright © Lars-Erik Aabech 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("8676536c-bd0a-4d83-8063-5db932cb61e3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyInformationalVersion("1.0.6-beta")]
mit
C#
bc3b0a1f77f509307ae86225eeb3bd4c77f4c5a8
Set character encoding when displaying html from markdown (BL-3785)
ermshiperete/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,tombogle/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,gmartin7/libpalaso
SIL.Windows.Forms/ReleaseNotes/ShowReleaseNotesDialog.cs
SIL.Windows.Forms/ReleaseNotes/ShowReleaseNotesDialog.cs
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using MarkdownDeep; using SIL.IO; namespace SIL.Windows.Forms.ReleaseNotes { /// <summary> /// Shows a dialog for release notes; accepts html and markdown /// </summary> public partial class ShowReleaseNotesDialog : Form { private readonly string _path; private TempFile _temp; private readonly Icon _icon; public ShowReleaseNotesDialog(Icon icon, string path) { _path = path; _icon = icon; InitializeComponent(); } private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, GetBasicHtmlFromMarkdown(md.Transform(contents))); _browser.Url = new Uri(_temp.Path); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // a bug in Mono requires us to wait to set Icon until handle created. Icon = _icon; } private string GetBasicHtmlFromMarkdown(string markdownHtml) { return string.Format("<html><head><meta charset=\"utf-8\"/></head><body>{0}</body></html>", markdownHtml); } } }
using System; using System.Drawing; using System.IO; using System.Windows.Forms; using MarkdownDeep; using SIL.IO; namespace SIL.Windows.Forms.ReleaseNotes { /// <summary> /// Shows a dialog for release notes; accepts html and markdown /// </summary> public partial class ShowReleaseNotesDialog : Form { private readonly string _path; private TempFile _temp; private readonly Icon _icon; public ShowReleaseNotesDialog(Icon icon, string path) { _path = path; _icon = icon; InitializeComponent(); } private void ShowReleaseNotesDialog_Load(object sender, EventArgs e) { string contents = File.ReadAllText(_path); var md = new Markdown(); _temp = TempFile.WithExtension("htm"); //enhance: will leek a file to temp File.WriteAllText(_temp.Path, md.Transform(contents)); _browser.Url = new Uri(_temp.Path); } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); // a bug in Mono requires us to wait to set Icon until handle created. Icon = _icon; } } }
mit
C#
7207c3d58d96b4db0a261fbcb435bfa885257ca5
Refactor logic for thousands (M, MM, MMM).
pvasys/PillarRomanNumeralKata
VasysRomanNumeralsKata/RomanNumeral.cs
VasysRomanNumeralsKata/RomanNumeral.cs
using System; using System.Collections.Generic; using System.Text; namespace VasysRomanNumeralsKata { public class RomanNumeral { private int? _baseTenRepresentation = null; public RomanNumeral(int baseTenNumber) { _baseTenRepresentation = baseTenNumber; } public string GenerateRomanNumeralRepresntation() { StringBuilder romanNumeralBuilder = new StringBuilder(); int remainder = (int)_baseTenRepresentation; while(remainder / 1000 > 0) { romanNumeralBuilder.Append("M"); remainder -= 1000; } if (remainder >= 900) { romanNumeralBuilder.Append("CM"); remainder -= 900; } if(remainder >= 500) { romanNumeralBuilder.Append("D"); remainder -= 500; } if (remainder >= 400) { romanNumeralBuilder.Append("CD"); remainder -= 400; } while(remainder >= 100) { romanNumeralBuilder.Append("C"); remainder -= 100; } int numberOfTens = remainder / 10; if (numberOfTens > 0) { for (int i = 0; i < numberOfTens; i++) { romanNumeralBuilder.Append("X"); } } return romanNumeralBuilder.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace VasysRomanNumeralsKata { public class RomanNumeral { private int? _baseTenRepresentation = null; public RomanNumeral(int baseTenNumber) { _baseTenRepresentation = baseTenNumber; } public string GenerateRomanNumeralRepresntation() { StringBuilder romanNumeralBuilder = new StringBuilder(); int numberOfThousands = (int)_baseTenRepresentation / 1000; if (numberOfThousands > 0) { for(int i = 0; i < numberOfThousands; i++) { romanNumeralBuilder.Append("M"); } } int remainder = (int)_baseTenRepresentation % 1000; if (remainder >= 900) { romanNumeralBuilder.Append("CM"); remainder -= 900; } if(remainder >= 500) { romanNumeralBuilder.Append("D"); remainder -= 500; } if (remainder >= 400) { romanNumeralBuilder.Append("CD"); remainder -= 400; } while(remainder >= 100) { romanNumeralBuilder.Append("C"); remainder -= 100; } int numberOfTens = remainder / 10; if (numberOfTens > 0) { for (int i = 0; i < numberOfTens; i++) { romanNumeralBuilder.Append("X"); } } return romanNumeralBuilder.ToString(); } } }
mit
C#
7140da937ec024e9b0afa495dbe8e91dc6765bd8
Fix build
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer
LmpClient/Harmony/Vessel_Load.cs
LmpClient/Harmony/Vessel_Load.cs
using Harmony; using LmpClient.Systems.SafetyBubble; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to avoid loading a vessel if it's in safety bubble /// </summary> [HarmonyPatch(typeof(Vessel))] [HarmonyPatch("Load")] public class Vessel_Load { [HarmonyPrefix] private static bool PrefixLoad(Vessel __instance) { if (FlightGlobals.ActiveVessel != null && FlightGlobals.ActiveVessel.loaded && FlightGlobals.ActiveVessel.id != __instance.id) { return !SafetyBubbleSystem.Singleton.IsInSafetyBubble(__instance); } return true; } } }
using Harmony; using LmpClient.Systems.SafetyBubble; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to avoid loading a vessel if it's in safety bubble /// </summary> [HarmonyPatch(typeof(Vessel))] [HarmonyPatch("Load")] public class Vessel_Load { [HarmonyPrefix] private static bool PrefixLoad(Vessel __instance) { if (FlightGlobals.ActiveVessel != null && FlightGlobals.ActiveVessel.loaded && FlightGlobals.ActiveVessel.id != __instance.id) { return !SafetyBubbleSystem.Singleton.IsInSafetyBubble(__instance, false); } return true; } } }
mit
C#
c08232c4074160fc677048534b491e733b83a2e5
Update LandscapeFactory.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/Landscapes/LandscapeFactory.cs
src/Landscapes/LandscapeFactory.cs
// Contributors: // James Domingo, Green Code LLC using Landis.SpatialModeling; namespace Landis.Landscapes { public class LandscapeFactory : ILandscapeFactory { /// <summary> /// Creates a new landscape using an input grid of active sites. /// </summary> /// <param name="activeSites"> /// A grid that indicates which sites are active. /// </param> public ILandscape CreateLandscape(IInputGrid<bool> activeSites) { return new Landscape(activeSites); } //--------------------------------------------------------------------- /// <summary> /// Creates a new landscape using an indexable grid of active sites. /// </summary> /// <param name="activeSites"> /// A grid that indicates which sites are active. /// </param> public ILandscape CreateLandscape(IIndexableGrid<bool> activeSites) { return new Landscape(activeSites); } } }
// Copyright 2010 Green Code LLC // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, Green Code LLC using Landis.SpatialModeling; namespace Landis.Landscapes { public class LandscapeFactory : ILandscapeFactory { /// <summary> /// Creates a new landscape using an input grid of active sites. /// </summary> /// <param name="activeSites"> /// A grid that indicates which sites are active. /// </param> public ILandscape CreateLandscape(IInputGrid<bool> activeSites) { return new Landscape(activeSites); } //--------------------------------------------------------------------- /// <summary> /// Creates a new landscape using an indexable grid of active sites. /// </summary> /// <param name="activeSites"> /// A grid that indicates which sites are active. /// </param> public ILandscape CreateLandscape(IIndexableGrid<bool> activeSites) { return new Landscape(activeSites); } } }
apache-2.0
C#
987731eaf1d19e1ee2e3a92241f341a2be840ad0
Add endpoint for metrics
mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard
src/Okanshi.Dashboard/ApiModule.cs
src/Okanshi.Dashboard/ApiModule.cs
using Nancy; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public class ApiModule : NancyModule { public ApiModule(IConfiguration configuration, IGetMetrics getMetrics, IGetHealthChecks getHealthChecks) { Get["/api/instances"] = _ => Response.AsJson(configuration.GetAll()); Get["/api/instances/{instanceName}"] = p => { string instanceName = p.instanceName.ToString(); var service = new Service { Metrics = getMetrics.Execute(instanceName), HealthChecks = getHealthChecks.Execute(instanceName) }; return Response.AsJson(service); }; Get["/api/instances/{instanceName}/healthchecks"] = p => { string instanceName = p.instanceName.ToString(); return Response.AsJson(getHealthChecks.Execute(instanceName)); }; Get["/api/instances/{instanceName}/metrics"] = p => { string instanceName = p.instanceName.ToString(); return Response.AsJson(getMetrics.Execute(instanceName)); }; } } }
using Nancy; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public class ApiModule : NancyModule { public ApiModule(IConfiguration configuration, IGetMetrics getMetrics, IGetHealthChecks getHealthChecks) { Get["/api/instances"] = _ => Response.AsJson(configuration.GetAll()); Get["/api/instances/{instanceName}"] = p => { string instanceName = p.instanceName.ToString(); var service = new Service { Metrics = getMetrics.Execute(instanceName), HealthChecks = getHealthChecks.Execute(instanceName) }; return Response.AsJson(service); }; Get["/api/instances/{instanceName}/healthchecks"] = p => { string instanceName = p.instanceName.ToString(); return Response.AsJson(getHealthChecks.Execute(instanceName)); }; } } }
mit
C#
e78a4bcc3892c67179dfba62db94617f5963aa31
Improve tower shoot behavior
emazzotta/unity-tower-defense
Assets/Scripts/Tower.cs
Assets/Scripts/Tower.cs
using UnityEngine; using System.Collections; public class Tower : MonoBehaviour { Transform towerTransform; public float range = 10f; public GameObject bulletPrefab; public int cost = 5; public int damage = 10; public float radius = 0; private MetallKefer nearestMetallKefer; void Start () { InvokeRepeating("AimAtTarget", 0, 0.5f); this.nearestMetallKefer = null; towerTransform = transform.Find("Tower"); } void AimAtTarget() { MetallKefer[] enemies = GameObject.FindObjectsOfType<MetallKefer>(); this.nearestMetallKefer = GetClosestEnemy(enemies); if(nearestMetallKefer == null) { Debug.Log("No enemies?"); return; } if (nearestMetallKefer != null && nearestMetallKefer.GetHealth () > 0) { ShootAt (nearestMetallKefer); } Vector3 lookRotation = nearestMetallKefer.transform.position - this.transform.position; if (lookRotation != Vector3.zero) { var targetRotation = Quaternion.LookRotation(lookRotation); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime); } } void ShootAt(MetallKefer metallKefer) { GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation); bulletGO.transform.SetParent (this.transform); Bullet b = bulletGO.GetComponent<Bullet>(); b.target = metallKefer; b.damage = damage; } MetallKefer GetClosestEnemy(MetallKefer[] enemies) { MetallKefer tMin = null; float minDist = Mathf.Infinity; Vector3 currentPos = transform.position; foreach (MetallKefer enemy in enemies) { float dist = Vector3.Distance(enemy.transform.position, currentPos); if (dist < minDist) { tMin = enemy; minDist = dist; } } return tMin; } }
using UnityEngine; using System.Collections; public class Tower : MonoBehaviour { Transform towerTransform; public float range = 10f; public GameObject bulletPrefab; public int cost = 5; //float fireCooldown = 0.5f; //float fireCooldownLeft = 0; public int damage = 10; public float radius = 0; //private float dist = Mathf.Infinity; private MetallKefer nearestMetallKefer; void Start () { this.nearestMetallKefer = null; towerTransform = transform.Find("Tower"); } void Update () { MetallKefer[] enemies = GameObject.FindObjectsOfType<MetallKefer>(); this.nearestMetallKefer = GetClosestEnemy(enemies); if(nearestMetallKefer == null) { Debug.Log("No enemies?"); return; } if (nearestMetallKefer != null && nearestMetallKefer.GetHealth () > 0) { ShootAt (nearestMetallKefer); } Vector3 lookRotation = nearestMetallKefer.transform.position - this.transform.position; if (lookRotation != Vector3.zero) { var targetRotation = Quaternion.LookRotation(lookRotation); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime); } } void ShootAt(MetallKefer metallKefer) { GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation); bulletGO.transform.SetParent (this.transform); Bullet b = bulletGO.GetComponent<Bullet>(); b.target = metallKefer; b.damage = damage; } MetallKefer GetClosestEnemy(MetallKefer[] enemies) { MetallKefer tMin = null; float minDist = Mathf.Infinity; Vector3 currentPos = transform.position; foreach (MetallKefer enemy in enemies) { float dist = Vector3.Distance(enemy.transform.position, currentPos); if (dist < minDist) { tMin = enemy; minDist = dist; } } return tMin; } }
mit
C#
910efb5f720cefca57d8b1bb9272fd20f957c727
Use the latest major version when saving a new LS file
Norbyte/lslib,Norbyte/lslib,Norbyte/lslib
LSLib/LS/Resource.cs
LSLib/LS/Resource.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace LSLib.LS { public class InvalidFormatException : Exception { public InvalidFormatException(string message) : base(message) { } } public struct LSMetadata { public const uint CurrentMajorVersion = 33; public UInt64 timestamp; public UInt32 majorVersion; public UInt32 minorVersion; public UInt32 revision; public UInt32 buildNumber; } public struct LSBHeader { public const uint Signature = 0x40000000; public const uint CurrentMajorVersion = 1; public const uint CurrentMinorVersion = 3; public UInt32 signature; public UInt32 totalSize; public UInt32 bigEndian; public UInt32 unknown; public LSMetadata metadata; } public class Resource { public LSMetadata Metadata; public Dictionary<string, Region> Regions = new Dictionary<string,Region>(); public Resource() { Metadata.majorVersion = LSMetadata.CurrentMajorVersion; } } public class Region : Node { public string RegionName; } public class Node { public string Name; public Node Parent; public Dictionary<string, NodeAttribute> Attributes = new Dictionary<string, NodeAttribute>(); public Dictionary<string, List<Node>> Children = new Dictionary<string, List<Node>>(); public int ChildCount { get { return (from c in Children select c.Value.Count).Sum(); } } public void AppendChild(Node child) { List<Node> children; if (!Children.TryGetValue(child.Name, out children)) { children = new List<Node>(); Children.Add(child.Name, children); } children.Add(child); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace LSLib.LS { public class InvalidFormatException : Exception { public InvalidFormatException(string message) : base(message) { } } public struct LSMetadata { public UInt64 timestamp; public UInt32 majorVersion; public UInt32 minorVersion; public UInt32 revision; public UInt32 buildNumber; } public struct LSBHeader { public const uint Signature = 0x40000000; public const uint CurrentMajorVersion = 1; public const uint CurrentMinorVersion = 3; public UInt32 signature; public UInt32 totalSize; public UInt32 bigEndian; public UInt32 unknown; public LSMetadata metadata; } public class Resource { public LSMetadata Metadata; public Dictionary<string, Region> Regions = new Dictionary<string,Region>(); } public class Region : Node { public string RegionName; } public class Node { public string Name; public Node Parent; public Dictionary<string, NodeAttribute> Attributes = new Dictionary<string, NodeAttribute>(); public Dictionary<string, List<Node>> Children = new Dictionary<string, List<Node>>(); public int ChildCount { get { return (from c in Children select c.Value.Count).Sum(); } } public void AppendChild(Node child) { List<Node> children; if (!Children.TryGetValue(child.Name, out children)) { children = new List<Node>(); Children.Add(child.Name, children); } children.Add(child); } } }
mit
C#
c57dfcc1b172b820c5a8a2c7f357ffbb78622e64
add docs
jonnii/SpeakEasy
src/SpeakEasy/INamingConvention.cs
src/SpeakEasy/INamingConvention.cs
namespace SpeakEasy { /// <summary> /// The naming convention is the process by which a segment name is converted into a /// query string parameter /// </summary> public interface INamingConvention { /// <summary> /// Converts a property name to a parameter name /// </summary> /// <param name="propertyName">The name of the property to convert</param> /// <returns>The converted name</returns> string ConvertPropertyNameToParameterName(string propertyName); } }
namespace SpeakEasy { /// <summary> /// The naming convention is the process by which a segment name is converted into a /// query string parameter /// </summary> public interface INamingConvention { string ConvertPropertyNameToParameterName(string propertyName); } }
apache-2.0
C#
ed701bf45304f974bbdf604e33862ac5b40ff9d0
fix failijg tests
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests/Validation/ApprenticeshipBulkUpload/ApprenticeshipBulkUploadValidationTestBase.cs
src/SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests/Validation/ApprenticeshipBulkUpload/ApprenticeshipBulkUploadValidationTestBase.cs
using System; using Moq; using NUnit.Framework; using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces; using SFA.DAS.ProviderApprenticeshipsService.Web.Models; using SFA.DAS.ProviderApprenticeshipsService.Web.Models.BulkUpload; using SFA.DAS.ProviderApprenticeshipsService.Web.Models.Types; using SFA.DAS.ProviderApprenticeshipsService.Web.Orchestrators.BulkUpload; using SFA.DAS.ProviderApprenticeshipsService.Web.Validation; using SFA.DAS.ProviderApprenticeshipsService.Web.Validation.Text; using SFA.DAS.Learners.Validators; namespace SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests.Validation.ApprenticeshipBulkUpload { public abstract class ApprenticeshipBulkUploadValidationTestBase { protected ApprenticeshipUploadModelValidator Validator; protected ApprenticeshipUploadModel ValidModel; protected Mock<ICurrentDateTime> MockCurrentDateTime; protected Mock<IUlnValidator> MockUlnValidator; protected Mock<IAcademicYearDateProvider> MockAcademicYear; protected Mock<IAcademicYearValidator> MockAcademicYearValidator; [SetUp] public void BaseSetup() { MockCurrentDateTime = new Mock<ICurrentDateTime>(); MockUlnValidator = new Mock<IUlnValidator>(); MockAcademicYear = new Mock<IAcademicYearDateProvider>(); MockAcademicYearValidator = new Mock<IAcademicYearValidator>(); Validator = new ApprenticeshipUploadModelValidator(new BulkUploadApprenticeshipValidationText(MockAcademicYear.Object), MockCurrentDateTime.Object, MockUlnValidator.Object); ValidModel = new ApprenticeshipUploadModel { ApprenticeshipViewModel = new ApprenticeshipViewModel { ULN = "1001234567", FirstName = "TestFirstName", LastName = "TestLastName", CourseCode = "12", DateOfBirth = new DateTimeViewModel(DateTime.UtcNow.AddYears(-39)), StartDate = new DateTimeViewModel(new DateTime(2017, 06, 20)), EndDate = new DateTimeViewModel(new DateTime(2018, 05, 15)), Cost = "1234" }, CsvRecord = new CsvRecord { CohortRef = "abba123", ProgType = "25", StdCode = "123" } }; } } }
using System; using Moq; using NUnit.Framework; using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces; using SFA.DAS.ProviderApprenticeshipsService.Web.Models; using SFA.DAS.ProviderApprenticeshipsService.Web.Models.BulkUpload; using SFA.DAS.ProviderApprenticeshipsService.Web.Models.Types; using SFA.DAS.ProviderApprenticeshipsService.Web.Orchestrators.BulkUpload; using SFA.DAS.ProviderApprenticeshipsService.Web.Validation; using SFA.DAS.ProviderApprenticeshipsService.Web.Validation.Text; using SFA.DAS.Learners.Validators; namespace SFA.DAS.ProviderApprenticeshipsService.Web.UnitTests.Validation.ApprenticeshipBulkUpload { public abstract class ApprenticeshipBulkUploadValidationTestBase { protected ApprenticeshipUploadModelValidator Validator; protected ApprenticeshipUploadModel ValidModel; protected Mock<ICurrentDateTime> MockCurrentDateTime; protected Mock<IUlnValidator> MockUlnValidator; protected Mock<IAcademicYearDateProvider> MockAcademicYear; protected Mock<IAcademicYearValidator> MockAcademicYearValidator; [SetUp] public void BaseSetup() { MockCurrentDateTime = new Mock<ICurrentDateTime>(); MockUlnValidator = new Mock<IUlnValidator>(); MockAcademicYear = new Mock<IAcademicYearDateProvider>(); MockAcademicYearValidator = new Mock<IAcademicYearValidator>(); Validator = new ApprenticeshipUploadModelValidator(new BulkUploadApprenticeshipValidationText(MockAcademicYear.Object), MockCurrentDateTime.Object, MockUlnValidator.Object); ValidModel = new ApprenticeshipUploadModel { ApprenticeshipViewModel = new ApprenticeshipViewModel { ULN = "1001234567", FirstName = "TestFirstName", LastName = "TestLastName", CourseCode = "12", DateOfBirth = new DateTimeViewModel(DateTime.UtcNow.AddYears(-18)), StartDate = new DateTimeViewModel(new DateTime(2017, 06, 20)), EndDate = new DateTimeViewModel(new DateTime(2018, 05, 15)), Cost = "1234" }, CsvRecord = new CsvRecord { CohortRef = "abba123", ProgType = "25", StdCode = "123" } }; } } }
mit
C#
8f8abab942364670aa9138beef0a0916ca901a70
Print filename with each error
vindvaki/xlsx-validator
XlsxValidator/Program.cs
XlsxValidator/Program.cs
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; // Adapted from // https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/ namespace XlsxValidator { class MainClass { public static void Main(string[] args) { if (args.Count() == 0) { Console.WriteLine("No document given"); return; } var path = args[0]; using (SpreadsheetDocument doc = SpreadsheetDocument.Open(path, false)) { var validator = new OpenXmlValidator(); var errors = validator.Validate(doc); if (errors.Count() == 0) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is not valid"); } Console.WriteLine(); foreach (var error in errors) { Console.WriteLine("File: {0}", path); Console.WriteLine("Error: {0}", error.Description); Console.WriteLine("ContentType: {0}", error.Part.ContentType); Console.WriteLine("XPath: {0}", error.Path.XPath); Console.WriteLine(); } } } } }
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; // Adapted from // https://blogs.msdn.microsoft.com/ericwhite/2010/03/04/validate-open-xml-documents-using-the-open-xml-sdk-2-0/ namespace XlsxValidator { class MainClass { public static void Main(string[] args) { if (args.Count() == 0) { Console.WriteLine("No document given"); return; } using (SpreadsheetDocument doc = SpreadsheetDocument.Open(args[0], false)) { var validator = new OpenXmlValidator(); var errors = validator.Validate(doc); if (errors.Count() == 0) { Console.WriteLine("Document is valid"); } else { Console.WriteLine("Document is not valid"); } Console.WriteLine(); foreach (var error in errors) { Console.WriteLine("Error description: {0}", error.Description); Console.WriteLine("Content type of part with error: {0}", error.Part.ContentType); Console.WriteLine("Location of error: {0}", error.Path.XPath); Console.WriteLine(); } } } } }
apache-2.0
C#
16e5e4007c8f73018b23a73fd0470538ed759be1
Add extra check on result type
mspons/DiceApi
test/DiceApi.WebApi.Tests/DieControllerTest.cs
test/DiceApi.WebApi.Tests/DieControllerTest.cs
using Microsoft.AspNetCore.Mvc; using Xunit; using DiceApi.WebApi.Controllers; namespace DiceApi.WebApi.Tests { /// <summary> /// Test class for <see cref="DieController" />. /// </summary> public class DieControllerTest { /// <summary> /// Verifies that Get() returns a BadRequestResult when given an invalid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult() { var sut = new DieController(); var result = sut.Get(-1); Assert.Equal(typeof(BadRequestResult), result.GetType()); } /// <summary> /// Verifies that Get() returns an OkObjectResult when given an valid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenValidSizeValue_ReturnsOkResult() { var sut = new DieController(); var result = sut.Get(6); Assert.Equal(typeof(OkObjectResult), result.GetType()); Assert.Equal(typeof(int), ((OkObjectResult)result).Value.GetType()); } } }
using Microsoft.AspNetCore.Mvc; using Xunit; using DiceApi.WebApi.Controllers; namespace DiceApi.WebApi.Tests { /// <summary> /// Test class for <see cref="DieController" />. /// </summary> public class DieControllerTest { /// <summary> /// Verifies that Get() returns a BadRequestResult when given an invalid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenSidesLessThanZero_ReturnsBadRequestResult() { var sut = new DieController(); var result = sut.Get(-1); Assert.Equal(typeof(BadRequestResult), result.GetType()); } /// <summary> /// Verifies that Get() returns an OkObjectResult when given an valid number /// of sides for the die to roll. /// </summary> [Fact] public void Get_GivenValidSizeValue_ReturnsOkResult() { var sut = new DieController(); var result = sut.Get(6); Assert.Equal(typeof(OkObjectResult), result.GetType()); } } }
mit
C#
eb92831b23a5a4060f8f1d8b28f9c07ab0411be1
Update sample app to use newer config API
serilog-web/classic
test/SerilogWeb.Test/Global.asax.cs
test/SerilogWeb.Test/Global.asax.cs
using System; using Serilog; using Serilog.Events; using SerilogWeb.Classic; namespace SerilogWeb.Test { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { // ReSharper disable once PossibleNullReferenceException SerilogWebClassic.Configuration .IgnoreRequestsMatching(ctx => ctx.Request.Url.PathAndQuery.StartsWith("/__browserLink")) .EnableFormDataLogging(formData => formData .AtLevel(LogEventLevel.Debug) .OnMatch(ctx => ctx.Response.StatusCode >= 400)); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" ) .CreateLogger(); } } }
using System; using Serilog; using Serilog.Events; using SerilogWeb.Classic; namespace SerilogWeb.Test { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { ApplicationLifecycleModule.FormDataLoggingLevel = LogEventLevel.Debug; ApplicationLifecycleModule.LogPostedFormData = LogPostedFormDataOption.OnMatch; ApplicationLifecycleModule.ShouldLogPostedFormData = context => context.Response.StatusCode >= 400; // ReSharper disable once PossibleNullReferenceException ApplicationLifecycleModule.RequestFilter = context => context.Request.Url.PathAndQuery.StartsWith("/__browserLink"); Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Trace(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception} {Properties:j}" ) .CreateLogger(); } } }
apache-2.0
C#
afb15ff7fdd4752438aa435b057b06fa8a7b38f3
Add assert helper for tests
Xeeynamo/KingdomHearts
OpenKh.Tests/Helpers.cs
OpenKh.Tests/Helpers.cs
using System; using System.IO; using System.Linq; using OpenKh.Common; using OpenKh.Kh2; using Xunit; namespace OpenKh.Tests { public static class Helpers { public static void Dump(this Stream stream, string path) => File.Create(path).Using(outStream => { stream.Position = 0; stream.CopyTo(outStream); }); public static void AssertStream(Stream expectedStream, Func<Stream, Stream> funcGenerateNewStream) { var expectedData = expectedStream.ReadAllBytes(); var actualStream = funcGenerateNewStream(new MemoryStream(expectedData)); var actualData = actualStream.ReadAllBytes(); Assert.Equal(expectedData.Length, actualData.Length); for (var i = 0; i < expectedData.Length; i++) { var ch1 = expectedData[i]; var ch2 = actualData[i]; Assert.True(ch1 == ch2, $"Expected {ch1:X02} but found {ch2:X02} at {i:X}"); } } public static void AssertAllBarEntries(string gamePath, Bar.EntryType entryType, Func<Stream, Stream> assertion) => Directory .GetFiles(gamePath, "*", SearchOption.AllDirectories) .Where(fileName => File.OpenRead(fileName).Using(stream => Bar.IsValid(stream))) .SelectMany(fileName => File.OpenRead(fileName).Using(stream => Bar.Read(stream))) .Where(x => x.Type == entryType && x.Index == 0) .AsParallel() .ForAll(entry => AssertStream(entry.Stream, assertion)); public static void UseAsset(string assetName, Action<Stream> action) => File.OpenRead(Path.Combine($"_Assets", assetName)).Using(x => action(x)); public static void Dump(this byte[] data, string path) => new MemoryStream(data).Using(x => x.Dump(path)); } public class Common { public static void FileOpenRead(string path, Action<Stream> action) { File.OpenRead(path).Using(x => action(x)); } } }
using System; using System.IO; using OpenKh.Common; using Xunit; namespace OpenKh.Tests { public static class Helpers { public static void Dump(this Stream stream, string path) => File.Create(path).Using(outStream => { stream.Position = 0; stream.CopyTo(outStream); }); public static void AssertStream(Stream expectedStream, Func<Stream, Stream> funcGenerateNewStream) { var expectedData = expectedStream.ReadAllBytes(); var actualStream = funcGenerateNewStream(new MemoryStream(expectedData)); var actualData = actualStream.ReadAllBytes(); Assert.Equal(expectedData.Length, actualData.Length); for (var i = 0; i < expectedData.Length; i++) { var ch1 = expectedData[i]; var ch2 = actualData[i]; Assert.True(ch1 == ch2, $"Expected {ch1:X02} but found {ch2:X02} at {i:X}"); } } public static void UseAsset(string assetName, Action<Stream> action) => File.OpenRead(Path.Combine($"_Assets", assetName)).Using(x => action(x)); public static void Dump(this byte[] data, string path) => new MemoryStream(data).Using(x => x.Dump(path)); } public class Common { public static void FileOpenRead(string path, Action<Stream> action) { File.OpenRead(path).Using(x => action(x)); } } }
mit
C#
7babb8f13fa614b01b4d23b891c171e9a7f3d8a5
Update IContainer.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
Test/Core/IContainer.cs
Test/Core/IContainer.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test.Core { public interface IContainer { double Width { get; set; } double Height { get; set; } IList<XStyle> Styles { get; set; } XStyle CurrentStyle { get; set; } XShape PointShape { get; set; } IList<ILayer> Layers { get; set; } ILayer CurrentLayer { get; set; } ILayer WorkingLayer { get; set; } XShape CurrentShape { get; set; } void Clear(); void Invalidate(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test.Core { public interface IContainer { double Width { get; set; } double Height { get; set; } IList<XStyle> Styles { get; set; } XStyle CurrentStyle { get; set; } XShape PointShape { get; set; } IList<ILayer> Layers { get; set; } ILayer CurrentLayer { get; set; } ILayer WorkingLayer { get; set; } XShape CurrentShape { get; set; } void Clear(); void Invalidate(); } }
mit
C#
88cf7724497b498552ab345fa3187c26cc1b3051
Update Drivers/ManagePersonsPermissionCheckerTaskDisplayDriver.cs
Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module
Drivers/ManagePersonsPermissionCheckerTaskDisplayDriver.cs
Drivers/ManagePersonsPermissionCheckerTaskDisplayDriver.cs
using Lombiq.TrainingDemo.Activities; using Lombiq.TrainingDemo.ViewModels; using OrchardCore.Workflows.Display; using OrchardCore.Workflows.Models; namespace Lombiq.TrainingDemo.Drivers; // ActivityDisplayDriver is specifically for implementing workflow tasks. It performs a simple mapping of a ManagePersonsPermissionCheckerTask // to a ManagePersonsPermissionCheckerTaskViewModel and vice versa. Don't forget to register this class with the service provider (see: Startup.cs). public class ManagePersonsPermissionCheckerTaskDisplayDriver : ActivityDisplayDriver<ManagePersonsPermissionCheckerTask, ManagePersonsPermissionCheckerTaskViewModel> { protected override void EditActivity(ManagePersonsPermissionCheckerTask activity, ManagePersonsPermissionCheckerTaskViewModel model) => model.UserName = activity.UserName.Expression; protected override void UpdateActivity(ManagePersonsPermissionCheckerTaskViewModel model, ManagePersonsPermissionCheckerTask activity) => activity.UserName = new WorkflowExpression<string>(model.UserName); } // NEXT STATION: Check out the following files to see how we make the activity visible on the admin, the come back here. // Views/Items/ManagePersonsPermissionCheckerTask.Fields.Edit.cshtml, // ManagePersonsPermissionCheckerTask.Fields.Design.cshtml, ManagePersonsPermissionCheckerTask.Fields.Thumbnail.cshtml // END OF TRAINING SECTION: Workflows
using Lombiq.TrainingDemo.Activities; using Lombiq.TrainingDemo.ViewModels; using OrchardCore.Workflows.Display; using OrchardCore.Workflows.Models; namespace Lombiq.TrainingDemo.Drivers; // ActivityDisplayDriver is specifically for implementing workflow tasks. It performs a simple mapping of a ManagePersonsPermissionCheckerTask // to a ManagePersonsPermissionCheckerTaskViewModel and vice versa. Don't forget to register this class with the service provider (see: Startup.cs). public class ManagePersonsPermissionCheckerTaskDisplayDriver : ActivityDisplayDriver<ManagePersonsPermissionCheckerTask, ManagePersonsPermissionCheckerTaskViewModel> { protected override void EditActivity(ManagePersonsPermissionCheckerTask activity, ManagePersonsPermissionCheckerTaskViewModel model) => model.UserName = activity.UserName.Expression; protected override void UpdateActivity(ManagePersonsPermissionCheckerTaskViewModel model, ManagePersonsPermissionCheckerTask activity) => activity.UserName = new WorkflowExpression<string>(model.UserName); } // Now you have to create the Razor files for the View. It's important to put these in a folder called Items. // NEXT STATION: Views/Items/ManagePersonsPermissionCheckerTask.Fields.Edit.cshtml, ManagePersonsPermissionCheckerTask.Fields.Design.cshtml, // ManagePersonsPermissionCheckerTask.Fields.Thumbnail.cshtml // END OF TRAINING SECTION: Workflows
bsd-3-clause
C#
4ec7f47c3caa0da2c3f39256df8351230cc54b1b
Adjust BackoffIdleStrategy defaults
AdaptiveConsulting/Aeron.NET,AdaptiveConsulting/Aeron.NET
src/Adaptive.Agrona/Concurrent/Configuration.cs
src/Adaptive.Agrona/Concurrent/Configuration.cs
namespace Adaptive.Agrona.Concurrent { public class Configuration { /// <summary> /// Spin on no activity before backing off to yielding. /// </summary> public const long IDLE_MAX_SPINS = 10; /// <summary> /// Yield the thread so others can run before backing off to parking. /// </summary> public const long IDLE_MAX_YIELDS = 40; /// <summary> /// Park for the minimum period of time which is typically 50-55 microseconds on 64-bit non-virtualised Linux. /// You will typically get 50-55 microseconds plus the number of nanoseconds requested if a core is available. /// On Windows expect to wait for at least 16ms or 1ms if the high-res timers are enabled. /// </summary> public const long IDLE_MIN_PARK_MS = 1; /// <summary> /// Maximum back-off park time which doubles on each interval stepping up from the min park idle. /// </summary> public static readonly long IDLE_MAX_PARK_MS = 16; } }
namespace Adaptive.Agrona.Concurrent { public class Configuration { /// <summary> /// Spin on no activity before backing off to yielding. /// </summary> public const long IDLE_MAX_SPINS = 10; /// <summary> /// Yield the thread so others can run before backing off to parking. /// </summary> public const long IDLE_MAX_YIELDS = 20; /// <summary> /// Park for the minimum period of time which is typically 50-55 microseconds on 64-bit non-virtualised Linux. /// You will typically get 50-55 microseconds plus the number of nanoseconds requested if a core is available. /// On Windows expect to wait for at least 16ms or 1ms if the high-res timers are enabled. /// </summary> public const long IDLE_MIN_PARK_MS = 1; /// <summary> /// Maximum back-off park time which doubles on each interval stepping up from the min park idle. /// </summary> public static readonly long IDLE_MAX_PARK_MS = 1000; } }
apache-2.0
C#
469fa5adde358fe39eea1ded6230f753922b3740
Add [Serializable] attribute
dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute
Source/NSubstitute/Exceptions/NotRunningAQueryException.cs
Source/NSubstitute/Exceptions/NotRunningAQueryException.cs
using System; using System.Runtime.Serialization; namespace NSubstitute.Exceptions { [Serializable] public class NotRunningAQueryException : SubstituteException { public NotRunningAQueryException() { } protected NotRunningAQueryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System.Runtime.Serialization; namespace NSubstitute.Exceptions { [Serializable] public class NotRunningAQueryException : SubstituteException { public NotRunningAQueryException() { } protected NotRunningAQueryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
bsd-3-clause
C#
241cbc571e3e999d8d9c66154f042c0dfd4755c3
Add the C test suite via Cake to Travis and AppVeyor.
jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000
build.cake
build.cake
#!mono .cake/Cake/Cake.exe #tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); #load "build/Utils.cake" #load "build/Android.cake" #load "build/Tests.cake" #load "build/Packaging.cake" Task("Clean") .Does(() => { CleanDirectory("./build/lib"); CleanDirectory("./build/obj"); CleanDirectories("./tests/common/c"); CleanDirectories("./tests/common/java"); CleanDirectories("./tests/common/mk"); CleanDirectories(GetDirectories("./tests/**/obj")); CleanDirectories(GetDirectories("./tests/**/bin")); CleanDirectories(GetDirectories("./tests/android/**/build")); }); Task("NuGet-Restore") .Does(() => { NuGetRestore("./Embeddinator-4000.sln"); }); Task("Build-Binder") .IsDependentOn("Clean") .IsDependentOn("Generate-Project-Files") .IsDependentOn("NuGet-Restore") .Does(() => { MSBuild("./build/projects/Embeddinator-4000.csproj", settings => settings.SetConfiguration(configuration).SetVerbosity(Verbosity.Minimal)); }); Task("Generate-Project-Files") .Does(() => { var os = IsRunningOnWindows() ? "windows" : "macosx"; Premake(File("./build/premake5.lua"), $"--outdir=.. --os={os}", "vs2015"); }); Task("Default") .IsDependentOn("Build-Binder"); Task("Tests") .IsDependentOn("Generate-Android") .IsDependentOn("Generate-Android-PCL") .IsDependentOn("Generate-Android-NetStandard") .IsDependentOn("Generate-Android-FSharp") .IsDependentOn("Build-CSharp-Tests") .IsDependentOn("Run-C-Tests"); Task("AppVeyor") .IsDependentOn("Build-Binder") .IsDependentOn("Tests"); Task("Travis") .IsDependentOn("Build-Binder") .IsDependentOn("Tests"); RunTarget(target);
#!mono .cake/Cake/Cake.exe #tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); #load "build/Utils.cake" #load "build/Android.cake" #load "build/Tests.cake" #load "build/Packaging.cake" Task("Clean") .Does(() => { CleanDirectory("./build/lib"); CleanDirectory("./build/obj"); CleanDirectories("./tests/common/c"); CleanDirectories("./tests/common/java"); CleanDirectories("./tests/common/mk"); CleanDirectories(GetDirectories("./tests/**/obj")); CleanDirectories(GetDirectories("./tests/**/bin")); CleanDirectories(GetDirectories("./tests/android/**/build")); }); Task("NuGet-Restore") .Does(() => { NuGetRestore("./Embeddinator-4000.sln"); }); Task("Build-Binder") .IsDependentOn("Clean") .IsDependentOn("Generate-Project-Files") .IsDependentOn("NuGet-Restore") .Does(() => { MSBuild("./build/projects/Embeddinator-4000.csproj", settings => settings.SetConfiguration(configuration).SetVerbosity(Verbosity.Minimal)); }); Task("Generate-Project-Files") .Does(() => { var os = IsRunningOnWindows() ? "windows" : "macosx"; Premake(File("./build/premake5.lua"), $"--outdir=.. --os={os}", "vs2015"); }); Task("Default") .IsDependentOn("Build-Binder"); Task("AppVeyor") .IsDependentOn("Generate-Android") .IsDependentOn("Generate-Android-PCL") .IsDependentOn("Generate-Android-NetStandard") .IsDependentOn("Generate-Android-FSharp") .IsDependentOn("Build-CSharp-Tests"); Task("Travis") .IsDependentOn("Build-Binder") .IsDependentOn("Build-C-Tests"); RunTarget(target);
mit
C#
58fb4e3d441a224a7054fa647a7062688c378e6a
Revert "Fix "Pack" step to be dependent on the "Test" step"
HangfireIO/Cronos
build.cake
build.cake
#tool "nuget:?package=xunit.runner.console" #addin "Cake.FileHelpers" // Don't edit manually! Use `.\build.ps1 -ScriptArgs '--newVersion="*.*.*"'` command instead! var version = "0.2.0"; var configuration = Argument("configuration", "Release"); var newVersion = Argument("newVersion", version); var target = Argument("target", "Pack"); Task("Restore") .Does(()=> { DotNetCoreRestore(); }); Task("Clean") .Does(()=> { CleanDirectory("./build"); StartProcess("dotnet", "clean -c:" + configuration); }); Task("Version") .Does(() => { if(newVersion == version) return; var versionRegex = @"[0-9]+(\.([0-9]+|\*)){1,3}"; var cakeRegex = "var version = \"" + versionRegex + "\""; ReplaceRegexInFiles("build.cake", cakeRegex, "var version = \"" + newVersion + "\""); ReplaceRegexInFiles("appveyor.yml", "version: " + versionRegex, "version: " + newVersion + ""); }); Task("Build") .IsDependentOn("Version") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(()=> { DotNetCoreBuild("src/Cronos/Cronos.csproj", new DotNetCoreBuildSettings { Configuration = configuration, ArgumentCustomization = args => args.Append("/p:Version=" + version) }); }); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings { Configuration = "Release", ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false") }); }); Task("AppVeyor") .IsDependentOn("Test") .Does(()=> { if (AppVeyor.Environment.Repository.Tag.IsTag) { var tagName = AppVeyor.Environment.Repository.Tag.Name; if(tagName.StartsWith("v")) { version = tagName.Substring(1); } AppVeyor.UpdateBuildVersion(version); } }); Task("Local") .Does(()=> { RunTarget("Test"); }); Task("Pack") .Does(()=> { var target = AppVeyor.IsRunningOnAppVeyor ? "AppVeyor" : "Local"; RunTarget(target); CreateDirectory("build"); Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip"); }); RunTarget(target);
#tool "nuget:?package=xunit.runner.console" #addin "Cake.FileHelpers" // Don't edit manually! Use `.\build.ps1 -ScriptArgs '--newVersion="*.*.*"'` command instead! var version = "0.2.0"; var configuration = Argument("configuration", "Release"); var newVersion = Argument("newVersion", version); var target = Argument("target", "Pack"); Task("Restore") .Does(()=> { DotNetCoreRestore(); }); Task("Clean") .Does(()=> { CleanDirectory("./build"); StartProcess("dotnet", "clean -c:" + configuration); }); Task("Version") .Does(() => { if(newVersion == version) return; var versionRegex = @"[0-9]+(\.([0-9]+|\*)){1,3}"; var cakeRegex = "var version = \"" + versionRegex + "\""; ReplaceRegexInFiles("build.cake", cakeRegex, "var version = \"" + newVersion + "\""); ReplaceRegexInFiles("appveyor.yml", "version: " + versionRegex, "version: " + newVersion + ""); }); Task("Build") .IsDependentOn("Version") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(()=> { DotNetCoreBuild("src/Cronos/Cronos.csproj", new DotNetCoreBuildSettings { Configuration = configuration, ArgumentCustomization = args => args.Append("/p:Version=" + version) }); }); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings { Configuration = "Release", ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false") }); }); Task("AppVeyor") .IsDependentOn("Test") .Does(()=> { if (AppVeyor.Environment.Repository.Tag.IsTag) { var tagName = AppVeyor.Environment.Repository.Tag.Name; if(tagName.StartsWith("v")) { version = tagName.Substring(1); } AppVeyor.UpdateBuildVersion(version); } }); Task("Local") .Does(()=> { RunTarget("Test"); }); Task("Pack") .IsDependentOn("Test") .Does(()=> { var target = AppVeyor.IsRunningOnAppVeyor ? "AppVeyor" : "Local"; RunTarget(target); CreateDirectory("build"); Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip"); }); RunTarget(target);
mit
C#
81d1dc14f81655e0f5b779f04a82f4009dedb8bc
Remove unnecessary using statements.
LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform
src/CompetitionPlatform/Helpers/StatusHelper.cs
src/CompetitionPlatform/Helpers/StatusHelper.cs
using System; using CompetitionPlatform.Models; namespace CompetitionPlatform.Helpers { public static class StatusHelper { public static Status GetProjectStatusFromString(string status) { if (status == "CompetitionRegistration") return Status.Registration; if (status == "Implementation") return Status.Submission; return (Status)Enum.Parse(typeof(Status), status, true); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CompetitionPlatform.Models; namespace CompetitionPlatform.Helpers { public static class StatusHelper { public static Status GetProjectStatusFromString(string status) { if (status == "CompetitionRegistration") return Status.Registration; if (status == "Implementation") return Status.Submission; return (Status)Enum.Parse(typeof(Status), status, true); } } }
mit
C#
e9e3c240ec259db0a6ee34609aa605c0e1e8edaa
Update player stats
mk-dev-team/mk-world-of-imagination
src/Hevadea/Scenes/Widgets/WidgetPlayerStats.cs
src/Hevadea/Scenes/Widgets/WidgetPlayerStats.cs
using Hevadea.Framework.Graphic.SpriteAtlas; using Hevadea.Framework.UI; using Hevadea.GameObjects.Entities.Components.States; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; namespace Hevadea.Scenes.Widgets { public class WidgetPlayerStats : Widget { private readonly Sprite _energy; private readonly Sprite _hearth; private readonly GameObjects.Entities.Player _player; public WidgetPlayerStats(GameObjects.Entities.Player player) { _player = player; _hearth = new Sprite(Ressources.TileIcons, 0); _energy = new Sprite(Ressources.TileIcons, 1); } public override void Draw(SpriteBatch spriteBatch, GameTime gameTime) { if (!_player.HasComponent<Energy>() && !_player.HasComponent<Health>()) return; var health = _player.GetComponent<Health>().Value; var energy = _player.GetComponent<Energy>().ValuePercent; var i = 0; var size = Scale(48); for (i = 0; i <= health - 1; i++) _hearth.Draw(spriteBatch, new Rectangle(Bound.X + (size * i), Bound.Y, size, size), Color.White); _hearth.Draw(spriteBatch, new Rectangle(Bound.X + (size * i), Bound.Y, size, size), Color.White * (float)(health - Math.Floor( health))); for (i = 0; i <= 10 * energy - 1; i++) _energy.Draw(spriteBatch, new Rectangle(Bound.X + (size * i), Bound.Y + size, size, size), Color.White); _energy.Draw(spriteBatch, new Rectangle(Bound.X + (size * i), Bound.Y + size, size, size), Color.White * (float)(10 * energy - Math.Floor(10 * energy))); } } }
using Hevadea.Framework.Graphic.SpriteAtlas; using Hevadea.Framework.UI; using Hevadea.GameObjects.Entities.Components.States; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; namespace Hevadea.Scenes.Widgets { public class WidgetPlayerStats : Widget { private readonly Sprite _energy; private readonly Sprite _hearth; private readonly GameObjects.Entities.Player _player; public WidgetPlayerStats(GameObjects.Entities.Player player) { _player = player; _hearth = new Sprite(Ressources.TileIcons, 0); _energy = new Sprite(Ressources.TileIcons, 1); } public override void Draw(SpriteBatch spriteBatch, GameTime gameTime) { if (!_player.HasComponent<Energy>() && !_player.HasComponent<Health>()) return; var health = _player.GetComponent<Health>().Value; var energy = _player.GetComponent<Energy>().ValuePercent; var i = 0; var size = Scale(48); for (i = 0; i <= health - 1; i++) _hearth.Draw(spriteBatch, new Rectangle(Bound.X + size * i, Bound.Y, size, size), Color.White); _hearth.Draw(spriteBatch, new Rectangle(Bound.X + size * i, Bound.Y, size, size), Color.White * (float)(health - Math.Floor( health))); for (i = 0; i <= 10 * energy - 1; i++) _energy.Draw(spriteBatch, new Rectangle(Bound.X + size * i, Bound.Y + size, size, size), Color.White); _energy.Draw(spriteBatch, new Rectangle(Bound.X + size * i, Bound.Y + size, size, size), Color.White * (float)(10 * energy - Math.Floor(10 * energy))); } } }
mit
C#
a0bd4b7d1bb10e15082bfcf1c2977a70ccc352e4
Update MobSpawnControlScript.cs
fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Gateway/MobSpawnControlScript.cs
UnityProject/Assets/Scripts/Gateway/MobSpawnControlScript.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mirror; public class MobSpawnControlScript : NetworkBehaviour { public List<GameObject> MobSpawners; public bool DetectViaMatrix; private bool SpawnedMobs; private float timeElapsedServer = 0; [Server] public void SpawnMobs() { if (SpawnedMobs) return; SpawnedMobs = true; foreach (GameObject Spawner in MobSpawners) { if (Spawner != null) { Spawner.GetComponent<MobSpawnScript>().SpawnMob(); } } } protected virtual void UpdateMe() { if (isServer) { timeElapsedServer += Time.deltaTime; if (timeElapsedServer > 1f && !SpawnedMobs) { DetectPlayer(); timeElapsedServer = 0; } } } private void OnEnable() { if (!DetectViaMatrix) return; UpdateManager.Add(CallbackType.UPDATE, UpdateMe); } void OnDisable() { UpdateManager.Remove(CallbackType.UPDATE, UpdateMe); } [Server] private void DetectPlayer() { foreach (var player in PlayerList.Instance.InGamePlayers) { var playerScript = player.Script; if (playerScript == null) return; if (playerScript.registerTile.Matrix == gameObject.GetComponent<RegisterObject>().Matrix) { SpawnMobs(); UpdateManager.Remove(CallbackType.UPDATE, UpdateMe); return; } } } void OnDrawGizmosSelected() { var sprite = GetComponentInChildren<SpriteRenderer>(); if (sprite == null) return; //Highlighting all controlled lightSources Gizmos.color = new Color(0.5f, 0.5f, 1, 1); for (int i = 0; i < MobSpawners.Count; i++) { var mobSpawner = MobSpawners[i]; if (mobSpawner == null) continue; Gizmos.DrawLine(sprite.transform.position, mobSpawner.transform.position); Gizmos.DrawSphere(mobSpawner.transform.position, 0.25f); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mirror; public class MobSpawnControlScript : NetworkBehaviour { public List<GameObject> MobSpawners; public bool DetectViaMatrix; private bool SpawnedMobs; private float timeElapsedServer = 0; [Server] public void SpawnMobs() { if (SpawnedMobs) return; SpawnedMobs = true; foreach (GameObject Spawner in MobSpawners) { if (Spawner != null) { Spawner.GetComponent<MobSpawnScript>().SpawnMob(); } } } protected virtual void UpdateMe() { if (isServer) { timeElapsedServer += Time.deltaTime; if (timeElapsedServer > 1f && !SpawnedMobs) { DetectPlayer(); timeElapsedServer = 0; } } } private void OnEnable() { if (!DetectViaMatrix) return; UpdateManager.Add(CallbackType.UPDATE, UpdateMe); } void OnDisable() { UpdateManager.Remove(CallbackType.UPDATE, UpdateMe); } [Server] private void DetectPlayer() { foreach (var player in PlayerList.Instance.AllPlayers) { var playerScript = player.Script; if (playerScript == null) return; if (playerScript.registerTile.Matrix == gameObject.GetComponent<RegisterObject>().Matrix) { SpawnMobs(); UpdateManager.Remove(CallbackType.UPDATE, UpdateMe); return; } } } void OnDrawGizmosSelected() { var sprite = GetComponentInChildren<SpriteRenderer>(); if (sprite == null) return; //Highlighting all controlled lightSources Gizmos.color = new Color(0.5f, 0.5f, 1, 1); for (int i = 0; i < MobSpawners.Count; i++) { var mobSpawner = MobSpawners[i]; if (mobSpawner == null) continue; Gizmos.DrawLine(sprite.transform.position, mobSpawner.transform.position); Gizmos.DrawSphere(mobSpawner.transform.position, 0.25f); } } }
agpl-3.0
C#
91c99ef0477604616aaef4d65279caa871910185
Update AssemblyInfo.cs
dotJEM/web-host,dotJEM/web-host,dotJEM/web-host
DotJEM.Web.Host.Test/Properties/AssemblyInfo.cs
DotJEM.Web.Host.Test/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("DotJEM.Web.Host.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("DotJEM.Web.Host.Test")] [assembly: AssemblyCompany("N/A")] [assembly: AssemblyCopyright("Copyright © DotJEM 2014-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("503586ec-d51a-4d88-879f-38504914a6b6")] // 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("DotJEM.Web.Host.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("DotJEM.Web.Host.Test")] [assembly: AssemblyCompany("N/A")] [assembly: AssemblyCopyright("Copyright © DotJEM A/S 2014-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("503586ec-d51a-4d88-879f-38504914a6b6")] // 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#
36c0541aebf91d22f0d68f6422070799f35dce21
change version to 0.1
raol/amazon-sqs-net-extended-client-lib
src/Amazon.SQS.ExtendedClient/Properties/AssemblyInfo.cs
src/Amazon.SQS.ExtendedClient/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("Amazon.SQS.Net.ExtendedClient")] [assembly: AssemblyDescription("Extension to Amazon SQS that adds support for sending and receiving messages greater than 256K")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oleg Rakitskiy")] [assembly: AssemblyProduct("Amazon.SQS.Net.ExtendedClient")] [assembly: AssemblyCopyright("Copyright © Oleg Rakitskiy 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("38832a23-5aea-4856-991e-81ed4082bb67")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Amazon.SQS.Net.ExtendedClient.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Amazon.SQS.Net.ExtendedClient")] [assembly: AssemblyDescription("Extension to Amazon SQS that adds support for sending and receiving messages greater than 256K")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Oleg Rakitskiy")] [assembly: AssemblyProduct("Amazon.SQS.Net.ExtendedClient")] [assembly: AssemblyCopyright("Copyright © Oleg Rakitskiy 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("38832a23-5aea-4856-991e-81ed4082bb67")] // 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")] [assembly: InternalsVisibleTo("Amazon.SQS.Net.ExtendedClient.Tests")]
apache-2.0
C#
c17c58f940b73810f6c249ee8026f2e11b5019af
use task run
6bee/Remote.Linq
src/Remote.Linq/DynamicQuery/AsyncDynamicResultMapper.cs
src/Remote.Linq/DynamicQuery/AsyncDynamicResultMapper.cs
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Remote.Linq.DynamicQuery { using Aqua.Dynamic; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; internal sealed class AsyncDynamicResultMapper : IAsyncQueryResultMapper<IEnumerable<DynamicObject>> { private readonly IDynamicObjectMapper _mapper; public AsyncDynamicResultMapper(IDynamicObjectMapper mapper) { _mapper = mapper; } public Task<TResult> MapResultAsync<TResult>(IEnumerable<DynamicObject> source, Expression expression) => Task.Run(() => DynamicResultMapper.MapToType<TResult>(source, _mapper, expression)); } }
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information. namespace Remote.Linq.DynamicQuery { using Aqua.Dynamic; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; internal sealed class AsyncDynamicResultMapper : IAsyncQueryResultMapper<IEnumerable<DynamicObject>> { private readonly IDynamicObjectMapper _mapper; public AsyncDynamicResultMapper(IDynamicObjectMapper mapper) { _mapper = mapper; } public Task<TResult> MapResultAsync<TResult>(IEnumerable<DynamicObject> source, Expression expression) => Task.Factory.StartNew(() => DynamicResultMapper.MapToType<TResult>(source, _mapper, expression)); } }
mit
C#
555a71c13f5d1773f99e1a501584ad5a189c0390
Fix indirizzo località
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
src/backend/SO115App.Models/Classi/Condivise/Localita.cs
src/backend/SO115App.Models/Classi/Condivise/Localita.cs
//----------------------------------------------------------------------- // <copyright file="Localita.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF 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. // // SOVVF 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/. // </copyright> //----------------------------------------------------------------------- using System.ComponentModel.DataAnnotations; using System.Linq; namespace SO115App.API.Models.Classi.Condivise { public class Localita { public Localita(Coordinate _coordinate, string Indirizzo, string Note = null) { this.Coordinate = _coordinate; this.Note = Note; this.Indirizzo = Indirizzo; } private Localita() { } //Via Camillo Benso di Cavour 5, 00059, Tolfa, Roma [Required] public Coordinate Coordinate { get; set; } public string[] CoordinateString { get { string[] coordinate = new string[2]; coordinate[0] = this.Coordinate.Latitudine.ToString().Replace(",", "."); coordinate[1] = this.Coordinate.Longitudine.ToString().Replace(",", "."); return coordinate; } } public string Indirizzo { get; set; } public string Civico { get; set; } public string Citta { get; set; } public string Provincia { get; set; } public string Regione { get; set; } public string Interno { get; set; } public string cap { get; set; } public string Palazzo { get; set; } public string Scala { get; set; } public string Note { get; set; } public string Piano { get; set; } } }
//----------------------------------------------------------------------- // <copyright file="Localita.cs" company="CNVVF"> // Copyright (C) 2017 - CNVVF // // This file is part of SOVVF. // SOVVF 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. // // SOVVF 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/. // </copyright> //----------------------------------------------------------------------- using System.ComponentModel.DataAnnotations; using System.Linq; namespace SO115App.API.Models.Classi.Condivise { public class Localita { public Localita(Coordinate _coordinate, string Indirizzo, string Note = null) { this.Coordinate = _coordinate; this.Note = Note; } private Localita() { } //Via Camillo Benso di Cavour 5, 00059, Tolfa, Roma [Required] public Coordinate Coordinate { get; set; } public string[] CoordinateString { get { string[] coordinate = new string[2]; coordinate[0] = this.Coordinate.Latitudine.ToString().Replace(",", "."); coordinate[1] = this.Coordinate.Longitudine.ToString().Replace(",", "."); return coordinate; } } public string Indirizzo { get; set; } public string Civico { get; set; } public string Citta { get; set; } public string Provincia { get; set; } public string Regione { get; set; } public string Interno { get; set; } public string cap { get; set; } public string Palazzo { get; set; } public string Scala { get; set; } public string Note { get; set; } public string Piano { get; set; } } }
agpl-3.0
C#
397c73e786aa8c49ff233fc74bab2ec1bdd24657
Add audio adjustment support to `Metronome`
NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu
osu.Game/Rulesets/Mods/Metronome.cs
osu.Game/Rulesets/Mods/Metronome.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.Audio; using osu.Framework.Audio.Track; using osu.Framework.Bindables; using osu.Game.Audio; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; using osu.Game.Skinning; namespace osu.Game.Rulesets.Mods { public class Metronome : BeatSyncedContainer, IAdjustableAudioComponent { private readonly double firstHitTime; private readonly PausableSkinnableSound sample; /// <param name="firstHitTime">Start time of the first hit object, used for providing a count down.</param> public Metronome(double firstHitTime) { this.firstHitTime = firstHitTime; AllowMistimedEventFiring = false; Divisor = 1; InternalChild = sample = new PausableSkinnableSound(new SampleInfo("Gameplay/catch-banana")); } protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes) { base.OnNewBeat(beatIndex, timingPoint, effectPoint, amplitudes); if (!IsBeatSyncedWithTrack) return; int timeSignature = (int)timingPoint.TimeSignature; // play metronome from one measure before the first object. if (BeatSyncClock.CurrentTime < firstHitTime - timingPoint.BeatLength * timeSignature) return; sample.Frequency.Value = beatIndex % timeSignature == 0 ? 1 : 0.5f; sample.Play(); } #region IAdjustableAudioComponent public IBindable<double> AggregateVolume => sample.AggregateVolume; public IBindable<double> AggregateBalance => sample.AggregateBalance; public IBindable<double> AggregateFrequency => sample.AggregateFrequency; public IBindable<double> AggregateTempo => sample.AggregateTempo; public BindableNumber<double> Volume => sample.Volume; public BindableNumber<double> Balance => sample.Balance; public BindableNumber<double> Frequency => sample.Frequency; public BindableNumber<double> Tempo => sample.Tempo; public void BindAdjustments(IAggregateAudioAdjustment component) { sample.BindAdjustments(component); } public void UnbindAdjustments(IAggregateAudioAdjustment component) { sample.UnbindAdjustments(component); } public void AddAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) { sample.AddAdjustment(type, adjustBindable); } public void RemoveAdjustment(AdjustableProperty type, IBindable<double> adjustBindable) { sample.RemoveAdjustment(type, adjustBindable); } public void RemoveAllAdjustments(AdjustableProperty type) { sample.RemoveAllAdjustments(type); } #endregion } }
// 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.Audio.Track; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Graphics.Containers; using osu.Game.Skinning; namespace osu.Game.Rulesets.Mods { public class Metronome : BeatSyncedContainer { private readonly double firstHitTime; private PausableSkinnableSound sample; /// <param name="firstHitTime">Start time of the first hit object, used for providing a count down.</param> public Metronome(double firstHitTime) { this.firstHitTime = firstHitTime; AllowMistimedEventFiring = false; Divisor = 1; } [BackgroundDependencyLoader] private void load() { InternalChildren = new Drawable[] { sample = new PausableSkinnableSound(new SampleInfo("Gameplay/catch-banana")) }; } protected override void OnNewBeat(int beatIndex, TimingControlPoint timingPoint, EffectControlPoint effectPoint, ChannelAmplitudes amplitudes) { base.OnNewBeat(beatIndex, timingPoint, effectPoint, amplitudes); if (!IsBeatSyncedWithTrack) return; int timeSignature = (int)timingPoint.TimeSignature; // play metronome from one measure before the first object. if (BeatSyncClock.CurrentTime < firstHitTime - timingPoint.BeatLength * timeSignature) return; sample.Frequency.Value = beatIndex % timeSignature == 0 ? 1 : 0.5f; sample.Play(); } } }
mit
C#
503d238a2d80f5c784d1cd55a20a4364ff53cc09
Fix path to internal test data location
BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB,BrightstarDB/BrightstarDB
src/core/BrightstarDB.InternalTests/TestConfiguration.cs
src/core/BrightstarDB.InternalTests/TestConfiguration.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrightstarDB.InternalTests { internal static class TestConfiguration { public static string DataLocation = "..\\..\\..\\Data\\"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BrightstarDB.InternalTests { internal static class TestConfiguration { public static string DataLocation = "..\\..\\Data\\"; } }
mit
C#
ab43f8277150a6fc231cff57132899b28b5f5f0f
Update audio_ffmpeg.cs
AntiTcb/Discord.Net,Confruggy/Discord.Net,LassieME/Discord.Net,RogueException/Discord.Net
docs/guides/samples/audio_ffmpeg.cs
docs/guides/samples/audio_ffmpeg.cs
private async Task SendAsync(IAudioClient client, string path) { // Create FFmpeg using the previous example var ffmpeg = CreateStream(path); var output = ffmpeg.StandardOutput.BaseStream; var discord = client.CreatePCMStream(AudioApplication.Mixed, 1920); await output.CopyToAsync(discord); await discord.FlushAsync(); }
private async Task SendAsync(IAudioClient client, string path) { // Create FFmpeg using the previous example var ffmpeg = CreateStream(path); var output = ffmpeg.StandardOutput.BaseStream; var discord = client.CreatePCMStream(1920); await output.CopyToAsync(discord); await discord.FlushAsync(); }
mit
C#
25f59e0489a292b825f60af57d6a8ac9df7e1692
Add failing test cases
NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,peppy/osu,smoogipoo/osu
osu.Game.Rulesets.Osu.Tests/Mods/TestSceneOsuModSpunOut.cs
osu.Game.Rulesets.Osu.Tests/Mods/TestSceneOsuModSpunOut.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 System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osuTK; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModSpunOut : OsuModTestScene { protected override bool AllowFail => true; [Test] public void TestSpinnerAutoCompleted() => CreateModTest(new ModTestData { Mod = new OsuModSpunOut(), Autoplay = false, Beatmap = singleSpinnerBeatmap, PassCondition = () => Player.ChildrenOfType<DrawableSpinner>().Single().Progress >= 1 }); [TestCase(null)] [TestCase(typeof(OsuModDoubleTime))] [TestCase(typeof(OsuModHalfTime))] public void TestSpinRateUnaffectedByMods(Type additionalModType) { var mods = new List<Mod> { new OsuModSpunOut() }; if (additionalModType != null) mods.Add((Mod)Activator.CreateInstance(additionalModType)); CreateModTest(new ModTestData { Mods = mods, Autoplay = false, Beatmap = singleSpinnerBeatmap, PassCondition = () => Precision.AlmostEquals(Player.ChildrenOfType<SpinnerSpmCounter>().Single().SpinsPerMinute, 286, 1) }); } private Beatmap singleSpinnerBeatmap => new Beatmap { HitObjects = new List<HitObject> { new Spinner { Position = new Vector2(256, 192), StartTime = 500, Duration = 2000 } } }; } }
// 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 System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osuTK; namespace osu.Game.Rulesets.Osu.Tests.Mods { public class TestSceneOsuModSpunOut : OsuModTestScene { [Test] public void TestSpinnerAutoCompleted() => CreateModTest(new ModTestData { Mod = new OsuModSpunOut(), Autoplay = false, Beatmap = new Beatmap { HitObjects = new List<HitObject> { new Spinner { Position = new Vector2(256, 192), StartTime = 500, Duration = 2000 } } }, PassCondition = () => Player.ChildrenOfType<DrawableSpinner>().Single().Progress >= 1 }); } }
mit
C#
397066663b96a176315aec22031d40f026398f0a
Add missing Platform
AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia
src/Avalonia.Base/Logging/LogArea.cs
src/Avalonia.Base/Logging/LogArea.cs
namespace Avalonia.Logging { /// <summary> /// Specifies the area in which a log event occurred. /// </summary> public static class LogArea { /// <summary> /// The log event comes from the property system. /// </summary> public const string Property = "Property"; /// <summary> /// The log event comes from the binding system. /// </summary> public const string Binding = "Binding"; /// <summary> /// The log event comes from the animations system. /// </summary> public const string Animations = "Animations"; /// <summary> /// The log event comes from the visual system. /// </summary> public const string Visual = "Visual"; /// <summary> /// The log event comes from the layout system. /// </summary> public const string Layout = "Layout"; /// <summary> /// The log event comes from the control system. /// </summary> public const string Control = "Control"; /// <summary> /// The log event comes from Win32 Platform. /// </summary> public const string Win32Platform = nameof(Win32Platform); /// <summary> /// The log event comes from X11 Platform. /// </summary> public const string X11Platform = nameof(X11Platform); /// <summary> /// The log event comes from Android Platform. /// </summary> public const string AndroidPlatform = nameof(AndroidPlatform); /// <summary> /// The log event comes from iOS Platform. /// </summary> public const string IOSPlatform = nameof(IOSPlatform); /// <summary> /// The log event comes from LinuxFramebuffer Platform /// </summary> public const string LinuxFramebufferPlatform = nameof(LinuxFramebufferPlatform); /// <summary> /// The log event comes from FreeDesktop Platform /// </summary> public const string FreeDesktopPlatform = nameof(FreeDesktopPlatform); /// <summary> /// The log event comes from macOS Platform /// </summary> public const string macOSPlatform = nameof(macOSPlatform); } }
namespace Avalonia.Logging { /// <summary> /// Specifies the area in which a log event occurred. /// </summary> public static class LogArea { /// <summary> /// The log event comes from the property system. /// </summary> public const string Property = "Property"; /// <summary> /// The log event comes from the binding system. /// </summary> public const string Binding = "Binding"; /// <summary> /// The log event comes from the animations system. /// </summary> public const string Animations = "Animations"; /// <summary> /// The log event comes from the visual system. /// </summary> public const string Visual = "Visual"; /// <summary> /// The log event comes from the layout system. /// </summary> public const string Layout = "Layout"; /// <summary> /// The log event comes from the control system. /// </summary> public const string Control = "Control"; /// <summary> /// The log event comes from Win32Platform. /// </summary> public const string Win32Platform = nameof(Win32Platform); /// <summary> /// The log event comes from X11Platform. /// </summary> public const string X11Platform = nameof(X11Platform); /// <summary> /// The log event comes from AndroidPlatform. /// </summary> public const string AndroidPlatform = nameof(AndroidPlatform); /// <summary> /// The log event comes from IOSPlatform. /// </summary> public const string IOSPlatform = nameof(IOSPlatform); } }
mit
C#
1fd975f333c4a149e9b3b036f2a75f6aba0cc36b
Remove debug info
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Payment/Receipt.cshtml
Anlab.Mvc/Views/Payment/Receipt.cshtml
@model AnlabMvc.Models.CyberSource.ReceiptResponseModel @{ ViewData["Title"] = "Receipt"; //var paymentDict = (Dictionary<string, string>)ViewBag.PaymentDictionary; } <h1>Thank you for your payment.</h1> <h2>@Model.Auth_Amount</h2> @*<div> <h2>Debugging Info</h2> <div> @foreach (var key in paymentDict) { <p>@key.Key -- @key.Value</p> } </div> </div>*@
@model AnlabMvc.Models.CyberSource.ReceiptResponseModel @{ ViewData["Title"] = "Receipt"; var paymentDict = (Dictionary<string, string>)ViewBag.PaymentDictionary; } <h2>Receipt</h2> <h1>@Model.Auth_Amount</h1> <div> <h2>Debugging Info</h2> <div> @foreach (var key in paymentDict) { <p>@key.Key -- @key.Value</p> } </div> </div>
mit
C#
a2d3767ea940dbb49aaba26bcfbaf6461b679ccc
copy and paste is a bitch
mzrimsek/resume-site-api
Core/Interfaces/ILanguageRepository.cs
Core/Interfaces/ILanguageRepository.cs
using System.Collections.Generic; using Core.Models; namespace Core.Interfaces { public interface ILanguageRepository { IEnumerable<LanguageDomainModel> GetAll(); LanguageDomainModel GetById(int id); LanguageDomainModel Save(LanguageDomainModel language); void Delete(int id); } }
using System.Collections.Generic; using Core.Models; namespace Core.Interfaces { public interface ILanguageRepository { IEnumerable<LanguageDomainModel> GetAll(); LanguageDomainModel GetById(int id); LanguageDomainModel Save(LanguageDomainModel job); void Delete(int id); } }
mit
C#
bcaccc0bbcf0b16b9006b52f19cbf9ee6b530112
Add more comments
attemoi/MoistureBot
SampleAddins/GameInviteReply/GameInviteReply.cs
SampleAddins/GameInviteReply/GameInviteReply.cs
using System; using Mono.Addins; using MoistureBot.ExtensionPoints; using MoistureBot.Steam; using System.Xml; using System.Collections.Generic; using System.Threading; [assembly:Addin("GameInviteReply", "1.0")] [assembly:AddinDependency("MoistureBot", "1.0")] [assembly:AddinAuthor("Atte Moisio")] [assembly:AddinDescription("Reply to game invites.")] [assembly:AddinName("GameInviteReply")] [assembly:AddinUrl("")] [assembly:ImportAddinFile ("GameInviteReply.xml")] namespace MoistureBot { [Extension(typeof(IReceiveGameLobbyInvites))] public class GameInviteReply : IReceiveGameLobbyInvites { static Random rnd = new Random(); IMoistureBot Bot = MoistureBotComponentProvider.GetBot(); ILogger Logger = MoistureBotComponentProvider.GetLogger(); public void InviteReceived(GameLobbyInvite invite) { // GameInviteReply.xml example data: // // <?xml version="1.0" encoding="UTF-8" ?> // <replies> // // <reply> // <message>Hello, Thank you for the invite!</message> // <message>Unfortunately, I don't have a mouse or a keyboard.</message> // </reply> // // <reply> // <message>Hmm, let me think about this...</message> // <message>...</message> // <message>...</message> // <message>No.</message> // </reply> // // </replies> List<List<string>> replies = new List<List<string>>(); using (XmlTextReader reader = new XmlTextReader("addins/GameInviteReply.xml")) { reader.ReadToFollowing("replies"); while (reader.ReadToFollowing("reply")) { var messages = new List<string>(); if (reader.ReadToDescendant("message")) { do { messages.Add(reader.ReadElementContentAsString()); } while (reader.ReadToNextSibling("message")); } replies.Add(messages); } } // We should now have a list of possible replies // => pick one randomly and send the messages int r = rnd.Next(replies.Count); foreach (string message in replies[r]) { Bot.SendChatMessage(message, invite.InviterId); Thread.Sleep(1000); } } } }
using System; using Mono.Addins; using MoistureBot.ExtensionPoints; using MoistureBot.Steam; using System.Xml; using System.Collections.Generic; using System.Threading; [assembly:Addin("GameInviteReply", "1.0")] [assembly:AddinDependency("MoistureBot", "1.0")] [assembly:AddinAuthor("Atte Moisio")] [assembly:AddinDescription("Reply to game invites.")] [assembly:AddinName("GameInviteReply")] [assembly:AddinUrl("")] [assembly:ImportAddinFile ("GameInviteReply.xml")] namespace MoistureBot { [Extension(typeof(IReceiveGameLobbyInvites))] public class GameInviteReply : IReceiveGameLobbyInvites { static Random rnd = new Random(); IMoistureBot Bot = MoistureBotComponentProvider.GetBot(); ILogger Logger = MoistureBotComponentProvider.GetLogger(); public void InviteReceived(GameLobbyInvite invite) { List<List<string>> replies = new List<List<string>>(); using (XmlTextReader reader = new XmlTextReader("addins/GameInviteReply.xml")) { // Parse the file and display each of the nodes. reader.ReadToFollowing("replies"); while (reader.ReadToFollowing("reply")) { var messages = new List<string>(); if (reader.ReadToDescendant("message")) { do { messages.Add(reader.ReadElementContentAsString()); } while (reader.ReadToNextSibling("message")); } replies.Add(messages); } } // We should now have a list of possible replies int r = rnd.Next(replies.Count); foreach (string message in replies[r]) { Bot.SendChatMessage(message, invite.InviterId); Thread.Sleep(1000); } } } }
mit
C#
c58226913a803ee4ce23c4cb838ba03409b86ef4
Improve constants.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Core/TraktConstants.cs
Source/Lib/TraktApiSharp/Core/TraktConstants.cs
namespace TraktApiSharp.Core { internal static class TraktConstants { internal static readonly string APIClientIdHeaderKey = "trakt-api-key"; internal static readonly string APIVersionHeaderKey = "trakt-api-version"; internal static readonly string OAuthBaseAuthorizeUrl = "https://trakt.tv"; internal static readonly string OAuthAuthorizeUri = "oauth/authorize"; internal static readonly string OAuthTokenUri = "oauth/token"; internal static readonly string OAuthRevokeUri = "oauth/revoke"; internal static readonly string OAuthDeviceCodeUri = "oauth/device/code"; internal static readonly string OAuthDeviceTokenUri = "oauth/device/token"; } }
namespace TraktApiSharp.Core { internal static class TraktConstants { internal static string APIClientIdHeaderKey = "trakt-api-key"; internal static string APIVersionHeaderKey = "trakt-api-version"; internal static string OAuthBaseAuthorizeUrl => "https://trakt.tv"; internal static string OAuthAuthorizeUri => "oauth/authorize"; internal static string OAuthTokenUri => "oauth/token"; internal static string OAuthRevokeUri => "oauth/revoke"; internal static string OAuthDeviceCodeUri => "oauth/device/code"; internal static string OAuthDeviceTokenUri => "oauth/device/token"; } }
mit
C#
48c94f78a10fb6fc0e4b5355e7047969e6ad7d36
update progress
justcoding121/Advanced-Algorithms,justcoding121/Algorithm-Sandbox
Algorithm.Sandbox/DataStructures/Tree/AsBTree.cs
Algorithm.Sandbox/DataStructures/Tree/AsBTree.cs
using System; namespace Algorithm.Sandbox.DataStructures.Tree { internal class AsBTreeNode<T> where T : IComparable { public T[] Values { get; set; } public AsBTreeNode<T> Parent { get; set; } public AsBTreeNode<T>[] Children { get; set; } public int Count { get; internal set; } public AsBTreeNode(int maxChildren) { Values = new T[maxChildren]; Children = new AsBTreeNode<T>[maxChildren + 1]; } } public class AsBTree<T> where T : IComparable { public int Count { get; private set; } internal AsBTreeNode<T> Root; private int maxChildren; public AsBTree(int maxChildren) { this.maxChildren = maxChildren; } public void Insert(T value) { var nodeToInsert = FindInsertionNode(ref Root, value); if (nodeToInsert.Count == nodeToInsert.Values.Length) { } } private AsBTreeNode<T> FindInsertionNode(ref AsBTreeNode<T> node, T value) { if (node == null) { node = new AsBTreeNode<T>(maxChildren); return node; } throw new NotImplementedException(); } public void Delete(T value) { } public bool Exists(T value) { throw new NotImplementedException(); } } }
using System; namespace Algorithm.Sandbox.DataStructures.Tree { internal class AsBTreeNode<T> where T : IComparable { public AsArrayList<T> Value { get; set; } public AsBTreeNode<T> Parent { get; set; } public AsArrayList<AsBTreeNode<T>> Children { get; set; } } public class AsBTree<T> where T : IComparable { public int Count { get; private set; } internal AsBTreeNode<T> Root; public void Insert(T value) { } public void Delete(T value) { } public bool Exists(T value) { throw new NotImplementedException(); } } }
mit
C#
bfc9cb955232d806a914c3603ee89b3423e43840
Fix cherry pick, spaces not tabs and remove unused delegate
rover886/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,AJDev77/CefSharp,dga711/CefSharp,battewr/CefSharp,wangzheng888520/CefSharp,rlmcneary2/CefSharp,Octopus-ITSM/CefSharp,yoder/CefSharp,ruisebastiao/CefSharp,ITGlobal/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,illfang/CefSharp,dga711/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,ruisebastiao/CefSharp,rover886/CefSharp,joshvera/CefSharp,yoder/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,dga711/CefSharp,Livit/CefSharp,AJDev77/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,twxstar/CefSharp,windygu/CefSharp,Livit/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,illfang/CefSharp,NumbersInternational/CefSharp,haozhouxu/CefSharp,rover886/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,ruisebastiao/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,VioletLife/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,yoder/CefSharp,illfang/CefSharp,Octopus-ITSM/CefSharp,battewr/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,zhangjingpu/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,illfang/CefSharp,haozhouxu/CefSharp
CefSharp/IsBrowserInitializedChangedEventArgs.cs
CefSharp/IsBrowserInitializedChangedEventArgs.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the IsBrowserInitializedChanged event handler. /// </summary> public class IsBrowserInitializedChangedEventArgs : EventArgs { public bool IsBrowserInitialized { get; private set; } public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized) { IsBrowserInitialized = isBrowserInitialized; } } }
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; namespace CefSharp { /// <summary> /// Event arguments to the IsBrowserInitializedChanged event handler. /// </summary> public class IsBrowserInitializedChangedEventArgs : EventArgs { public bool IsBrowserInitialized { get; private set; } public IsBrowserInitializedChangedEventArgs(bool isBrowserInitialized) { IsBrowserInitialized = isBrowserInitialized; } } }; /// <summary> /// A delegate type used to listen to IsBrowserInitializedChanged events. /// </summary> public delegate void IsBrowserInitializedChangedEventHandler(object sender, IsBrowserInitializedChangedEventArgs args); }
bsd-3-clause
C#
90985b6af65a6008b55fd968d523e7c9ebc40d05
Add missing license header
NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,johnneijzen/osu,peppy/osu,ZLima12/osu,EVAST9919/osu,peppy/osu-new,peppy/osu,ppy/osu,smoogipooo/osu,2yangk23/osu,ZLima12/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu
osu.Game/Skinning/SkinUtils.cs
osu.Game/Skinning/SkinUtils.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.Bindables; namespace osu.Game.Skinning { /// <summary> /// Contains helper methods to assist in implementing <see cref="ISkin"/>s. /// </summary> public static class SkinUtils { /// <summary> /// Converts an <see cref="object"/> to a <see cref="Bindable{TValue}"/>. Used for returning configuration values of specific types. /// </summary> /// <param name="value">The value.</param> /// <typeparam name="TValue">The type of value <paramref name="value"/>, and the type of the resulting bindable.</typeparam> /// <returns>The resulting bindable.</returns> public static Bindable<TValue> As<TValue>(object value) => (Bindable<TValue>)value; } }
using osu.Framework.Bindables; namespace osu.Game.Skinning { /// <summary> /// Contains helper methods to assist in implementing <see cref="ISkin"/>s. /// </summary> public static class SkinUtils { /// <summary> /// Converts an <see cref="object"/> to a <see cref="Bindable{TValue}"/>. Used for returning configuration values of specific types. /// </summary> /// <param name="value">The value.</param> /// <typeparam name="TValue">The type of value <paramref name="value"/>, and the type of the resulting bindable.</typeparam> /// <returns>The resulting bindable.</returns> public static Bindable<TValue> As<TValue>(object value) => (Bindable<TValue>)value; } }
mit
C#
ed020e0269e326e7a51cb855e83891c27b9daf21
Update moment.js
martincostello/api,martincostello/api,martincostello/api
src/API/Pages/Shared/_Scripts.cshtml
src/API/Pages/Shared/_Scripts.cshtml
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/js/bootstrap.bundle.min.js" integrity="sha512-9GacT4119eY3AcosfWtHMsT5JyZudrexyEVzTBWV3viP/YfB9e2pEy3N7WXL3SV6ASXpTU0vzzSxsbfsuUH4sQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js" integrity="sha512-jNDtFf7qgU0eH/+Z42FG4fw3w7DM/9zbgNPe3wfJlCylVDTT3IgKW5r92Vy9IHa6U50vyMz5gRByIu4YIXFtaQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js" integrity="sha512-CryKbMe7sjSCDPl18jtJI5DR5jtkUWxPXWaLCst6QjH8wxDexfRJic2WRmRXmstr2Y8SxDDWuBO6CQC6IE4KTA==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> @{ var analyticsId = Options.Value.Analytics?.Google; } @if (!string.IsNullOrWhiteSpace(analyticsId)) { <script src="https://www.googletagmanager.com/gtag/js?id=@(analyticsId)" async></script> } <environment names="Development"> <script src="~/assets/js/site.js" asp-append-version="true" defer></script> </environment> <environment names="Staging,Production"> <script src="~/assets/js/site.min.js" asp-append-version="true" defer></script> </environment>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.2.0/js/bootstrap.bundle.min.js" integrity="sha512-9GacT4119eY3AcosfWtHMsT5JyZudrexyEVzTBWV3viP/YfB9e2pEy3N7WXL3SV6ASXpTU0vzzSxsbfsuUH4sQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js" integrity="sha512-jNDtFf7qgU0eH/+Z42FG4fw3w7DM/9zbgNPe3wfJlCylVDTT3IgKW5r92Vy9IHa6U50vyMz5gRByIu4YIXFtaQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js" integrity="sha512-dGM81hdEjiW5IomkknOx3fIfwij3c7xwh6TcrbumlkHJtO81OKNjLISJaPEhCgVxM6+0uGJ7KRmI2YJFn0AmHQ==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script> @{ var analyticsId = Options.Value.Analytics?.Google; } @if (!string.IsNullOrWhiteSpace(analyticsId)) { <script src="https://www.googletagmanager.com/gtag/js?id=@(analyticsId)" async></script> } <environment names="Development"> <script src="~/assets/js/site.js" asp-append-version="true" defer></script> </environment> <environment names="Staging,Production"> <script src="~/assets/js/site.min.js" asp-append-version="true" defer></script> </environment>
mit
C#
146f85c30d73e04dfdc02b4a3dad4fec8ed3283d
Update XTemplates.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Collections/XTemplates.cs
src/Core2D/Collections/XTemplates.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Immutable; using Core2D.Attributes; using Core2D.Project; namespace Core2D.Collections { /// <summary> /// Observable <see cref="XContainer"/> collection. /// </summary> public class XTemplates : ObservableResource { /// <summary> /// Gets or sets resource name. /// </summary> [Name] public string Name { get; set; } /// <summary> /// Gets or sets children collection. /// </summary> [Content] public ImmutableArray<XContainer> Children { get; set; } /// <summary> /// Initializes a new instance of the <see cref="XContainer"/> class. /// </summary> public XTemplates() { Children = ImmutableArray.Create<XContainer>(); } /// <summary> /// Check whether the <see cref="Name"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeName() => !String.IsNullOrWhiteSpace(Name); /// <summary> /// Check whether the <see cref="Children"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeChildren() => Children.IsEmpty == false; } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using Core2D.Attributes; using Core2D.Project; namespace Core2D.Collections { /// <summary> /// Observable <see cref="XContainer"/> collection. /// </summary> public class XTemplates : ObservableResource { /// <summary> /// Gets or sets resource name. /// </summary> [Name] public string Name { get; set; } /// <summary> /// Gets or sets children collection. /// </summary> [Content] public ImmutableArray<XContainer> Children { get; set; } /// <summary> /// Initializes a new instance of the <see cref="XContainer"/> class. /// </summary> public XTemplates() { Children = ImmutableArray.Create<XContainer>(); } } }
mit
C#
e9a18f8f1b17e7046f7e4ba7e693cb5fd9df6441
Fix tableName not correctly saved
lecaillon/Evolve
src/Evolve/Metadata/MetadataTable.cs
src/Evolve/Metadata/MetadataTable.cs
using Evolve.Migration; using System.Collections.Generic; using Evolve.Utilities; using Evolve.Connection; namespace Evolve.Metadata { public abstract class MetadataTable : IEvolveMetadata { protected IWrappedConnection _wrappedConnection; public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection) { Schema = Check.NotNullOrEmpty(schema, nameof(schema)); TableName = Check.NotNullOrEmpty(tableName, nameof(tableName)); _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection)); } public string Schema { get; private set; } public string TableName { get; private set; } public abstract void Lock(); public abstract bool CreateIfNotExists(); public void AddMigrationMetadata(MigrationScript migration, bool success) { CreateIfNotExists(); InternalAddMigrationMetadata(migration, success); } public IEnumerable<MigrationMetadata> GetAllMigrationMetadata() { CreateIfNotExists(); return InternalGetAllMigrationMetadata(); } protected abstract bool IsExists(); protected abstract void Create(); protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success); protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata(); } }
using Evolve.Migration; using System.Collections.Generic; using Evolve.Utilities; using Evolve.Connection; namespace Evolve.Metadata { public abstract class MetadataTable : IEvolveMetadata { protected IWrappedConnection _wrappedConnection; public MetadataTable(string schema, string tableName, IWrappedConnection wrappedConnection) { Schema = Check.NotNullOrEmpty(schema, nameof(schema)); TableName = Check.NotNullOrEmpty(schema, nameof(tableName)); _wrappedConnection = Check.NotNull(wrappedConnection, nameof(wrappedConnection)); } public string Schema { get; private set; } public string TableName { get; private set; } public abstract void Lock(); public abstract bool CreateIfNotExists(); public void AddMigrationMetadata(MigrationScript migration, bool success) { CreateIfNotExists(); InternalAddMigrationMetadata(migration, success); } public IEnumerable<MigrationMetadata> GetAllMigrationMetadata() { CreateIfNotExists(); return InternalGetAllMigrationMetadata(); } protected abstract bool IsExists(); protected abstract void Create(); protected abstract void InternalAddMigrationMetadata(MigrationScript migration, bool success); protected abstract IEnumerable<MigrationMetadata> InternalGetAllMigrationMetadata(); } }
mit
C#
148b32ac59a7a3537d3cf4cc1d33061d8c224655
Fix FileExistsCondition.IsMet logic.
jinlook/NAppUpdate,synhershko/NAppUpdate,piotrwest/NAppUpdateMono,johnrossell/NAppUpdate,piotrwest/NAppUpdateMono,vbjay/NAppUpdate,group6tech/NAppUpdate2,miguel-misstipsi/NAppUpdate2,lexruster/NAppUpdate,halotron/NAppUpdate
src/NAppUpdate.Framework/Conditions/FileExistsCondition.cs
src/NAppUpdate.Framework/Conditions/FileExistsCondition.cs
using System; using System.Collections.Generic; using System.IO; using NAppUpdate.Framework.Common; namespace NAppUpdate.Framework.Conditions { [Serializable] [UpdateConditionAlias("exists")] public class FileExistsCondition : IUpdateCondition { [NauField("localPath", "The local path of the file to check. If not set but set under a FileUpdateTask, the LocalPath of the task will be used. Otherwise this condition will be ignored." , false)] public string LocalPath { get; set; } #region IUpdateCondition Members public IDictionary<string, string> Attributes { get; private set; } public bool IsMet(Tasks.IUpdateTask task) { string localPath = !string.IsNullOrEmpty(LocalPath) ? LocalPath : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string; if (string.IsNullOrEmpty(localPath) || !File.Exists(localPath)) return true; return false; } #endregion } }
using System; using System.Collections.Generic; using System.IO; using NAppUpdate.Framework.Common; namespace NAppUpdate.Framework.Conditions { [Serializable] [UpdateConditionAlias("exists")] public class FileExistsCondition : IUpdateCondition { [NauField("localPath", "The local path of the file to check. If not set but set under a FileUpdateTask, the LocalPath of the task will be used. Otherwise this condition will be ignored." , false)] public string LocalPath { get; set; } #region IUpdateCondition Members public IDictionary<string, string> Attributes { get; private set; } public bool IsMet(Tasks.IUpdateTask task) { string localPath = !string.IsNullOrEmpty(LocalPath) ? LocalPath : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string; if (string.IsNullOrEmpty(localPath) || !File.Exists(localPath)) return true; return !string.IsNullOrEmpty(localPath) && File.Exists(localPath); } #endregion } }
apache-2.0
C#
e41c42598834d6d19d174320b8d4413fd8bf46d6
Change the casting way of event number
Archie-Yang/PcscDotNet
src/PcscDotNet/PcscReaderStatus_1.cs
src/PcscDotNet/PcscReaderStatus_1.cs
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; namespace PcscDotNet { public sealed class PcscReaderStatus<TIScardReaderState> : PcscReaderStatus where TIScardReaderState : struct, ISCardReaderState { private readonly TIScardReaderState[] _readerStates; private unsafe static void CopyAndFree(IPcscProvider provider, ref TIScardReaderState src, PcscReaderState dest) { var state = src.EventState; src.CurrentState = state; dest.Atr = src.Atr; dest.EventNumber = ((int)state >> 16) & 0x0000FFFF; dest.State = state & (SCardReaderStates)0x0000FFFF; provider.FreeString(src.Reader); } public PcscReaderStatus(PcscContext context, IList<string> readerNames) : base(context, readerNames) { _readerStates = new TIScardReaderState[readerNames.Count]; } public unsafe override PcscReaderStatus WaitForChanged(int timeout = Timeout.Infinite) { if (Context.IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(WaitForChanged)); var provider = Context.Pcsc.Provider; var readerStates = _readerStates; var length = readerStates.Length; GCHandle hReaderStates; try { for (var i = 0; i < length; ++i) { readerStates[i].Reader = (void*)provider.AllocateString(Items[i].ReaderName); } hReaderStates = GCHandle.Alloc(readerStates, GCHandleType.Pinned); provider.SCardGetStatusChange(Context.Handle, timeout, (void*)hReaderStates.AddrOfPinnedObject(), length).ThrowIfNotSuccess(); } finally { if (hReaderStates.IsAllocated) hReaderStates.Free(); for (var i = 0; i < length; ++i) { CopyAndFree(provider, ref readerStates[i], Items[i]); } } return this; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; namespace PcscDotNet { public sealed class PcscReaderStatus<TIScardReaderState> : PcscReaderStatus where TIScardReaderState : struct, ISCardReaderState { private readonly TIScardReaderState[] _readerStates; private unsafe static void CopyAndFree(IPcscProvider provider, ref TIScardReaderState src, PcscReaderState dest) { var state = src.EventState; src.CurrentState = state; dest.Atr = src.Atr; dest.EventNumber = (int)((long)state >> 16) & 0x0000FFFF; dest.State = state & (SCardReaderStates)0x0000FFFF; provider.FreeString(src.Reader); } public PcscReaderStatus(PcscContext context, IList<string> readerNames) : base(context, readerNames) { _readerStates = new TIScardReaderState[readerNames.Count]; } public unsafe override PcscReaderStatus WaitForChanged(int timeout = Timeout.Infinite) { if (Context.IsDisposed) throw new ObjectDisposedException(nameof(PcscContext), nameof(WaitForChanged)); var provider = Context.Pcsc.Provider; var readerStates = _readerStates; var length = readerStates.Length; GCHandle hReaderStates; try { for (var i = 0; i < length; ++i) { readerStates[i].Reader = (void*)provider.AllocateString(Items[i].ReaderName); } hReaderStates = GCHandle.Alloc(readerStates, GCHandleType.Pinned); provider.SCardGetStatusChange(Context.Handle, timeout, (void*)hReaderStates.AddrOfPinnedObject(), length).ThrowIfNotSuccess(); } finally { if (hReaderStates.IsAllocated) hReaderStates.Free(); for (var i = 0; i < length; ++i) { CopyAndFree(provider, ref readerStates[i], Items[i]); } } return this; } } }
mit
C#
0c43eaeeb5ef51571c935a9c6fcf3c0232b4d50c
Update SqliteConnectionStringParser.cs
msallin/SQLiteCodeFirst,liujunhua/SQLiteCodeFirst
SQLite.CodeFirst/SqliteConnectionStringParser.cs
SQLite.CodeFirst/SqliteConnectionStringParser.cs
using System.Collections.Generic; namespace SQLite.CodeFirst { internal static class SqliteConnectionStringParser { private const char KeyValuePairSeperator = ';'; private const char KeyValueSeperator = '='; private const int KeyPosition = 0; private const int ValuePosition = 1; public static IDictionary<string, string> ParseSqliteConnectionString(string connectionString) { connectionString = connectionString.Trim(); string[] keyValuePairs = connectionString.Split(KeyValuePairSeperator); IDictionary<string, string> keyValuePairDictionary = new Dictionary<string, string>(); foreach (var keyValuePair in keyValuePairs) { string[] keyValue = keyValuePair.Split(KeyValueSeperator); keyValuePairDictionary.Add(keyValue[KeyPosition].ToLower(), keyValue[ValuePosition]); } return keyValuePairDictionary; } public static string GetDataSource(string connectionString) { return ParseSqliteConnectionString(connectionString)["data source"]; } } }
using System.Collections.Generic; namespace SQLite.CodeFirst { internal static class SqliteConnectionStringParser { private const char KeyValuePairSeperator = ';'; private const char KeyValueSeperator = '='; private const int KeyPosition = 0; private const int ValuePosition = 1; public static IDictionary<string, string> ParseSqliteConnectionString(string connectionString) { connectionString = connectionString.Trim(); string[] keyValuePairs = connectionString.Split(KeyValuePairSeperator); IDictionary<string, string> keyValuePairDictionary = new Dictionary<string, string>(); foreach (var keyValuePair in keyValuePairs) { string[] keyValue = keyValuePair.Split(KeyValueSeperator); keyValuePairDictionary.Add(keyValue[KeyPosition], keyValue[ValuePosition]); } return keyValuePairDictionary; } public static string GetDataSource(string connectionString) { return ParseSqliteConnectionString(connectionString)["data source"]; } } }
apache-2.0
C#
a9bbf5f5be2fc8bfb0e78380ac028173790929b6
Fix Bahamas
tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date
Src/Nager.Date/PublicHolidays/BahamasProvider.cs
Src/Nager.Date/PublicHolidays/BahamasProvider.cs
using Nager.Date.Model; using System.Collections.Generic; using System.Linq; namespace Nager.Date.PublicHolidays { public class BahamasProvider : CatholicBaseProvider { public override IEnumerable<PublicHoliday> Get(int year) { //Bahamas //https://en.wikipedia.org/wiki/Public_holidays_in_the_Bahamas var countryCode = CountryCode.BS; var easterSunday = base.EasterSunday(year); var items = new List<PublicHoliday>(); items.Add(new PublicHoliday(year, 1, 1, "New Year's Day", "New Year's Day", countryCode)); items.Add(new PublicHoliday(year, 1, 10, "Majority Rule Day", "Majority Rule Day", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Good Friday", "Good Friday", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(1), "Easter Monday", "Easter Monday", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(50), "Whit Monday", "Whit Monday", countryCode)); items.Add(new PublicHoliday(year, 4, 1, "Perry Christie Day", "Perry Christie Day", countryCode)); items.Add(new PublicHoliday(year, 7, 10, "Independence Day", "Independence Day", countryCode)); items.Add(new PublicHoliday(year, 8, 5, "Emancipation Day", "Emancipation Day", countryCode)); items.Add(new PublicHoliday(year, 10, 12, "National Heroes' Day", "National Heroes' Day", countryCode)); items.Add(new PublicHoliday(year, 12, 25, "Christmas Day", "Christmas Day", countryCode)); items.Add(new PublicHoliday(year, 12, 26, "Boxing Day", "St. Stephen's Day", countryCode)); return items.OrderBy(o => o.Date); } } }
using Nager.Date.Model; using System.Collections.Generic; using System.Linq; namespace Nager.Date.PublicHolidays { public class BahamasProvider : CatholicBaseProvider { public override IEnumerable<PublicHoliday> Get(int year) { //Bahamas //https://en.wikipedia.org/wiki/Public_holidays_in_the_Bahamas var countryCode = CountryCode.BS; var easterSunday = base.EasterSunday(year); var items = new List<PublicHoliday>(); items.Add(new PublicHoliday(year, 1, 1, "New Year's Day", "New Year's Day", countryCode)); items.Add(new PublicHoliday(year, 1, 10, "Majority Rule Day", "Majority Rule Day", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Good Friday", "Good Friday", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(1), "Easter Monday", "Easter Monday", countryCode)); items.Add(new PublicHoliday(easterSunday.AddDays(50), "Whit Monday", "Whit Monday", countryCode)); items.Add(new PublicHoliday(year, 4, 1, "Perry Christie Day", "Perry Christie Day", countryCode)); items.Add(new PublicHoliday(year, 7, 10, "Independence Day", "Independence Day", countryCode)); items.Add(new PublicHoliday(year, 8, 5, "Emancipation Day", "Emancipation Day", countryCode)); items.Add(new PublicHoliday(year, 10, 12, "National Heroes' Day", "National Heroes' Day", countryCode)); items.Add(new PublicHoliday(year, 12, 25, "Christmas Day", "Christmas Day", countryCode)); items.Add(new PublicHoliday(year, 12, 26, "Boxing Day", "St. Stephen's Day", countryCode)); items.Add(new PublicHoliday(year, 12, 26, "Junkanoo", "Junkanoo", countryCode)); return items.OrderBy(o => o.Date); } } }
mit
C#
fecec9a859793feaeaf29bfac01e9baa49724db4
add computer type to enum
sghaida/ADWS
ADWS/Models/ADObjectTypecs.cs
ADWS/Models/ADObjectTypecs.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace ADWS.Models { [DataContract( Name = "ObjectType" )] public enum ObjectType { [EnumMember( Value = "USER" )] USER = 1 , [EnumMember( Value = "GROUP" )] GROUP = 2, [EnumMember( Value = "COMPUTER" )] COMPUTER = 3 }; }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Web; namespace ADWS.Models { [DataContract( Name = "ObjectType" )] public enum ObjectType { [EnumMember( Value = "USER" )] USER = 1 , [EnumMember( Value = "GROUP" )] GROUP = 2 }; }
apache-2.0
C#
31b118f60071e913cdd363567cc36c530e9687cf
Remove unused using directive.
jmptrader/elmah-mvc,fhchina/elmah-mvc,alexbeletsky/elmah-mvc,mmsaffari/elmah-mvc
src/Tests/Properties/AssemblyInfo.cs
src/Tests/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("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6e60a351-8538-431d-bd92-d87abed5145b")] // 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("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6e60a351-8538-431d-bd92-d87abed5145b")] // 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#
361b0d2db83f2bc00706f1bde137b3ca93b0f2de
Add tests for `kernel32!SetHandleInformation` and `kernel32!GetHandleInformation`
AArnott/pinvoke
src/Kernel32.Tests/Kernel32Facts.cs
src/Kernel32.Tests/Kernel32Facts.cs
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using System.Threading; using PInvoke; using Xunit; using static PInvoke.Kernel32; public partial class Kernel32Facts { [Fact] public void GetTickCount_Nonzero() { uint result = GetTickCount(); Assert.NotEqual(0u, result); } [Fact] public void GetTickCount64_Nonzero() { ulong result = GetTickCount64(); Assert.NotEqual(0ul, result); } [Fact] public void SetLastError_ImpactsMarshalGetLastWin32Error() { SetLastError(2); Assert.Equal(2, Marshal.GetLastWin32Error()); } [Fact] public unsafe void GetStartupInfo_Title() { var startupInfo = STARTUPINFO.Create(); GetStartupInfo(ref startupInfo); Assert.NotNull(startupInfo.Title); Assert.NotEqual(0, startupInfo.Title.Length); } [Fact] public void GetHandleInformation_DoesNotThrow() { var manualResetEvent = new ManualResetEvent(false); GetHandleInformation(manualResetEvent.SafeWaitHandle, out var lpdwFlags); } [Fact] public void SetHandleInformation_DoesNotThrow() { var manualResetEvent = new ManualResetEvent(false); SetHandleInformation( manualResetEvent.SafeWaitHandle, HandleFlags.HANDLE_FLAG_INHERIT | HandleFlags.HANDLE_FLAG_PROTECT_FROM_CLOSE, HandleFlags.HANDLE_FLAG_NONE); } }
// Copyright (c) All contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using PInvoke; using Xunit; using static PInvoke.Kernel32; public partial class Kernel32Facts { [Fact] public void GetTickCount_Nonzero() { uint result = GetTickCount(); Assert.NotEqual(0u, result); } [Fact] public void GetTickCount64_Nonzero() { ulong result = GetTickCount64(); Assert.NotEqual(0ul, result); } [Fact] public void SetLastError_ImpactsMarshalGetLastWin32Error() { SetLastError(2); Assert.Equal(2, Marshal.GetLastWin32Error()); } [Fact] public unsafe void GetStartupInfo_Title() { var startupInfo = STARTUPINFO.Create(); GetStartupInfo(ref startupInfo); Assert.NotNull(startupInfo.Title); Assert.NotEqual(0, startupInfo.Title.Length); } }
mit
C#
7246100bef279e20d41ee94d27c6f213d301e704
fix for pre 1.9 compilers
Yetangitu/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,mono/f-spot,Yetangitu/f-spot,dkoeb/f-spot,mono/f-spot,mans0954/f-spot,GNOME/f-spot,Sanva/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,mans0954/f-spot,nathansamson/F-Spot-Album-Exporter,NguyenMatthieu/f-spot,mono/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,GNOME/f-spot,mono/f-spot,dkoeb/f-spot,Sanva/f-spot,mans0954/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,Yetangitu/f-spot,GNOME/f-spot,Yetangitu/f-spot,dkoeb/f-spot,nathansamson/F-Spot-Album-Exporter,mono/f-spot,NguyenMatthieu/f-spot,Sanva/f-spot,GNOME/f-spot,Sanva/f-spot,GNOME/f-spot,nathansamson/F-Spot-Album-Exporter,dkoeb/f-spot,mans0954/f-spot,Yetangitu/f-spot,Sanva/f-spot
extensions/Tools/HashJob/HashJob.cs
extensions/Tools/HashJob/HashJob.cs
/* * HashJob.cs * * Author(s) * Stephane Delcroix <stephane@delcroix.org> * * This is free software. See COPYING for details */ using System; using System.Collections.Generic; using Mono.Unix; using Mono.Data.SqliteClient; using Gtk; using FSpot; using FSpot.UI.Dialog; using FSpot.Extensions; using FSpot.Jobs; namespace HashJobExtension { public class HashJob : ICommand { public void Run (object o, EventArgs e) { HashJobDialog dialog = new HashJobDialog (); dialog.ShowDialog (); } } public class HashJobDialog : Dialog { public void ShowDialog () { VBox.Spacing = 6; Label l = new Label ("In order to detect duplicates on pictures you imported before f-spot 0.5.0, f-spot need to analyze your image collection. This is is not done by default as it's time consuming. You can Start or Pause this update process using this dialog."); l.LineWrap = true; VBox.PackStart (l); Button execute = new Button (Stock.Execute); execute.Clicked += HandleExecuteClicked; VBox.PackStart (execute); Button stop = new Button (Stock.Stop); stop.Clicked += HandleStopClicked; VBox.PackStart (stop); this.AddButton ("_Close", ResponseType.Close); this.Response += HandleResponse; ShowAll (); } void HandleResponse (object obj, ResponseArgs args) { switch(args.ResponseId) { case ResponseType.Close: this.Destroy (); break; } } void HandleExecuteClicked (object o, EventArgs e) { SqliteDataReader reader = FSpot.Core.Database.Database.Query ("SELECT id from photos WHERE md5_sum IS NULL"); FSpot.Core.Database.Database.BeginTransaction (); while (reader.Read ()) FSpot.Jobs.CalculateHashJob.Create (FSpot.Core.Database.Jobs, Convert.ToUInt32 (reader[0])); reader.Close (); FSpot.Core.Database.Database.CommitTransaction (); } void HandleStopClicked (object o, EventArgs e) { FSpot.Core.Database.Database.ExecuteNonQuery (String.Format ("DELETE FROM jobs WHERE job_type = '{0}'", typeof(FSpot.Jobs.CalculateHashJob).ToString ())); } } }
/* * HashJob.cs * * Author(s) * Stephane Delcroix <stephane@delcroix.org> * * This is free software. See COPYING for details */ using System; using System.Collections.Generic; using Mono.Unix; using Mono.Data.SqliteClient; using Gtk; using FSpot; using FSpot.UI.Dialog; using FSpot.Extensions; using FSpot.Jobs; namespace HashJobExtension { public class HashJob : ICommand { public void Run (object o, EventArgs e) { HashJobDialog dialog = new HashJobDialog (); dialog.ShowDialog (); } } public class HashJobDialog : Dialog { public void ShowDialog () { VBox.Spacing = 6; Label l = new Label ("In order to detect duplicates on pictures you imported before f-spot 0.5.0, f-spot need to analyze your image collection. This is is not done by default as it's time consuming. You can Start or Pause this update process using this dialog.") {LineWrap = true}; VBox.PackStart (l); Button execute = new Button (Stock.Execute); execute.Clicked += HandleExecuteClicked; VBox.PackStart (execute); Button stop = new Button (Stock.Stop); stop.Clicked += HandleStopClicked; VBox.PackStart (stop); this.AddButton ("_Close", ResponseType.Close); this.Response += HandleResponse; ShowAll (); } void HandleResponse (object obj, ResponseArgs args) { switch(args.ResponseId) { case ResponseType.Close: this.Destroy (); break; } } void HandleExecuteClicked (object o, EventArgs e) { SqliteDataReader reader = FSpot.Core.Database.Database.Query ("SELECT id from photos WHERE md5_sum IS NULL"); FSpot.Core.Database.Database.BeginTransaction (); while (reader.Read ()) FSpot.Jobs.CalculateHashJob.Create (FSpot.Core.Database.Jobs, Convert.ToUInt32 (reader[0])); reader.Close (); FSpot.Core.Database.Database.CommitTransaction (); } void HandleStopClicked (object o, EventArgs e) { FSpot.Core.Database.Database.ExecuteNonQuery (String.Format ("DELETE FROM jobs WHERE job_type = '{0}'", typeof(FSpot.Jobs.CalculateHashJob).ToString ())); } } }
mit
C#
573be04cbe018d2387f124dddf491cc0bc52d511
Fix the defines
mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp,mono/SkiaSharp
binding/Binding.Shared/PlatformConfiguration.cs
binding/Binding.Shared/PlatformConfiguration.cs
using System; using System.Runtime.InteropServices; #if HARFBUZZ namespace HarfBuzzSharp #else namespace SkiaSharp #endif { internal static class PlatformConfiguration { public static bool IsUnix { get; } public static bool IsWindows { get; } public static bool IsMac { get; } public static bool IsLinux { get; } static PlatformConfiguration () { #if WINDOWS_UWP IsMac = false; IsLinux = false; IsUnix = false; IsWindows = true; #elif __NET_45__ IsUnix = Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix; IsWindows = !IsUnix; IsMac = IsUnix && MacPlatformDetector.IsMac.Value; IsLinux = IsUnix && !IsMac; #else IsMac = RuntimeInformation.IsOSPlatform (OSPlatform.OSX); IsLinux = RuntimeInformation.IsOSPlatform (OSPlatform.Linux); IsUnix = IsMac || IsLinux; IsWindows = RuntimeInformation.IsOSPlatform (OSPlatform.Windows); #endif } #if __NET_45__ #pragma warning disable IDE1006 // Naming Styles private static class MacPlatformDetector { internal static readonly Lazy<bool> IsMac = new Lazy<bool> (IsRunningOnMac); [DllImport ("libc")] static extern int uname (IntPtr buf); static bool IsRunningOnMac () { IntPtr buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal (8192); // This is a hacktastic way of getting sysname from uname () if (uname (buf) == 0) { string os = Marshal.PtrToStringAnsi (buf); if (os == "Darwin") return true; } } catch { } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal (buf); } return false; } } #pragma warning restore IDE1006 // Naming Styles #endif } }
using System; using System.Runtime.InteropServices; #if HARFBUZZ namespace HarfBuzzSharp #else namespace SkiaSharp #endif { internal static class PlatformConfiguration { public static bool IsUnix { get; } public static bool IsWindows { get; } public static bool IsMac { get; } public static bool IsLinux { get; } static PlatformConfiguration () { #if WINDOWS_UWP IsMac = false; IsLinux = false; IsUnix = false; IsWindows = true; #elif NET_STANDARD || __NET_46__ IsMac = RuntimeInformation.IsOSPlatform (OSPlatform.OSX); IsLinux = RuntimeInformation.IsOSPlatform (OSPlatform.Linux); IsUnix = IsMac || IsLinux; IsWindows = RuntimeInformation.IsOSPlatform (OSPlatform.Windows); #else IsUnix = Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix; IsWindows = !IsUnix; IsMac = IsUnix && MacPlatformDetector.IsMac.Value; IsLinux = IsUnix && !IsMac; #endif } #if __NET_45__ #pragma warning disable IDE1006 // Naming Styles private static class MacPlatformDetector { internal static readonly Lazy<bool> IsMac = new Lazy<bool> (IsRunningOnMac); [DllImport ("libc")] static extern int uname (IntPtr buf); static bool IsRunningOnMac () { IntPtr buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal (8192); // This is a hacktastic way of getting sysname from uname () if (uname (buf) == 0) { string os = Marshal.PtrToStringAnsi (buf); if (os == "Darwin") return true; } } catch { } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal (buf); } return false; } } #pragma warning restore IDE1006 // Naming Styles #endif } }
mit
C#
26cbaa76d854eba9e309ea6c07cc5dba5727d9d7
apply corrections
unosquare/swan
test/Unosquare.Swan.Test/ExtensionsExceptionMEssageTest.cs
test/Unosquare.Swan.Test/ExtensionsExceptionMEssageTest.cs
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Unosquare.Swan.Networking; using Unosquare.Swan.Test.Mocks; namespace Unosquare.Swan.Test { [TestFixture] public class ExtensionsExceptionMessageTest { [Test] public async Task ExceptionMessageTest() { try { var token = await JsonClient.GetString("https://accesscore.azurewebsites.net/api/token"); } catch(Exception ex) { var exMsg = ex.ExceptionMessage(); Assert.IsNotNull(exMsg); Assert.AreEqual(exMsg, ex.Message); } } [Test] public void InnerExceptionTest() { string[] splits = { "\r\n" }; var exceptions = new List<Exception>(); exceptions.Add(new TimeoutException("It timed out", new ArgumentException("ID missing"))); exceptions.Add(new NotImplementedException("Somethings not implemented", new ArgumentNullException())); var ex = new AggregateException(exceptions); var exMsg = ex.ExceptionMessage(); var lines = exMsg.Split(splits, StringSplitOptions.None); Assert.IsNotNull(exMsg); Assert.AreEqual(lines.Count() - 1, ex.InnerExceptions.Count()); } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Unosquare.Swan.Networking; using Unosquare.Swan.Test.Mocks; namespace Unosquare.Swan.Test { [TestFixture] public class ExtensionsExceptionMessageTest { [Test] public async Task ExceptionMessageTest() { try { var token = await JsonClient.GetString("https://accesscore.azurewebsites.net/api/token"); } catch(Exception ex) { var exMsg = ex.ExceptionMessage(); Assert.IsNotNull(exMsg); Assert.AreEqual(exMsg, ex.Message); } } [Test] public void InnerExceptionTest() { string[] splits = { "\r\n" }; List<Exception> exceptions = new List<Exception>(); exceptions.Add(new TimeoutException("It timed out", new ArgumentException("ID missing"))); exceptions.Add(new NotImplementedException("Somethings not implemented", new ArgumentNullException())); AggregateException ex = new AggregateException(exceptions); var exMsg = ex.ExceptionMessage(); string[] lines = exMsg.Split(splits, StringSplitOptions.None); Assert.IsNotNull(exMsg); Assert.AreEqual(lines.Count() - 1, ex.InnerExceptions.Count()); } } }
mit
C#
ab1f22ce80c2111dd654d8687ea489f67e015313
Add missing 'new' modifier.
JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity,JetBrains/resharper-cyclomatic-complexity
src/CyclomaticComplexity/Options/HyperlinkOptionViewModel.cs
src/CyclomaticComplexity/Options/HyperlinkOptionViewModel.cs
/* * Copyright 2007-2015 JetBrains * * 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.Collections.Generic; using System.Windows.Input; using JetBrains.DataFlow; using JetBrains.UI.Options; using JetBrains.UI.Options.OptionsDialog2.SimpleOptions; namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity.Options { public class HyperlinkOptionViewModel : OptionEntityPrimitive, IOptionCanBeEnabled, IOptionCanBeVisible { public HyperlinkOptionViewModel(Lifetime lifetime, string text, ICommand command) : base(lifetime) { Text = text; Command = command; IsEnabledProperty = new Property<bool>(lifetime, "IsEnabledProperty") { Value = true }; IsVisibleProperty = new Property<bool>(lifetime, "IsVisibleProperty") { Value = true }; } public string Text { get; } public ICommand Command { get; set; } public new IProperty<bool> IsEnabledProperty { get; } public new IProperty<bool> IsVisibleProperty { get; } public override IEnumerable<OptionsPageKeyword> GetKeywords() { yield return new OptionsPageKeyword(Text); } } }
/* * Copyright 2007-2015 JetBrains * * 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.Collections.Generic; using System.Windows.Input; using JetBrains.DataFlow; using JetBrains.UI.Options; using JetBrains.UI.Options.OptionsDialog2.SimpleOptions; namespace JetBrains.ReSharper.Plugins.CyclomaticComplexity.Options { public class HyperlinkOptionViewModel : OptionEntityPrimitive, IOptionCanBeEnabled, IOptionCanBeVisible { public HyperlinkOptionViewModel(Lifetime lifetime, string text, ICommand command) : base(lifetime) { Text = text; Command = command; IsEnabledProperty = new Property<bool>(lifetime, "IsEnabledProperty") { Value = true }; IsVisibleProperty = new Property<bool>(lifetime, "IsVisibleProperty") { Value = true }; } public string Text { get; } public ICommand Command { get; set; } public IProperty<bool> IsEnabledProperty { get; } public IProperty<bool> IsVisibleProperty { get; set; } public override IEnumerable<OptionsPageKeyword> GetKeywords() { yield return new OptionsPageKeyword(Text); } } }
apache-2.0
C#
2ebc20719a34df6ca762d040b02678de3fe38e50
Remove Parse(Uri) overload.
GetTabster/Tabster.Core
Parsing/IWebTabParser.cs
Parsing/IWebTabParser.cs
#region using System; #endregion namespace Tabster.Core.Parsing { /// <summary> /// Web-based tab parser. /// </summary> public interface IWebTabParser : IStringTabParser { ///<summary> /// Determines whether a specified URL matches a specific pattern used by the parser. Used for web-based parsing. ///</summary> ///<param name="url"> The URL to check. </param> ///<returns> True if the URL matches the supported pattern; otherwise, False. </returns> bool MatchesUrlPattern(Uri url); } }
#region using System; using Tabster.Core.Data; using Tabster.Core.Types; #endregion namespace Tabster.Core.Parsing { /// <summary> /// Web-based tab parser. /// </summary> public interface IWebTabParser : IStringTabParser { /// <summary> /// Parses tab from URL. /// </summary> /// <param name="url"> Source url to parse. </param> /// <param name="type"> Explicitly defined type. </param> /// <returns> Parsed tab. </returns> TablatureDocument Parse(Uri url, TabType? type); //todo remove nullable ///<summary> /// Determines whether a specified URL matches a specific pattern used by the parser. Used for web-based parsing. ///</summary> ///<param name="url"> The URL to check. </param> ///<returns> True if the URL matches the supported pattern; otherwise, False. </returns> bool MatchesUrlPattern(Uri url); } }
apache-2.0
C#
425bded7535a6a8096d39f93c36ae29e998e90b8
Fix for font sizing
mtskelton/unity-ucs
UCS.cs
UCS.cs
using UnityEngine; using System.Collections; /** * The Universal Coordinate System provides a simple class to convert screen independent co-ordinates from -1.0 to 1.0 into screen space, * taking into account aspect ratio. * It's a bit raw in it's current state, so improvements are welcome. */ public class UCS : MonoBehaviour { static float aspectX = 0.0f; static float aspectY = 0.0f; static float halfX = Screen.width / 2.0f; static float halfY = Screen.height / 2.0f; static float padX = 0.0f; static float padY = 0.0f; public static Rect ConvertRect(Rect rect) { rect.x = ConvertX (rect.x); rect.y = ConvertY (rect.y); rect.width = ConvertW (rect.width); rect.height = ConvertH (rect.height); return rect; } public static float ConvertX(float x) { return ConvertW (x+GetPadX()) + (halfX / GetAspectX ()); } public static float ConvertY(float y) { return ConvertH (y+GetPadY()) + (halfY / GetAspectY ()); } /** * Return additional screen space on X axis */ public static float GetPadX() { CheckAspect (); return padX; } public static float GetPadY() { CheckAspect (); return padY; } public static float ConvertW(float x) { return (x * (halfX / GetAspectX())); } public static float ConvertH(float y) { return (y * (halfY / GetAspectY())); } private static float GetAspectY() { CheckAspect (); return aspectY; } private static float GetAspectX() { CheckAspect (); return aspectX; } private static void CheckAspect() { if (aspectX != 0.0f) return; aspectX = 1.0f; aspectY = 1.0f; if(Screen.width > Screen.height) { aspectX = (Screen.width * 1.0f) / (Screen.height * 1.0f); } else { aspectY = (Screen.height * 1.0f) / (Screen.width * 1.0f); } padX = aspectX - 1.0f; padY = aspectY - 1.0f; } /** * Returns the full available width of the screen in universal co-ordinates. */ public static float GetWidth() { CheckAspect (); return (2.0f + (padX * 2)) / 2; } /** * Returns the full available width of the screen in universal co-ordinates. */ public static float GetHeight() { CheckAspect (); return (2.0f + (padY * 2)) / 2; } public static int FontSize(int size) { return (int)((size * Screen.height) / 480.0f); } }
using UnityEngine; using System.Collections; /** * The Universal Coordinate System provides a simple class to convert screen independent co-ordinates from -1.0 to 1.0 into screen space, * taking into account aspect ratio. * It's a bit raw in it's current state, so improvements are welcome. */ public class UCS : MonoBehaviour { static float aspectX = 0.0f; static float aspectY = 0.0f; static float halfX = Screen.width / 2.0f; static float halfY = Screen.height / 2.0f; static float padX = 0.0f; static float padY = 0.0f; public static Rect ConvertRect(Rect rect) { rect.x = ConvertX (rect.x); rect.y = ConvertY (rect.y); rect.width = ConvertW (rect.width); rect.height = ConvertH (rect.height); return rect; } public static float ConvertX(float x) { return ConvertW (x+GetPadX()) + (halfX / GetAspectX ()); } public static float ConvertY(float y) { return ConvertH (y+GetPadY()) + (halfY / GetAspectY ()); } /** * Return additional screen space on X axis */ public static float GetPadX() { CheckAspect (); return padX; } public static float GetPadY() { CheckAspect (); return padY; } public static float ConvertW(float x) { return (x * (halfX / GetAspectX())); } public static float ConvertH(float y) { return (y * (halfY / GetAspectY())); } private static float GetAspectY() { CheckAspect (); return aspectY; } private static float GetAspectX() { CheckAspect (); return aspectX; } private static void CheckAspect() { if (aspectX != 0.0f) return; aspectX = 1.0f; aspectY = 1.0f; if(Screen.width > Screen.height) { aspectX = (Screen.width * 1.0f) / (Screen.height * 1.0f); } else { aspectY = (Screen.height * 1.0f) / (Screen.width * 1.0f); } padX = aspectX - 1.0f; padY = aspectY - 1.0f; } /** * Returns the full available width of the screen in universal co-ordinates. */ public static float GetWidth() { CheckAspect (); return (2.0f + (padX * 2)) / 2; } /** * Returns the full available width of the screen in universal co-ordinates. */ public static float GetHeight() { CheckAspect (); return (2.0f + (padY * 2)) / 2; } public static int FontSize(int size) { return (int)((size * 480.0f) / Screen.height); } }
mit
C#
fa05ad896b996d6f5d7e05bf44d03ca651ade5b0
Change UI fullnode name
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/BitcoinCore/Monitoring/RpcStatus.cs
WalletWasabi/BitcoinCore/Monitoring/RpcStatus.cs
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.BitcoinCore.Monitoring { public class RpcStatus : IEquatable<RpcStatus> { public static RpcStatus Unresponsive = new RpcStatus(false, 0, 0, 0); private RpcStatus(bool success, ulong headers, ulong blocks, int peersCount) { Synchronized = false; if (success) { var diff = headers - blocks; if (peersCount == 0) { Status = "Bitcoin Knots is connecting..."; } else if (diff == 0) { Synchronized = true; Status = "Bitcoin Knots is synchronized"; } else { Status = $"Bitcoin Knots is downloading {diff} blocks..."; } } else { Status = "Bitcoin Knots is unresponsive"; } Success = success; Headers = headers; Blocks = blocks; PeersCount = peersCount; } public string Status { get; } public bool Success { get; } public ulong Headers { get; } public ulong Blocks { get; } public int PeersCount { get; } public bool Synchronized { get; } public static RpcStatus Responsive(ulong headers, ulong blocks, int peersCount) => new RpcStatus(true, headers, blocks, peersCount); public override string ToString() => Status; #region EqualityAndComparison public override bool Equals(object obj) => Equals(obj as RpcStatus); public bool Equals(RpcStatus other) => this == other; public override int GetHashCode() => Status.GetHashCode(); public static bool operator ==(RpcStatus x, RpcStatus y) => y?.Status == x?.Status; public static bool operator !=(RpcStatus x, RpcStatus y) => !(x == y); #endregion EqualityAndComparison } }
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.BitcoinCore.Monitoring { public class RpcStatus : IEquatable<RpcStatus> { public static RpcStatus Unresponsive = new RpcStatus(false, 0, 0, 0); private RpcStatus(bool success, ulong headers, ulong blocks, int peersCount) { Synchronized = false; if (success) { var diff = headers - blocks; if (peersCount == 0) { Status = "Bitcoin Core is connecting..."; } else if (diff == 0) { Synchronized = true; Status = "Bitcoin Core is synchronized"; } else { Status = $"Bitcoin Core is downloading {diff} blocks..."; } } else { Status = "Bitcoin Core is unresponsive"; } Success = success; Headers = headers; Blocks = blocks; PeersCount = peersCount; } public string Status { get; } public bool Success { get; } public ulong Headers { get; } public ulong Blocks { get; } public int PeersCount { get; } public bool Synchronized { get; } public static RpcStatus Responsive(ulong headers, ulong blocks, int peersCount) => new RpcStatus(true, headers, blocks, peersCount); public override string ToString() => Status; #region EqualityAndComparison public override bool Equals(object obj) => Equals(obj as RpcStatus); public bool Equals(RpcStatus other) => this == other; public override int GetHashCode() => Status.GetHashCode(); public static bool operator ==(RpcStatus x, RpcStatus y) => y?.Status == x?.Status; public static bool operator !=(RpcStatus x, RpcStatus y) => !(x == y); #endregion EqualityAndComparison } }
mit
C#
a125cc70a3bfaa7287b1285eb0d2994278c19946
Add the Material Manager to the context for injection.
Mitsugaru/game-off-2016
Assets/Scripts/RootContext.cs
Assets/Scripts/RootContext.cs
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); IMaterialManager materialManager = managers.GetComponent<MaterialManager>(); injectionBinder.Bind<IMaterialManager>().ToValue(materialManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
using UnityEngine; using System.Collections; using strange.extensions.context.impl; using strange.extensions.context.api; public class RootContext : MVCSContext, IRootContext { public RootContext(MonoBehaviour view) : base(view) { } public RootContext(MonoBehaviour view, ContextStartupFlags flags) : base(view, flags) { } protected override void mapBindings() { base.mapBindings(); GameObject managers = GameObject.Find("Managers"); injectionBinder.Bind<IRootContext>().ToValue(this).ToSingleton().CrossContext(); EventManager eventManager = managers.GetComponent<EventManager>(); injectionBinder.Bind<IEventManager>().ToValue(eventManager).ToSingleton().CrossContext(); ICameraLayerManager cameraManager = managers.GetComponent<ICameraLayerManager>(); injectionBinder.Bind<ICameraLayerManager>().ToValue(cameraManager).ToSingleton().CrossContext(); IGameLayerManager gameManager = managers.GetComponent<IGameLayerManager>(); injectionBinder.Bind<IGameLayerManager>().ToValue(gameManager).ToSingleton().CrossContext(); } public void Inject(Object o) { injectionBinder.injector.Inject(o); } }
mit
C#
6e963b6b91dba4e96f61304980fb614fae3b3db3
fix cf
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Services/UpdateChecker.cs
WalletWasabi/Services/UpdateChecker.cs
using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Bases; using WalletWasabi.Exceptions; using WalletWasabi.Helpers; using WalletWasabi.Logging; using WalletWasabi.Models; using WalletWasabi.WebClients.Wasabi; namespace WalletWasabi.Services { public class UpdateChecker : PeriodicRunner { private UpdateStatus _updateStatus; public UpdateChecker(TimeSpan period, WasabiSynchronizer synchronizer) : base(period) { Synchronizer = Guard.NotNull(nameof(synchronizer), synchronizer); WasabiClient = synchronizer.WasabiClient; UpdateStatus = new UpdateStatus(true, true, new Version()); Synchronizer.PropertyChanged += Synchronizer_PropertyChanged; } public event EventHandler<UpdateStatus> UpdateStatusChanged; public WasabiClient WasabiClient { get; } public WasabiSynchronizer Synchronizer { get; } public UpdateStatus UpdateStatus { get => _updateStatus; private set { if (value != _updateStatus) { _updateStatus = value; UpdateStatusChanged?.Invoke(this, value); } } } private void Synchronizer_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(WasabiSynchronizer.BackendStatus) && Synchronizer.BackendStatus == BackendStatus.Connected) { TriggerRound(); } } protected override async Task ActionAsync(CancellationToken cancel) { UpdateStatus = await WasabiClient.CheckUpdatesAsync(cancel).ConfigureAwait(false); } public override void Dispose() { Synchronizer.PropertyChanged -= Synchronizer_PropertyChanged; base.Dispose(); } } }
using System; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Bases; using WalletWasabi.Exceptions; using WalletWasabi.Helpers; using WalletWasabi.Logging; using WalletWasabi.Models; using WalletWasabi.WebClients.Wasabi; namespace WalletWasabi.Services { public class UpdateChecker : PeriodicRunner { private UpdateStatus _updateStatus; public UpdateChecker(TimeSpan period, WasabiSynchronizer synchronizer) : base(period) { Synchronizer = Guard.NotNull(nameof(synchronizer), synchronizer); WasabiClient = synchronizer.WasabiClient; UpdateStatus = new UpdateStatus(true, true, new Version()); Synchronizer.PropertyChanged += Synchronizer_PropertyChanged; } private void Synchronizer_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(WasabiSynchronizer.BackendStatus) && Synchronizer.BackendStatus == BackendStatus.Connected) { TriggerRound(); } } public event EventHandler<UpdateStatus> UpdateStatusChanged; public WasabiClient WasabiClient { get; } public WasabiSynchronizer Synchronizer { get; } public UpdateStatus UpdateStatus { get => _updateStatus; private set { if (value != _updateStatus) { _updateStatus = value; UpdateStatusChanged?.Invoke(this, value); } } } protected override async Task ActionAsync(CancellationToken cancel) { UpdateStatus = await WasabiClient.CheckUpdatesAsync(cancel).ConfigureAwait(false); } public override void Dispose() { Synchronizer.PropertyChanged -= Synchronizer_PropertyChanged; base.Dispose(); } } }
mit
C#
f22d025ef9ca5660721aa3f8569344a8241add02
set logging to info to see scientist results
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
WebAPI.Common/Logging/LoggingConfig.cs
WebAPI.Common/Logging/LoggingConfig.cs
using System.IO; using System.Web; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Email; using Serilog.Sinks.GoogleCloudLogging; namespace WebAPI.Common.Logging { public static class LoggingConfig { public static void Register(string name) { var config = new GoogleCloudLoggingSinkOptions { UseJsonOutput = true, LogName = "api.mapserv.utah.gov", UseSourceContextAsLogName = false, ResourceType = "global", ServiceName = "api.mapserv.utah.gov", ServiceVersion = "1.12.4" }; #if DEBUG var projectId = "ut-dts-agrc-web-api-dv"; var fileName = "ut-dts-agrc-web-api-dv-log-writer.json"; var serviceAccount = File.ReadAllText(Path.Combine(HttpRuntime.AppDomainAppPath, fileName)); config.GoogleCredentialJson = serviceAccount; #else var projectId = "ut-dts-agrc-web-api-prod"; #endif config.ProjectId = projectId; var email = new EmailConnectionInfo { EmailSubject = "Geocoding Log Email", FromEmail = "noreply@utah.gov", ToEmail = "SGourley@utah.gov" }; var levelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .WriteTo.GoogleCloudLogging(config) .CreateLogger(); #if DEBUG levelSwitch.MinimumLevel = LogEventLevel.Verbose; #else levelSwitch.MinimumLevel = LogEventLevel.Information; #endif Log.Debug("Logging initialized"); } } }
using System.IO; using System.Web; using Serilog; using Serilog.Core; using Serilog.Events; using Serilog.Sinks.Email; using Serilog.Sinks.GoogleCloudLogging; namespace WebAPI.Common.Logging { public static class LoggingConfig { public static void Register(string name) { var config = new GoogleCloudLoggingSinkOptions { UseJsonOutput = true, LogName = "api.mapserv.utah.gov", UseSourceContextAsLogName = false, ResourceType = "global", ServiceName = "api.mapserv.utah.gov", ServiceVersion = "1.12.4" }; #if DEBUG var projectId = "ut-dts-agrc-web-api-dv"; var fileName = "ut-dts-agrc-web-api-dv-log-writer.json"; var serviceAccount = File.ReadAllText(Path.Combine(HttpRuntime.AppDomainAppPath, fileName)); config.GoogleCredentialJson = serviceAccount; #else var projectId = "ut-dts-agrc-web-api-prod"; #endif config.ProjectId = projectId; var email = new EmailConnectionInfo { EmailSubject = "Geocoding Log Email", FromEmail = "noreply@utah.gov", ToEmail = "SGourley@utah.gov" }; var levelSwitch = new LoggingLevelSwitch(); Log.Logger = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.Email(email, restrictedToMinimumLevel: LogEventLevel.Error) .WriteTo.GoogleCloudLogging(config) .CreateLogger(); #if DEBUG levelSwitch.MinimumLevel = LogEventLevel.Verbose; #else levelSwitch.MinimumLevel = LogEventLevel.Warning; #endif Log.Debug("Logging initialized"); } } }
mit
C#
64d2e3ae01eda5f69e91a41d540ba9a90d28eeba
Build and publish nuget package
rlyczynski/XSerializer,QuickenLoans/XSerializer
XSerializer/Properties/AssemblyInfo.cs
XSerializer/Properties/AssemblyInfo.cs
using System; 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("XSerializer")] [assembly: AssemblyDescription("Advanced, high-performance XML and JSON serializers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("XSerializer")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.3.3")] [assembly: AssemblyInformationalVersion("0.3.3")] #if !BUILD [assembly: InternalsVisibleTo("XSerializer.Tests")] [assembly: InternalsVisibleTo("XSerializer.PerformanceTests")] #endif
using System; 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("XSerializer")] [assembly: AssemblyDescription("Advanced, high-performance XML and JSON serializers")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("XSerializer")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2013-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5aeaebd0-35de-424c-baa9-ba6d65fa3409")] [assembly: CLSCompliant(true)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.3.2")] [assembly: AssemblyInformationalVersion("0.3.2")] #if !BUILD [assembly: InternalsVisibleTo("XSerializer.Tests")] [assembly: InternalsVisibleTo("XSerializer.PerformanceTests")] #endif
mit
C#
6d92437752b78768dec5dcfa84bb47b61f256048
Set culture in NUnitSettings.cs in Atata.Tests project
atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata
src/Atata.Tests/NUnitSettings.cs
src/Atata.Tests/NUnitSettings.cs
using NUnit.Framework; [assembly: LevelOfParallelism(4)] [assembly: Parallelizable(ParallelScope.Fixtures)] [assembly: SetCulture("en-us")] [assembly: SetUICulture("en-us")]
using NUnit.Framework; [assembly: LevelOfParallelism(4)] [assembly: Parallelizable(ParallelScope.Fixtures)]
apache-2.0
C#
18a165c33d91f57b9771a1e71439cd90fc852498
Add third first rules
aloisdg/edx-csharp
edX/Module6/Program.cs
edX/Module6/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Module6 { class Program { public enum SchoolStatus { Student, Teacher, Other } // 1.Create a Person base class with common attributes for a person public abstract class APerson { public string FirstName { get; set; } public string LastName { get; set; } public DateTime Birthdate { get; set; } public abstract SchoolStatus SchoolStatus { get; } protected APerson(string firstName, string lastName, DateTime birthdate) { FirstName = firstName; LastName = lastName; Birthdate = birthdate; } } // 2.Make your Student and Teacher classes inherit from the Person base class // 3.Modify your Student and Teacher classes so that they inherit the common attributes from Person public class Student : APerson { public override SchoolStatus SchoolStatus { get { return SchoolStatus.Student; } } public Student(string firstName, string lastName, DateTime birthdate) : base(firstName, lastName, birthdate) { } public void TakeTest() { } } // 2.Make your Student and Teacher classes inherit from the Person base class // 3.Modify your Student and Teacher classes so that they inherit the common attributes from Person public class Teacher : APerson { public override SchoolStatus SchoolStatus { get { return SchoolStatus.Teacher; } } public Teacher(string firstName, string lastName, DateTime birthdate) : base(firstName, lastName, birthdate) { } public void GradeTest() { } } static void Main() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Module6 { class Program { static void Main() { } } }
mit
C#