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 |
---|---|---|---|---|---|---|---|---|
57e7d4a3cba0e83fd387fafc6c80d25359a7b42c | modify Demo | mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,wanddy/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,down4u/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK,lishewen/WeiXinMPSDK,down4u/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK | src/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/FilterTestController.cs | src/Senparc.Weixin.MP.Sample/Senparc.Weixin.MP.Sample/Controllers/FilterTestController.cs | /*----------------------------------------------------------------
Copyright (C) 2017 Senparc
文件名:FilterTestController.cs
文件功能描述:演示Senparc.Weixin.MP.MvcExtension.WeixinInternalRequestAttribute
创建标识:Senparc - 20150312
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Senparc.Weixin.MP.Sample.Controllers
{
using Senparc.Weixin.MP.MvcExtension;
/// <summary>
/// 演示Senparc.Weixin.MP.MvcExtension.WeixinInternalRequestAttribute
/// </summary>
public class FilterTestController : Controller
{
[WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!","nofilter")]
public ContentResult Index()
{
return Content("访问正常。当前地址:" + Request.Url.PathAndQuery + "<br />请点击右上角转发按钮,使用【在浏览器中打开】功能进行测试!<br />或者也可以直接在外部浏览器打开 http://sdk.weixin.senparc.com/FilterTest/ 进行测试。");
}
[WeixinInternalRequest("Message参数将被忽略", "nofilter", RedirectUrl = "/FilterTest/Index?note=has-been-redirected-url")]
public ContentResult Redirect()
{
return Content("访问正常。当前地址:" + Request.Url.PathAndQuery + "<br />请点击右上角转发按钮,使用【在浏览器中打开】功能进行测试!<br />或者也可以直接在外部浏览器打开 http://sdk.weixin.senparc.com/FilterTest/Redirect 进行测试。");
}
public ContentResult Agent()
{
return Content(Request.UserAgent);
}
}
} | /*----------------------------------------------------------------
Copyright (C) 2017 Senparc
文件名:FilterTestController.cs
文件功能描述:演示Senparc.Weixin.MP.MvcExtension.WeixinInternalRequestAttribute
创建标识:Senparc - 20150312
----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Senparc.Weixin.MP.Sample.Controllers
{
using Senparc.Weixin.MP.MvcExtension;
/// <summary>
/// 演示Senparc.Weixin.MP.MvcExtension.WeixinInternalRequestAttribute
/// </summary>
public class FilterTestController : Controller
{
[WeixinInternalRequest("访问被拒绝,请通过微信客户端访问!","nofilter")]
public ContentResult Index()
{
return Content("访问正常。当前地址:" + Request.Url.PathAndQuery + "<br />请点击右上角转发按钮,使用【在浏览器中打开】功能进行测试!<br />或者也可以直接在外部浏览器打开 http://sdk.weixin.senparc.com/FilterTest/ 进行测试。");
}
[WeixinInternalRequest("Message参数将被忽略", "nofilter", RedirectUrl = "/FilterTest/Index?note=has-been-redirected-url")]
public ContentResult Redirect()
{
return Content("访问正常。当前地址:" + Request.Url.PathAndQuery + "<br />请点击右上角转发按钮,使用【在浏览器中打开】功能进行测试!<br />或者也可以直接在外部浏览器打开 http://sdk.weixin.senparc.com/FilterTest/Redirect 进行测试。");
}
}
} | apache-2.0 | C# |
0df4723af20dbfe150cceb6cdd2b0d433a3ff8ae | test commit | iaspinDOL/CITest | NewMicroService/ConsoleApplication1/ConsoleApplication1/Program.cs | NewMicroService/ConsoleApplication1/ConsoleApplication1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world");
Console.WriteLine("Hello world again");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world");
}
}
}
| mit | C# |
306fd9bf993dffa8a941b6720eab0b14ef220e3b | Update PsychologicalPricingStrategy.cs | tiksn/TIKSN-Framework | TIKSN.Core/Finance/PricingStrategy/PsychologicalPricingStrategy.cs | TIKSN.Core/Finance/PricingStrategy/PsychologicalPricingStrategy.cs | using System;
namespace TIKSN.Finance.PricingStrategy
{
internal class PsychologicalPricingStrategy : IPricingStrategy
{
public Money EstimateMarketPrice(Money basePrice)
{
var estimatedPrice = this.EstimateMarketPrice(basePrice.Amount);
return new Money(basePrice.Currency, estimatedPrice);
}
public decimal EstimateMarketPrice(decimal basePrice)
{
var sign = basePrice >= decimal.Zero ? decimal.One : decimal.MinusOne;
var absoluteBasePrice = Math.Abs(basePrice);
var absoluteEstimatedPrice = absoluteBasePrice; //TODO: To change
return sign * absoluteEstimatedPrice;
}
}
}
| using System;
namespace TIKSN.Finance.PricingStrategy
{
internal class PsychologicalPricingStrategy : IPricingStrategy
{
public Money EstimateMarketPrice(Money basePrice)
{
var estimatedPrice = EstimateMarketPrice(basePrice.Amount);
return new Money(basePrice.Currency, estimatedPrice);
}
public decimal EstimateMarketPrice(decimal basePrice)
{
decimal sign = basePrice >= decimal.Zero ? decimal.One : decimal.MinusOne;
decimal absoluteBasePrice = Math.Abs(basePrice);
decimal absoluteEstimatedPrice = absoluteBasePrice; //TODO: To change
return sign * absoluteEstimatedPrice;
}
}
} | mit | C# |
885e3c421afb821e880d54965e3b1f6da70b4da8 | Set defaults when reading config file | crushjz/visualstudio-wakatime,wakatime/visualstudio-wakatime,gandarez/visualstudio-wakatime,CodeCavePro/wakatime-sharp,iwhp/visualstudio-wakatime,CodeCavePro/visualstudio-wakatime,lydonchandra/visualstudio-wakatime | WakaTimeConfigFile.cs | WakaTimeConfigFile.cs | using System;
using System.Text;
namespace WakaTime
{
class WakaTimeConfigFile
{
internal string ApiKey { get; set; }
internal string Proxy { get; set; }
internal bool Debug { get; set; }
private readonly string _configFilepath;
internal WakaTimeConfigFile()
{
_configFilepath = GetConfigFilePath();
Read();
}
internal void Read()
{
var ret = new StringBuilder(255);
ApiKey = NativeMethods.GetPrivateProfileString("settings", "api_key", "", ret, 255, _configFilepath) > 0
? ret.ToString()
: string.Empty;
Proxy = NativeMethods.GetPrivateProfileString("settings", "proxy", "", ret, 255, _configFilepath) > 0
? ret.ToString()
: string.Empty;
// ReSharper disable once InvertIf
if (NativeMethods.GetPrivateProfileString("settings", "debug", "", ret, 255, _configFilepath) > 0)
{
bool debug;
if (bool.TryParse(ret.ToString(), out debug))
Debug = debug;
}
}
internal void Save()
{
if (!string.IsNullOrEmpty(ApiKey))
NativeMethods.WritePrivateProfileString("settings", "api_key", ApiKey.Trim(), _configFilepath);
NativeMethods.WritePrivateProfileString("settings", "proxy", Proxy.Trim(), _configFilepath);
NativeMethods.WritePrivateProfileString("settings", "debug", Debug.ToString().ToLower(), _configFilepath);
}
static string GetConfigFilePath()
{
var userHomeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
return userHomeDir + "\\.wakatime.cfg";
}
}
} | using System;
using System.Text;
namespace WakaTime
{
class WakaTimeConfigFile
{
internal string ApiKey { get; set; }
internal string Proxy { get; set; }
internal bool Debug { get; set; }
private readonly string _configFilepath;
internal WakaTimeConfigFile()
{
_configFilepath = GetConfigFilePath();
Read();
}
internal void Read()
{
var ret = new StringBuilder(255);
if (NativeMethods.GetPrivateProfileString("settings", "api_key", "", ret, 255, _configFilepath) > 0)
ApiKey = ret.ToString();
if (NativeMethods.GetPrivateProfileString("settings", "proxy", "", ret, 255, _configFilepath) > 0)
Proxy = ret.ToString();
// ReSharper disable once InvertIf
if (NativeMethods.GetPrivateProfileString("settings", "debug", "", ret, 255, _configFilepath) > 0)
{
bool debug;
if (bool.TryParse(ret.ToString(), out debug))
Debug = debug;
}
}
internal void Save()
{
if (!string.IsNullOrEmpty(ApiKey))
NativeMethods.WritePrivateProfileString("settings", "api_key", ApiKey.Trim(), _configFilepath);
NativeMethods.WritePrivateProfileString("settings", "proxy", Proxy.Trim(), _configFilepath);
NativeMethods.WritePrivateProfileString("settings", "debug", Debug.ToString().ToLower(), _configFilepath);
}
static string GetConfigFilePath()
{
var userHomeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
return userHomeDir + "\\.wakatime.cfg";
}
}
} | bsd-3-clause | C# |
e6ec883084899f368847d3367f7000f409844b68 | Remove slider tail circle judgement requirements | peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu-new | osu.Game.Rulesets.Osu/Objects/SliderTailCircle.cs | osu.Game.Rulesets.Osu/Objects/SliderTailCircle.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Osu.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
/// <summary>
/// Note that this should not be used for timing correctness.
/// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information.
/// </summary>
public class SliderTailCircle : SliderCircle
{
private readonly IBindable<int> pathVersion = new Bindable<int>();
public SliderTailCircle(Slider slider)
{
pathVersion.BindTo(slider.Path.Version);
pathVersion.BindValueChanged(_ => Position = slider.EndPosition);
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
public override Judgement CreateJudgement() => new SliderTailJudgement();
public class SliderTailJudgement : OsuJudgement
{
protected override int NumericResultFor(HitResult result) => 0;
public override bool AffectsCombo => false;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Osu.Objects
{
/// <summary>
/// Note that this should not be used for timing correctness.
/// See <see cref="SliderEventType.LegacyLastTick"/> usage in <see cref="Slider"/> for more information.
/// </summary>
public class SliderTailCircle : SliderCircle
{
private readonly IBindable<int> pathVersion = new Bindable<int>();
public SliderTailCircle(Slider slider)
{
pathVersion.BindTo(slider.Path.Version);
pathVersion.BindValueChanged(_ => Position = slider.EndPosition);
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
public override Judgement CreateJudgement() => new SliderRepeat.SliderRepeatJudgement();
}
}
| mit | C# |
5bb8649f3b3502707db16c9a5963d74b7f98039a | Remove unused property from chat message | ZLima12/osu,ppy/osu,2yangk23/osu,UselessToucan/osu,EVAST9919/osu,2yangk23/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu-new,johnneijzen/osu,NeoAdonis/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,EVAST9919/osu,ppy/osu,ppy/osu | osu.Game/Online/Chat/Message.cs | osu.Game/Online/Chat/Message.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Users;
namespace osu.Game.Online.Chat
{
public class Message : IComparable<Message>, IEquatable<Message>
{
[JsonProperty(@"message_id")]
public readonly long? Id;
[JsonProperty(@"channel_id")]
public long ChannelId;
[JsonProperty(@"is_action")]
public bool IsAction;
[JsonProperty(@"timestamp")]
public DateTimeOffset Timestamp;
[JsonProperty(@"content")]
public string Content;
[JsonProperty(@"sender")]
public User Sender;
[JsonConstructor]
public Message()
{
}
/// <summary>
/// The text that is displayed in chat.
/// </summary>
public string DisplayContent { get; set; }
/// <summary>
/// The links found in this message.
/// </summary>
/// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks>
public List<Link> Links;
public Message(long? id)
{
Id = id;
}
public int CompareTo(Message other)
{
if (!Id.HasValue)
return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp);
if (!other.Id.HasValue)
return -1;
return Id.Value.CompareTo(other.Id.Value);
}
public virtual bool Equals(Message other) => Id == other?.Id;
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public override int GetHashCode() => Id.GetHashCode();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using osu.Game.Users;
namespace osu.Game.Online.Chat
{
public class Message : IComparable<Message>, IEquatable<Message>
{
[JsonProperty(@"message_id")]
public readonly long? Id;
//todo: this should be inside sender.
[JsonProperty(@"sender_id")]
public long UserId;
[JsonProperty(@"channel_id")]
public long ChannelId;
[JsonProperty(@"is_action")]
public bool IsAction;
[JsonProperty(@"timestamp")]
public DateTimeOffset Timestamp;
[JsonProperty(@"content")]
public string Content;
[JsonProperty(@"sender")]
public User Sender;
[JsonConstructor]
public Message()
{
}
/// <summary>
/// The text that is displayed in chat.
/// </summary>
public string DisplayContent { get; set; }
/// <summary>
/// The links found in this message.
/// </summary>
/// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks>
public List<Link> Links;
public Message(long? id)
{
Id = id;
}
public int CompareTo(Message other)
{
if (!Id.HasValue)
return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp);
if (!other.Id.HasValue)
return -1;
return Id.Value.CompareTo(other.Id.Value);
}
public virtual bool Equals(Message other) => Id == other?.Id;
// ReSharper disable once ImpureMethodCallOnReadonlyValueField
public override int GetHashCode() => Id.GetHashCode();
}
}
| mit | C# |
b6841dda6c14412d4f017fcbbc0ef7a812de2fb3 | Fix tests | steven-r/Oberon0Compiler | UnitTestProject1/SimpleTests.cs | UnitTestProject1/SimpleTests.cs | using System.Collections.Generic;
using NUnit.Framework;
using Oberon0.Compiler.Definitions;
using Oberon0.CompilerSupport;
namespace Oberon0.Compiler.Tests
{
[TestFixture]
public class SimpleTests
{
[Test]
public void EmptyApplication()
{
Module m = Oberon0Compiler.CompileString("MODULE Test; END Test.");
Assert.AreEqual("Test", m.Name);
Assert.AreEqual(2, m.Block.Declarations.Count);
}
[Test]
public void EmptyApplication2()
{
Module m = TestHelper.CompileString(@"MODULE Test;
BEGIN END Test.");
Assert.AreEqual(0, m.Block.Statements.Count);
}
[Test]
public void ModuleMissingDot()
{
List<CompilerError> errors = new List<CompilerError>();
Module m = TestHelper.CompileString(@"MODULE Test;
END Test", errors);
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("missing '.' at '<EOF>'", errors[0].Message);
}
[Test]
public void ModuleMissingId()
{
List<CompilerError> errors = new List<CompilerError>();
Module m = TestHelper.CompileString(@"MODULE ;
BEGIN END Test.", errors);
Assert.AreEqual(2, errors.Count);
Assert.AreEqual("missing ID at ';'", errors[0].Message);
Assert.AreEqual("The name of the module does not match the end node", errors[1].Message);
}
}
}
| using System.Collections.Generic;
using NUnit.Framework;
using Oberon0.Compiler.Definitions;
using Oberon0.CompilerSupport;
namespace Oberon0.Compiler.Tests
{
[TestFixture]
public class SimpleTests
{
[Test]
public void EmptyApplication()
{
Module m = Oberon0Compiler.CompileString("MODULE Test; END Test.");
Assert.AreEqual("Test", m.Name);
Assert.AreEqual(2, m.Block.Declarations.Count);
}
[Test]
public void EmptyApplication2()
{
List<CompilerError> errors = new List<CompilerError>();
Module m = TestHelper.CompileString(@"MODULE Test;
BEGIN END Test.", errors);
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("Statement expected", errors[0].Message);
}
[Test]
public void ModuleMissingDot()
{
List<CompilerError> errors = new List<CompilerError>();
Module m = TestHelper.CompileString(@"MODULE Test;
END Test", errors);
Assert.AreEqual(1, errors.Count);
Assert.AreEqual("missing '.' at '<EOF>'", errors[0].Message);
}
[Test]
public void ModuleMissingId()
{
List<CompilerError> errors = new List<CompilerError>();
Module m = TestHelper.CompileString(@"MODULE ;
BEGIN END Test.", errors);
Assert.AreEqual(3, errors.Count);
Assert.AreEqual("missing ID at ';'", errors[0].Message);
Assert.AreEqual("Statement expected", errors[1].Message);
Assert.AreEqual("The name of the module does not match the end node", errors[2].Message);
}
}
}
| mit | C# |
2b598489bd3170d8338a0744d8b84065a01f0688 | Tweak comment. | heejaechang/roslyn,tannergooding/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,reaction1989/roslyn,genlu/roslyn,eriawan/roslyn,gafter/roslyn,lorcanmooney/roslyn,pdelvo/roslyn,jasonmalinowski/roslyn,gafter/roslyn,KirillOsenkov/roslyn,pdelvo/roslyn,xasx/roslyn,kelltrick/roslyn,MattWindsor91/roslyn,bbarry/roslyn,KirillOsenkov/roslyn,vslsnap/roslyn,khyperia/roslyn,akrisiun/roslyn,sharwell/roslyn,davkean/roslyn,jeffanders/roslyn,dotnet/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,jamesqo/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,mavasani/roslyn,diryboy/roslyn,srivatsn/roslyn,CaptainHayashi/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,orthoxerox/roslyn,mavasani/roslyn,Hosch250/roslyn,kelltrick/roslyn,mattscheffer/roslyn,jkotas/roslyn,AmadeusW/roslyn,davkean/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,CaptainHayashi/roslyn,tmat/roslyn,drognanar/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,cston/roslyn,vslsnap/roslyn,nguerrera/roslyn,VSadov/roslyn,stephentoub/roslyn,jcouv/roslyn,a-ctor/roslyn,robinsedlaczek/roslyn,amcasey/roslyn,bbarry/roslyn,cston/roslyn,OmarTawfik/roslyn,davkean/roslyn,agocke/roslyn,MattWindsor91/roslyn,yeaicc/roslyn,Giftednewt/roslyn,abock/roslyn,zooba/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,orthoxerox/roslyn,OmarTawfik/roslyn,wvdd007/roslyn,sharwell/roslyn,yeaicc/roslyn,mmitche/roslyn,robinsedlaczek/roslyn,DustinCampbell/roslyn,KevinH-MS/roslyn,bkoelman/roslyn,TyOverby/roslyn,TyOverby/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,physhi/roslyn,robinsedlaczek/roslyn,CaptainHayashi/roslyn,MattWindsor91/roslyn,genlu/roslyn,nguerrera/roslyn,tannergooding/roslyn,reaction1989/roslyn,pdelvo/roslyn,jcouv/roslyn,mattwar/roslyn,lorcanmooney/roslyn,jamesqo/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,jeffanders/roslyn,gafter/roslyn,orthoxerox/roslyn,mattscheffer/roslyn,amcasey/roslyn,aelij/roslyn,mattscheffer/roslyn,paulvanbrenk/roslyn,agocke/roslyn,TyOverby/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,dpoeschl/roslyn,KevinH-MS/roslyn,stephentoub/roslyn,xoofx/roslyn,heejaechang/roslyn,AArnott/roslyn,xoofx/roslyn,jmarolf/roslyn,dpoeschl/roslyn,AnthonyDGreen/roslyn,panopticoncentral/roslyn,mgoertz-msft/roslyn,bkoelman/roslyn,vslsnap/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,mattwar/roslyn,lorcanmooney/roslyn,tvand7093/roslyn,AArnott/roslyn,AArnott/roslyn,zooba/roslyn,stephentoub/roslyn,tvand7093/roslyn,brettfo/roslyn,zooba/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,khyperia/roslyn,heejaechang/roslyn,MattWindsor91/roslyn,brettfo/roslyn,weltkante/roslyn,dotnet/roslyn,DustinCampbell/roslyn,genlu/roslyn,a-ctor/roslyn,paulvanbrenk/roslyn,tvand7093/roslyn,drognanar/roslyn,xasx/roslyn,jasonmalinowski/roslyn,OmarTawfik/roslyn,tmeschter/roslyn,jeffanders/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,a-ctor/roslyn,DustinCampbell/roslyn,akrisiun/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,jamesqo/roslyn,mgoertz-msft/roslyn,mmitche/roslyn,srivatsn/roslyn,tmat/roslyn,jkotas/roslyn,akrisiun/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,dpoeschl/roslyn,yeaicc/roslyn,jkotas/roslyn,diryboy/roslyn,tmeschter/roslyn,Hosch250/roslyn,AlekseyTs/roslyn,KevinH-MS/roslyn,AnthonyDGreen/roslyn,abock/roslyn,physhi/roslyn,bkoelman/roslyn,physhi/roslyn,Giftednewt/roslyn,AmadeusW/roslyn,khyperia/roslyn,kelltrick/roslyn,mattwar/roslyn,xoofx/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,drognanar/roslyn,mmitche/roslyn,jmarolf/roslyn,MichalStrehovsky/roslyn,paulvanbrenk/roslyn,ErikSchierboom/roslyn,cston/roslyn,tmat/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,aelij/roslyn,brettfo/roslyn,srivatsn/roslyn,Hosch250/roslyn,bbarry/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,amcasey/roslyn,abock/roslyn,jcouv/roslyn,aelij/roslyn,Giftednewt/roslyn,AnthonyDGreen/roslyn,xasx/roslyn,VSadov/roslyn,nguerrera/roslyn,eriawan/roslyn,KevinRansom/roslyn,tmeschter/roslyn,MichalStrehovsky/roslyn | src/Workspaces/Core/Desktop/SymbolSearch/ISymbolSearchUpdateEngine.cs | src/Workspaces/Core/Desktop/SymbolSearch/ISymbolSearchUpdateEngine.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
/// <summary>
/// Service that allows you to query the SymbolSearch database and which keeps
/// the database up to date.
/// </summary>
internal interface ISymbolSearchUpdateEngine : IDisposable
{
Task UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory);
Task StopUpdatesAsync();
Task<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(
string source, string name, int arity);
Task<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(
string name, int arity);
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.SymbolSearch
{
/// <summary>
/// Service that keeps the SymbolSearch database up to date.
/// </summary>
internal interface ISymbolSearchUpdateEngine : IDisposable
{
Task UpdateContinuouslyAsync(string sourceName, string localSettingsDirectory);
Task StopUpdatesAsync();
Task<ImmutableArray<PackageWithTypeResult>> FindPackagesWithTypeAsync(
string source, string name, int arity);
Task<ImmutableArray<ReferenceAssemblyWithTypeResult>> FindReferenceAssembliesWithTypeAsync(
string name, int arity);
}
} | mit | C# |
cebc1f2e3c4cda64e2734e7f9086892be6f69138 | Increment version to 1.8 | phdesign/NppToolBucket | phdesign.NppToolBucket/Properties/AssemblyInfo.cs | phdesign.NppToolBucket/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("NppToolBucket")]
[assembly: AssemblyDescription("Plugin of assorted tools for Notepad++")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("phdesign")]
[assembly: AssemblyProduct("phdesign.NppToolBucket")]
[assembly: AssemblyCopyright("Copyright © phdesign 2011 - 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("31492674-6fe0-485c-91f0-2e17244588ff")]
// 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.8.*")]
//[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("NppToolBucket")]
[assembly: AssemblyDescription("Plugin of assorted tools for Notepad++")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("phdesign")]
[assembly: AssemblyProduct("phdesign.NppToolBucket")]
[assembly: AssemblyCopyright("Copyright © phdesign 2011 - 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("31492674-6fe0-485c-91f0-2e17244588ff")]
// 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.7.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
f6d4108eb0e68db4fa3281335c44ab88e5dca71d | Fix audio thread not exiting correctly | ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework | osu.Framework/Threading/AudioThread.cs | osu.Framework/Threading/AudioThread.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
namespace osu.Framework.Threading
{
public class AudioThread : GameThread
{
public AudioThread()
: base(name: "Audio")
{
OnNewFrame = onNewFrame;
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.TasksRun,
StatisticsCounterType.Tracks,
StatisticsCounterType.Samples,
StatisticsCounterType.SChannels,
StatisticsCounterType.Components,
};
private readonly List<AudioManager> managers = new List<AudioManager>();
private void onNewFrame()
{
lock (managers)
{
for (var i = 0; i < managers.Count; i++)
{
var m = managers[i];
m.Update();
}
}
}
public void RegisterManager(AudioManager manager)
{
lock (managers)
{
if (managers.Contains(manager))
throw new InvalidOperationException($"{manager} was already registered");
managers.Add(manager);
}
}
public void UnregisterManager(AudioManager manager)
{
lock (managers)
managers.Remove(manager);
}
protected override void PerformExit()
{
base.PerformExit();
lock (managers)
{
foreach (var manager in managers)
manager.Dispose();
managers.Clear();
}
ManagedBass.Bass.Free();
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Statistics;
using System;
using System.Collections.Generic;
using osu.Framework.Audio;
namespace osu.Framework.Threading
{
public class AudioThread : GameThread
{
public AudioThread()
: base(name: "Audio")
{
OnNewFrame = onNewFrame;
}
internal override IEnumerable<StatisticsCounterType> StatisticsCounters => new[]
{
StatisticsCounterType.TasksRun,
StatisticsCounterType.Tracks,
StatisticsCounterType.Samples,
StatisticsCounterType.SChannels,
StatisticsCounterType.Components,
};
private readonly List<AudioManager> managers = new List<AudioManager>();
private void onNewFrame()
{
lock (managers)
{
for (var i = 0; i < managers.Count; i++)
{
var m = managers[i];
m.Update();
}
}
}
public void RegisterManager(AudioManager manager)
{
lock (managers)
{
if (managers.Contains(manager))
throw new InvalidOperationException($"{manager} was already registered");
managers.Add(manager);
}
}
public void UnregisterManager(AudioManager manager)
{
lock (managers)
managers.Remove(manager);
}
protected override void PerformExit()
{
base.PerformExit();
lock (managers)
{
// AudioManager's disposal triggers an un-registration
while (managers.Count > 0)
managers[0].Dispose();
}
ManagedBass.Bass.Free();
}
}
}
| mit | C# |
d4b0d8b51deb426fc1f642a838cddb0a00b59b8e | Rearrange private class members. | mthamil/TFSTestCaseAutomator | TestCaseAutomator/ViewModels/Browser/Nodes/SourceDirectoryViewModel.cs | TestCaseAutomator/ViewModels/Browser/Nodes/SourceDirectoryViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SharpEssentials.Collections;
using TestCaseAutomator.TeamFoundation;
namespace TestCaseAutomator.ViewModels.Browser.Nodes
{
public class SourceDirectoryViewModel : VirtualizedNode<IVirtualizedNode>
{
/// <summary>
/// Initializes a new instance of the <see cref="SourceDirectoryViewModel"/> class.
/// </summary>
/// <param name="directory">A source control directory</param>
/// <param name="fileFactory">Creates file view-models</param>
/// <param name="directoryFactory">Creates directory view models</param>
public SourceDirectoryViewModel(TfsDirectory directory,
Func<TfsFile, AutomationSourceViewModel> fileFactory,
Func<TfsDirectory, SourceDirectoryViewModel> directoryFactory)
{
_directory = directory;
_fileFactory = fileFactory;
_directoryFactory = directoryFactory;
}
public override string Name => _directory.Name;
protected override IVirtualizedNode DummyNode => Dummy.Instance;
protected async override Task<IReadOnlyCollection<IVirtualizedNode>> LoadChildrenAsync(IProgress<IVirtualizedNode> progress)
{
return (await _directory.GetItemsAsync())
.Select(item => item is TfsDirectory
? _directoryFactory((TfsDirectory)item)
: _fileFactory(item as TfsFile))
.Tee(progress.Report)
.ToList();
}
private readonly TfsDirectory _directory;
private readonly Func<TfsFile, IVirtualizedNode> _fileFactory;
private readonly Func<TfsDirectory, IVirtualizedNode> _directoryFactory;
private class Dummy : SourceDirectoryViewModel
{
private Dummy() : base(null, null, null) { }
public override string Name => "Loading...";
public static readonly Dummy Instance = new Dummy();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SharpEssentials.Collections;
using TestCaseAutomator.TeamFoundation;
namespace TestCaseAutomator.ViewModels.Browser.Nodes
{
public class SourceDirectoryViewModel : VirtualizedNode<IVirtualizedNode>
{
/// <summary>
/// Initializes a new instance of the <see cref="SourceDirectoryViewModel"/> class.
/// </summary>
/// <param name="directory">A source control directory</param>
/// <param name="fileFactory">Creates file view-models</param>
/// <param name="directoryFactory">Creates directory view models</param>
public SourceDirectoryViewModel(TfsDirectory directory,
Func<TfsFile, AutomationSourceViewModel> fileFactory,
Func<TfsDirectory, SourceDirectoryViewModel> directoryFactory)
{
_directory = directory;
_fileFactory = fileFactory;
_directoryFactory = directoryFactory;
}
public override string Name => _directory.Name;
protected override IVirtualizedNode DummyNode => Dummy.Instance;
protected async override Task<IReadOnlyCollection<IVirtualizedNode>> LoadChildrenAsync(IProgress<IVirtualizedNode> progress)
{
return (await _directory.GetItemsAsync())
.Select(item => item is TfsDirectory
? _directoryFactory((TfsDirectory)item)
: _fileFactory(item as TfsFile))
.Tee(progress.Report)
.ToList();
}
private class Dummy : SourceDirectoryViewModel
{
private Dummy() : base(null, null, null) { }
public override string Name => "Loading...";
public static readonly Dummy Instance = new Dummy();
}
private readonly TfsDirectory _directory;
private readonly Func<TfsFile, IVirtualizedNode> _fileFactory;
private readonly Func<TfsDirectory, IVirtualizedNode> _directoryFactory;
}
} | apache-2.0 | C# |
51a7b3807a35f1dd2b3aad76fb687958af7d3e42 | Update default NuGet package url. | mrward/monodevelop-nuget-addin | src/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RegisteredPackageSources.cs | src/MonoDevelop.PackageManagement/MonoDevelop.PackageManagement/RegisteredPackageSources.cs | //
// RegisteredPackgaeSources.cs
//
// Author:
// Matt Ward <[email protected]>
//
// Copyright (C) 2012 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using NuGet;
namespace ICSharpCode.PackageManagement
{
public class RegisteredPackageSources : ObservableCollection<PackageSource>
{
public static readonly string DefaultPackageSourceUrl = "https://www.nuget.org/api/v2/";
public static readonly string DefaultPackageSourceName = "nuget.org";
public static readonly PackageSource DefaultPackageSource =
new PackageSource(DefaultPackageSourceUrl, DefaultPackageSourceName);
public RegisteredPackageSources(IEnumerable<PackageSource> packageSources)
: this(packageSources, DefaultPackageSource)
{
}
public RegisteredPackageSources(
IEnumerable<PackageSource> packageSources,
PackageSource defaultPackageSource)
{
AddPackageSources(packageSources);
AddDefaultPackageSourceIfNoRegisteredPackageSources(defaultPackageSource);
}
void AddPackageSources(IEnumerable<PackageSource> packageSources)
{
foreach (PackageSource source in packageSources) {
Add(source);
}
}
void AddDefaultPackageSourceIfNoRegisteredPackageSources(PackageSource defaultPackageSource)
{
if (HasNoRegisteredPackageSources) {
Add(defaultPackageSource);
}
}
bool HasNoRegisteredPackageSources {
get { return Count == 0; }
}
public bool HasMultipleEnabledPackageSources {
get { return GetEnabledPackageSources().Count() > 1; }
}
public IEnumerable<PackageSource> GetEnabledPackageSources()
{
return this.Where(packageSource => packageSource.IsEnabled);
}
}
}
| //
// RegisteredPackgaeSources.cs
//
// Author:
// Matt Ward <[email protected]>
//
// Copyright (C) 2012 Matthew Ward
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using NuGet;
namespace ICSharpCode.PackageManagement
{
public class RegisteredPackageSources : ObservableCollection<PackageSource>
{
public static readonly string DefaultPackageSourceUrl = "https://nuget.org/api/v2/";
public static readonly string DefaultPackageSourceName = "NuGet Official Package Source";
public static readonly PackageSource DefaultPackageSource =
new PackageSource(DefaultPackageSourceUrl, DefaultPackageSourceName);
public RegisteredPackageSources(IEnumerable<PackageSource> packageSources)
: this(packageSources, DefaultPackageSource)
{
}
public RegisteredPackageSources(
IEnumerable<PackageSource> packageSources,
PackageSource defaultPackageSource)
{
AddPackageSources(packageSources);
AddDefaultPackageSourceIfNoRegisteredPackageSources(defaultPackageSource);
}
void AddPackageSources(IEnumerable<PackageSource> packageSources)
{
foreach (PackageSource source in packageSources) {
Add(source);
}
}
void AddDefaultPackageSourceIfNoRegisteredPackageSources(PackageSource defaultPackageSource)
{
if (HasNoRegisteredPackageSources) {
Add(defaultPackageSource);
}
}
bool HasNoRegisteredPackageSources {
get { return Count == 0; }
}
public bool HasMultipleEnabledPackageSources {
get { return GetEnabledPackageSources().Count() > 1; }
}
public IEnumerable<PackageSource> GetEnabledPackageSources()
{
return this.Where(packageSource => packageSource.IsEnabled);
}
}
}
| mit | C# |
a16c3904882481dc98b672c7522cd0042067c9d5 | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.47")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.46")] | mit | C# |
4cff0e95989831d21d5f13ef02fc1de7a6ae0bef | Implement diagnostic SA1125 UseShorthandForNullableTypes (fixes #58) | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1125UseShorthandForNullableTypes.cs | StyleCop.Analyzers/StyleCop.Analyzers/ReadabilityRules/SA1125UseShorthandForNullableTypes.cs | namespace StyleCop.Analyzers.ReadabilityRules
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
/// <summary>
/// The <see cref="Nullable{T}"/> type has been defined not using the C# shorthand. For example,
/// <c>Nullable<DateTime></c> has been used instead of the preferred <c>DateTime?</c>.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs whenever the <see cref="Nullable{T}"/> type has been defined without using
/// the shorthand C# style.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SA1125UseShorthandForNullableTypes : DiagnosticAnalyzer
{
public const string DiagnosticId = "SA1125";
internal const string Title = "Use shorthand for nullable types";
internal const string MessageFormat = "Use shorthand for nullable types";
internal const string Category = "StyleCop.CSharp.ReadabilityRules";
internal const string Description = "The Nullable<T> type has been defined not using the C# shorthand. For example, Nullable<DateTime> has been used instead of the preferred DateTime?";
internal const string HelpLink = "http://www.stylecop.com/docs/SA1125.html";
public static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink);
private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return _supportedDiagnostics;
}
}
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(HandleGenericNameSyntax, SyntaxKind.GenericName);
}
private void HandleGenericNameSyntax(SyntaxNodeAnalysisContext context)
{
GenericNameSyntax genericNameSyntax = context.Node as GenericNameSyntax;
if (genericNameSyntax == null)
return;
if (genericNameSyntax.Identifier.IsMissing || genericNameSyntax.Identifier.Text != "Nullable")
return;
if (genericNameSyntax.FirstAncestorOrSelf<UsingDirectiveSyntax>() != null)
return;
SemanticModel semanticModel = context.SemanticModel;
INamedTypeSymbol symbol = semanticModel.GetSymbolInfo(genericNameSyntax, context.CancellationToken).Symbol as INamedTypeSymbol;
if (symbol?.OriginalDefinition?.SpecialType != SpecialType.System_Nullable_T)
return;
SyntaxNode locationNode = genericNameSyntax;
if (genericNameSyntax.Parent is QualifiedNameSyntax)
locationNode = genericNameSyntax.Parent;
// Use shorthand for nullable types
context.ReportDiagnostic(Diagnostic.Create(Descriptor, locationNode.GetLocation()));
}
}
}
| namespace StyleCop.Analyzers.ReadabilityRules
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
/// <summary>
/// The <see cref="Nullable{T}"/> type has been defined not using the C# shorthand. For example,
/// <c>Nullable<DateTime></c> has been used instead of the preferred <c>DateTime?</c>.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs whenever the <see cref="Nullable{T}"/> type has been defined without using
/// the shorthand C# style.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SA1125UseShorthandForNullableTypes : DiagnosticAnalyzer
{
public const string DiagnosticId = "SA1125";
internal const string Title = "Use shorthand for nullable types";
internal const string MessageFormat = "TODO: Message format";
internal const string Category = "StyleCop.CSharp.ReadabilityRules";
internal const string Description = "The Nullable<T> type has been defined not using the C# shorthand. For example, Nullable<DateTime> has been used instead of the preferred DateTime?";
internal const string HelpLink = "http://www.stylecop.com/docs/SA1125.html";
public static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink);
private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return _supportedDiagnostics;
}
}
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
// TODO: Implement analysis
}
}
}
| mit | C# |
68251d0ea2e4d81c76d22c948e76680079db12b8 | Fix bizarre behavior of SubTreeUnpacker.ReadSubTree before head | modulexcite/msgpack-cli,scopely/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli,scopely/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,msgpack/msgpack-cli | cli/src/MsgPack/SubtreeUnpacker.cs | cli/src/MsgPack/SubtreeUnpacker.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Diagnostics.Contracts;
using System.IO;
namespace MsgPack
{
// TODO: Expose base subtree unpacker as API
/// <summary>
/// Defines subtree unpacking unpacker.
/// </summary>
internal sealed class SubtreeUnpacker : Unpacker
{
private readonly StreamUnpacker _root;
private readonly SubtreeUnpacker _parent;
private readonly bool _isMap;
private long _unpacked;
private readonly long _itemsCount;
public sealed override long ItemsCount
{
get { return this._itemsCount; }
}
public sealed override bool IsArrayHeader
{
get { return this._root.IsArrayHeader; }
}
public sealed override bool IsMapHeader
{
get { return this._root.IsMapHeader; }
}
public sealed override bool IsInStart
{
get { return false; }
}
public sealed override MessagePackObject? Data
{
get { return this._root.Data; }
}
public SubtreeUnpacker( StreamUnpacker parent ) : this( parent, null ) { }
private SubtreeUnpacker( StreamUnpacker root, SubtreeUnpacker parent )
{
Contract.Assert( root != null );
Contract.Assert( root.IsArrayHeader || root.IsMapHeader );
this._root = root;
this._parent = parent;
this._itemsCount = root.ItemsCount;
this._isMap = root.IsMapHeader;
}
protected sealed override void Dispose( bool disposing )
{
if ( disposing )
{
// Drain...
while ( this.ReadCore() )
{
// nop
}
if ( this._parent != null )
{
this._parent.EndReadSubtree();
}
else
{
this._root.EndReadSubtree();
}
}
}
protected sealed override Unpacker ReadSubtreeCore()
{
if ( this._unpacked == 0 )
{
throw new InvalidOperationException( "This unpacker is located before of the head." );
}
return new SubtreeUnpacker( this._root, this );
}
protected sealed override bool ReadCore()
{
if ( this._unpacked == this._itemsCount * ( this._isMap ? 2 : 1 ) )
{
return false;
}
if ( !this._root.ReadSubtreeItem() )
{
return false;
}
this._unpacked++;
return true;
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Diagnostics.Contracts;
using System.IO;
namespace MsgPack
{
// TODO: Expose base subtree unpacker as API
/// <summary>
/// Defines subtree unpacking unpacker.
/// </summary>
internal sealed class SubtreeUnpacker : Unpacker
{
private readonly StreamUnpacker _root;
private readonly SubtreeUnpacker _parent;
private readonly bool _isMap;
private long _unpacked;
private readonly long _itemsCount;
public sealed override long ItemsCount
{
get { return this._itemsCount; }
}
public sealed override bool IsArrayHeader
{
get { return this._root.IsArrayHeader; }
}
public sealed override bool IsMapHeader
{
get { return this._root.IsMapHeader; }
}
public sealed override bool IsInStart
{
get { return false; }
}
public sealed override MessagePackObject? Data
{
get { return this._root.Data; }
}
public SubtreeUnpacker( StreamUnpacker parent ) : this( parent, null ) { }
private SubtreeUnpacker( StreamUnpacker root, SubtreeUnpacker parent )
{
Contract.Assert( root != null );
Contract.Assert( root.IsArrayHeader || root.IsMapHeader );
this._root = root;
this._parent = parent;
this._itemsCount = root.ItemsCount;
this._isMap = root.IsMapHeader;
}
protected sealed override void Dispose( bool disposing )
{
if ( disposing )
{
// Drain...
while ( this.ReadCore() )
{
// nop
}
if ( this._parent != null )
{
this._parent.EndReadSubtree();
}
else
{
this._root.EndReadSubtree();
}
}
}
protected sealed override Unpacker ReadSubtreeCore()
{
if ( this._unpacked == 0 )
{
return this;
}
return new SubtreeUnpacker( this._root, this );
}
protected sealed override bool ReadCore()
{
if ( this._unpacked == this._itemsCount * ( this._isMap ? 2 : 1 ) )
{
return false;
}
if ( !this._root.ReadSubtreeItem() )
{
return false;
}
this._unpacked++;
return true;
}
}
}
| apache-2.0 | C# |
60c2d113b80eed1630d0ccdc951a3b1fa954b9e3 | Fix typo | smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,peppy/osu,johnneijzen/osu,ZLima12/osu,NeoAdonis/osu,2yangk23/osu,ppy/osu,ZLima12/osu,2yangk23/osu,UselessToucan/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu | osu.Game/Rulesets/UI/FallbackSampleStore.cs | osu.Game/Rulesets/UI/FallbackSampleStore.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
namespace osu.Game.Rulesets.UI
{
public class FallbackSampleStore : ISampleStore
{
private readonly ISampleStore primary;
private readonly ISampleStore secondary;
public FallbackSampleStore(ISampleStore primary, ISampleStore secondary)
{
this.primary = primary;
this.secondary = secondary;
}
public void Dispose()
{
primary.Dispose();
secondary.Dispose();
}
public SampleChannel Get(string name) => primary.Get(name) ?? secondary.Get(name);
public Task<SampleChannel> GetAsync(string name) => primary.GetAsync(name) ?? secondary.GetAsync(name);
public Stream GetStream(string name) => primary.GetStream(name) ?? secondary.GetStream(name);
public IEnumerable<string> GetAvailableResources() => primary.GetAvailableResources().Concat(secondary.GetAvailableResources());
public void AddAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.AddAdjustment(type, adjustBindable);
secondary.AddAdjustment(type, adjustBindable);
}
public void RemoveAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.RemoveAdjustment(type, adjustBindable);
secondary.RemoveAdjustment(type, adjustBindable);
}
public BindableDouble Volume => primary.Volume;
public BindableDouble Balance => primary.Balance;
public BindableDouble Frequency => primary.Frequency;
public int PlaybackConcurrency
{
get => primary.PlaybackConcurrency;
set => primary.PlaybackConcurrency = value;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
namespace osu.Game.Rulesets.UI
{
public class FallbackSampleStore : ISampleStore
{
private readonly ISampleStore primary;
private readonly ISampleStore secondary;
public FallbackSampleStore(ISampleStore primary, ISampleStore secondary)
{
this.primary = primary;
this.secondary = secondary;
}
public void Dispose()
{
primary.Dispose();
secondary.Dispose();
}
public SampleChannel Get(string name) => primary.Get(name) ?? secondary.Get(name);
public Task<SampleChannel> GetAsync(string name) => primary.GetAsync(name) ?? secondary.GetAsync(name);
public Stream GetStream(string name) => primary.GetStream(name) ?? secondary.GetStream(name);
public IEnumerable<string> GetAvailableResources() => primary.GetAvailableResources().Concat(secondary.GetAvailableResources());
public void AddAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.AddAdjustment(type, adjustBindable);
secondary.AddAdjustment(type, adjustBindable);
}
public void RemoveAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.RemoveAdjustment(type, adjustBindable);
primary.RemoveAdjustment(type, adjustBindable);
}
public BindableDouble Volume => primary.Volume;
public BindableDouble Balance => primary.Balance;
public BindableDouble Frequency => primary.Frequency;
public int PlaybackConcurrency
{
get => primary.PlaybackConcurrency;
set => primary.PlaybackConcurrency = value;
}
}
}
| mit | C# |
cf77cd685d7e7ff2bca37b0f8290e4a2aa7012d1 | Add singleton CallContext.Default (#1740) | AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet,AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet,AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet,AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet | src/Microsoft.IdentityModel.Tokens/CallContext.cs | src/Microsoft.IdentityModel.Tokens/CallContext.cs | //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Microsoft.IdentityModel.Tokens
{
/// <summary>
/// An opaque context used to store work when working with authentication artifacts.
/// </summary>
public class CallContext
{
private static CallContext _defaultContext = new CallContext(Guid.NewGuid()) { CaptureLogs = false };
/// <summary>
/// Instantiates a new <see cref="CallContext"/> with a default activityId.
/// </summary>
public CallContext()
{
}
/// <summary>
/// Instantiates a new <see cref="CallContext"/> with an activityId.
/// </summary>
public CallContext(Guid activityId)
{
ActivityId = activityId;
}
/// <summary>
/// Gets or set a <see cref="Guid"/> that will be used in the call to EventSource.SetCurrentThreadActivityId before logging.
/// </summary>
public Guid ActivityId { get; set; } = Guid.Empty;
/// <summary>
/// Gets or sets a boolean controlling if logs are written into the context.
/// Useful when debugging.
/// </summary>
public bool CaptureLogs { get; set; } = false;
/// <summary>
/// Instantiates a new singleton <see cref="CallContext"/> with a false <see cref="CaptureLogs"/>.
/// </summary>
public static CallContext Default { get => _defaultContext; }
/// <summary>
/// The collection of logs associated with a request. Use <see cref="CaptureLogs"/> to control capture.
/// </summary>
public ICollection<string> Logs { get; private set; } = new Collection<string>();
/// <summary>
/// Gets or sets an <see cref="IDictionary{String, Object}"/> that enables custom extensibility scenarios.
/// </summary>
public IDictionary<string, object> PropertyBag { get; set; }
}
}
| //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Microsoft.IdentityModel.Tokens
{
/// <summary>
/// An opaque context used to store work when working with authentication artifacts.
/// </summary>
public class CallContext
{
/// <summary>
/// Instantiates a new <see cref="CallContext"/> with a default activityId.
/// </summary>
public CallContext()
{
}
/// <summary>
/// Instantiates a new <see cref="CallContext"/> with an activityId.
/// </summary>
public CallContext(Guid activityId)
{
ActivityId = activityId;
}
/// <summary>
/// Gets or set a <see cref="Guid"/> that will be used in the call to EventSource.SetCurrentThreadActivityId before logging.
/// </summary>
public Guid ActivityId { get; set; } = Guid.Empty;
/// <summary>
/// Gets or sets a boolean controlling if logs are written into the context.
/// Useful when debugging.
/// </summary>
public bool CaptureLogs { get; set; } = false;
/// <summary>
/// The collection of logs associated with a request. Use <see cref="CaptureLogs"/> to control capture.
/// </summary>
public ICollection<string> Logs { get; private set; } = new Collection<string>();
/// <summary>
/// Gets or sets an <see cref="IDictionary{String, Object}"/> that enables custom extensibility scenarios.
/// </summary>
public IDictionary<string, object> PropertyBag { get; set; }
}
}
| mit | C# |
d29bcefb9c0d27b78aab12ba978f51e3c2cff547 | Add missing changes for last commit | cognisant/cr-viewmodels | src/Persistence.RavenDB/RavenDBViewModelHelper.cs | src/Persistence.RavenDB/RavenDBViewModelHelper.cs | // <copyright file="RavenDBViewModelHelper.cs" company="Cognisant">
// Copyright (c) Cognisant. All rights reserved.
// </copyright>
namespace CR.ViewModels.Persistence.RavenDB
{
/// <summary>
/// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>.
/// </summary>
// ReSharper disable once InconsistentNaming
internal static class RavenDBViewModelHelper
{
/// <summary>
/// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored.
/// </summary>
/// <typeparam name="TEntity">The type of the View Model.</typeparam>
/// <param name="key">The key of the view model.</param>
/// <returns>The ID of the RavenDB document.</returns>
// ReSharper disable once InconsistentNaming
internal static string MakeID<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}";
}
}
| // <copyright file="RavenDBViewModelHelper.cs" company="Cognisant">
// Copyright (c) Cognisant. All rights reserved.
// </copyright>
namespace CR.ViewModels.Persistence.RavenDB
{
/// <summary>
/// Helper class used for code shared between <see cref="RavenDBViewModelReader"/> and <see cref="RavenDBViewModelWriter"/>.
/// </summary>
// ReSharper disable once InconsistentNaming
internal static class RavenDBViewModelHelper
{
/// <summary>
/// Helper method used to generate the ID of the RavenDB document that a view model of type TEntity with specified key should be stored.
/// </summary>
/// <typeparam name="TEntity">The type of the View Model.</typeparam>
/// <param name="key">The key of the view model.</param>
/// <returns>The ID of the RavenDB document.</returns>
internal static string MakeId<TEntity>(string key) => $"{typeof(TEntity).FullName}/{key}";
}
}
| bsd-3-clause | C# |
280593abadac0bd39a8d7b6df4bb7989b6dfae1f | fix possible utc issue for daylight savings time and InsertUpdateLogBehavior (thanks @MykhayloKonopelskyy) | rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity | Serenity.Services/RequestHandlers/IntegratedFeatures/InsertUpdateLog/InsertUpdateLogBehavior.cs | Serenity.Services/RequestHandlers/IntegratedFeatures/InsertUpdateLog/InsertUpdateLogBehavior.cs | using Serenity.Data;
using System;
using System.Globalization;
namespace Serenity.Services
{
public class UpdateInsertLogBehavior : BaseSaveBehavior, IImplicitBehavior
{
public bool ActivateFor(Row row)
{
return row is IUpdateLogRow || row is IInsertLogRow;
}
public override void OnSetInternalFields(ISaveRequestHandler handler)
{
var row = handler.Row;
var updateLogRow = row as IUpdateLogRow;
var insertLogRow = row as IInsertLogRow;
Field field;
if (updateLogRow != null && (handler.IsUpdate || insertLogRow == null))
{
updateLogRow.UpdateDateField[row] = updateLogRow.UpdateDateField.DateTimeKind == DateTimeKind.Utc ?
DateTime.UtcNow : DateTime.Now;
if (updateLogRow.UpdateUserIdField.IsIntegerType)
updateLogRow.UpdateUserIdField[row] = Authorization.UserId.TryParseID();
else
{
field = (Field)updateLogRow.UpdateUserIdField;
field.AsObject(row, field.ConvertValue(Authorization.UserId, CultureInfo.InvariantCulture));
}
}
else if (insertLogRow != null && handler.IsCreate)
{
insertLogRow.InsertDateField[row] = insertLogRow.InsertDateField.DateTimeKind == DateTimeKind.Utc ?
DateTime.UtcNow : DateTime.Now;
if (insertLogRow.InsertUserIdField.IsIntegerType)
insertLogRow.InsertUserIdField[row] = Authorization.UserId.TryParseID();
else
{
field = (Field)insertLogRow.InsertUserIdField;
field.AsObject(row, field.ConvertValue(Authorization.UserId, CultureInfo.InvariantCulture));
}
}
}
}
} | using Serenity.Data;
using System;
using System.Globalization;
namespace Serenity.Services
{
public class UpdateInsertLogBehavior : BaseSaveBehavior, IImplicitBehavior
{
public bool ActivateFor(Row row)
{
return row is IUpdateLogRow || row is IInsertLogRow;
}
public override void OnSetInternalFields(ISaveRequestHandler handler)
{
var row = handler.Row;
var updateLogRow = row as IUpdateLogRow;
var insertLogRow = row as IInsertLogRow;
Field field;
if (updateLogRow != null && (handler.IsUpdate || insertLogRow == null))
{
updateLogRow.UpdateDateField[row] = DateTimeField.ToDateTimeKind(DateTime.Now, updateLogRow.UpdateDateField.DateTimeKind);
if (updateLogRow.UpdateUserIdField.IsIntegerType)
updateLogRow.UpdateUserIdField[row] = Authorization.UserId.TryParseID();
else
{
field = (Field)updateLogRow.UpdateUserIdField;
field.AsObject(row, field.ConvertValue(Authorization.UserId, CultureInfo.InvariantCulture));
}
}
else if (insertLogRow != null && handler.IsCreate)
{
insertLogRow.InsertDateField[row] = DateTimeField.ToDateTimeKind(DateTime.Now, insertLogRow.InsertDateField.DateTimeKind);
if (insertLogRow.InsertUserIdField.IsIntegerType)
insertLogRow.InsertUserIdField[row] = Authorization.UserId.TryParseID();
else
{
field = (Field)insertLogRow.InsertUserIdField;
field.AsObject(row, field.ConvertValue(Authorization.UserId, CultureInfo.InvariantCulture));
}
}
}
}
} | mit | C# |
1a5947349770bf892306bbe41868652af447d377 | Fix unit test. | jan-schubert/CrossMailing,jan-schubert/CrossApplication | Source/Wpf/CrossApplication.Wpf.Application.UnitTest/_Shell/_RichShellViewModel/StateMessage.cs | Source/Wpf/CrossApplication.Wpf.Application.UnitTest/_Shell/_RichShellViewModel/StateMessage.cs | using System.Collections.Generic;
using System.Threading;
using CrossApplication.Core.Contracts.Application.Events;
using CrossApplication.Core.Contracts.Common.Navigation;
using CrossApplication.Core.Net.Contracts.Navigation;
using CrossApplication.Wpf.Application.Shell;
using CrossApplication.Wpf.Application.Shell.RibbonTabs;
using FluentAssertions;
using Moq;
using Prism.Events;
using Prism.Regions;
using Xunit;
namespace CrossApplication.Wpf.Application.UnitTest._Shell._RichShellViewModel
{
public class StateMessage
{
[Fact]
public async void ShouldSetStateIfStateMessageEventIsPublished()
{
var eventAggregator = new EventAggregator();
var viewModel = new RichShellViewModel(null, new List<IMainNavigationItem>(), new Mock<INavigationService>().Object, new List<IBackstageTabViewModel>(), new Mock<IRegionManager>().Object, eventAggregator);
await viewModel.OnViewLoadedAsync();
var resetEvent = new AutoResetEvent(false);
viewModel.PropertyChanged += (sender, args) => resetEvent.Set();
eventAggregator.GetEvent<PubSubEvent<StateMessageEvent>>().Publish(new StateMessageEvent("Test message."));
resetEvent.WaitOne(200).Should().BeTrue();
viewModel.StateMessage.Should().Be("Test message.");
}
[Fact]
public async void ShouldNotRefreshStateIfViewIsUnloaded()
{
var eventAggregator = new EventAggregator();
var viewModel = new RichShellViewModel(null, new List<IMainNavigationItem>(), new Mock<INavigationService>().Object, new List<IBackstageTabViewModel>(), new Mock<IRegionManager>().Object, eventAggregator);
await viewModel.OnViewLoadedAsync();
var resetEvent = new AutoResetEvent(false);
viewModel.PropertyChanged += (sender, args) => resetEvent.Set();
eventAggregator.GetEvent<PubSubEvent<StateMessageEvent>>().Publish(new StateMessageEvent("Test message."));
resetEvent.WaitOne(1000).Should().BeTrue();
await viewModel.OnViewUnloadedAsync();
eventAggregator.GetEvent<PubSubEvent<StateMessageEvent>>().Publish(new StateMessageEvent("Next test message."));
resetEvent.WaitOne(1200).Should().BeFalse();
viewModel.StateMessage.Should().Be("Test message.");
}
}
} | using System.Collections.Generic;
using System.Threading;
using CrossApplication.Core.Contracts.Application.Events;
using CrossApplication.Core.Contracts.Common.Navigation;
using CrossApplication.Core.Net.Contracts.Navigation;
using CrossApplication.Wpf.Application.Shell;
using CrossApplication.Wpf.Application.Shell.RibbonTabs;
using FluentAssertions;
using Moq;
using Prism.Events;
using Prism.Regions;
using Xunit;
namespace CrossApplication.Wpf.Application.UnitTest._Shell._RichShellViewModel
{
public class StateMessage
{
[Fact]
public async void ShouldSetStateIfStateMessageEventIsPublished()
{
var eventAggregator = new EventAggregator();
var viewModel = new RichShellViewModel(null, new List<IMainNavigationItem>(), new Mock<INavigationService>().Object, new List<IBackstageTabViewModel>(), new Mock<IRegionManager>().Object, eventAggregator);
await viewModel.OnViewLoadedAsync();
var resetEvent = new AutoResetEvent(false);
viewModel.PropertyChanged += (sender, args) => resetEvent.Set();
eventAggregator.GetEvent<PubSubEvent<StateMessageEvent>>().Publish(new StateMessageEvent("Test message."));
resetEvent.WaitOne(200).Should().BeTrue();
viewModel.StateMessage.Should().Be("Test message.");
}
[Fact]
public async void ShouldNotRefreshStateIfViewIsUnloaded()
{
var eventAggregator = new EventAggregator();
var viewModel = new RichShellViewModel(null, new List<IMainNavigationItem>(), new Mock<INavigationService>().Object, new List<IBackstageTabViewModel>(), new Mock<IRegionManager>().Object, eventAggregator);
await viewModel.OnViewLoadedAsync();
var resetEvent = new AutoResetEvent(false);
viewModel.PropertyChanged += (sender, args) => resetEvent.Set();
eventAggregator.GetEvent<PubSubEvent<StateMessageEvent>>().Publish(new StateMessageEvent("Test message."));
resetEvent.WaitOne(200).Should().BeTrue();
await viewModel.OnViewUnloadedAsync();
eventAggregator.GetEvent<PubSubEvent<StateMessageEvent>>().Publish(new StateMessageEvent("Next test message."));
resetEvent.WaitOne(1200).Should().BeFalse();
viewModel.StateMessage.Should().Be("Test message.");
}
}
} | apache-2.0 | C# |
7e6894ca15f6f92daa9bbd2144f18bb508ff6c1a | include test results from sub directories when slicing by previous test runs | sebastianhallen/Mandolin | src/Mandolin/Slicers/Scorer/DirectoryScanningNUnitResultsRepository.cs | src/Mandolin/Slicers/Scorer/DirectoryScanningNUnitResultsRepository.cs | namespace Mandolin.Slicers.Scorer
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
public class DirectoryScanningNUnitResultsRepository
: INUnitResultsRepository
{
private readonly string path;
public DirectoryScanningNUnitResultsRepository(string path)
{
this.path = path;
}
public IEnumerable<INUnitResult> All()
{
if (string.IsNullOrWhiteSpace(this.path)) return Enumerable.Empty<INUnitResult>();
return from file in Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories)
let xml = ParseXml(file)
from testCase in xml.Descendants(XName.Get("test-case"))
let name = testCase.Attribute("name").Value
let time = testCase.Attribute("time")
where time != null
let duration = time.Value
let durationMilliseconds = ToMilliseconds(duration)
where durationMilliseconds > 0
select new NUnitResult(TimeSpan.FromMilliseconds(durationMilliseconds), name);
}
private int ToMilliseconds(string duration)
{
int milliseconds;
return int.TryParse(duration.Replace(".", ""), out milliseconds)
? milliseconds
: 0;
}
private XDocument ParseXml(string filePath)
{
try
{
return XDocument.Load(filePath);
}
catch (Exception)
{
return XDocument.Parse("");
}
}
}
} | namespace Mandolin.Slicers.Scorer
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
public class DirectoryScanningNUnitResultsRepository
: INUnitResultsRepository
{
private readonly string path;
public DirectoryScanningNUnitResultsRepository(string path)
{
this.path = path;
}
public IEnumerable<INUnitResult> All()
{
if (string.IsNullOrWhiteSpace(this.path)) return Enumerable.Empty<INUnitResult>();
return from file in Directory.GetFiles(path, "*.xml")
let xml = ParseXml(file)
from testCase in xml.Descendants(XName.Get("test-case"))
let name = testCase.Attribute("name").Value
let time = testCase.Attribute("time")
where time != null
let duration = time.Value
let durationMilliseconds = ToMilliseconds(duration)
where durationMilliseconds > 0
select new NUnitResult(TimeSpan.FromMilliseconds(durationMilliseconds), name);
}
private int ToMilliseconds(string duration)
{
int milliseconds;
return int.TryParse(duration.Replace(".", ""), out milliseconds)
? milliseconds
: 0;
}
private XDocument ParseXml(string filePath)
{
try
{
return XDocument.Load(filePath);
}
catch (Exception)
{
return XDocument.Parse("");
}
}
}
} | mit | C# |
3c8552f80226ed20b9958b66e017650eb7ca64df | Make implementation internal | pardahlman/RawRabbit | src/RawRabbit.Enrichers.ZeroFormatter/ZeroFormatterSerializerWorker.cs | src/RawRabbit.Enrichers.ZeroFormatter/ZeroFormatterSerializerWorker.cs | using System;
using System.Linq;
using System.Reflection;
using RawRabbit.Serialization;
using ZeroFormatter;
namespace RawRabbit.Enrichers.ZeroFormatter
{
internal class ZeroFormatterSerializerWorker : ISerializer
{
public string ContentType => "application/x-zeroformatter";
private readonly MethodInfo _deserializeType;
private readonly MethodInfo _serializeType;
public ZeroFormatterSerializerWorker()
{
_deserializeType = typeof(ZeroFormatterSerializer)
.GetMethod(nameof(ZeroFormatterSerializer.Deserialize), new[] { typeof(byte[]) });
_serializeType = typeof(ZeroFormatterSerializer)
.GetMethods()
.FirstOrDefault(s => s.Name == nameof(ZeroFormatterSerializer.Serialize) && s.ReturnType == typeof(byte[]));
}
public byte[] Serialize(object obj)
{
if (obj == null)
throw new ArgumentNullException();
return (byte[])_serializeType
.MakeGenericMethod(obj.GetType())
.Invoke(null, new[] { obj });
}
public object Deserialize(Type type, byte[] bytes)
{
return _deserializeType.MakeGenericMethod(type)
.Invoke(null, new object[] { bytes });
}
public TType Deserialize<TType>(byte[] bytes)
{
return ZeroFormatterSerializer.Deserialize<TType>(bytes);
}
}
}
| using System;
using System.Linq;
using System.Reflection;
using RawRabbit.Serialization;
using ZeroFormatter;
namespace RawRabbit.Enrichers.ZeroFormatter
{
public class ZeroFormatterSerializerWorker : ISerializer
{
public string ContentType => "application/x-zeroformatter";
private readonly MethodInfo _deserializeType;
private readonly MethodInfo _serializeType;
public ZeroFormatterSerializerWorker()
{
_deserializeType = typeof(ZeroFormatterSerializer)
.GetMethod(nameof(ZeroFormatterSerializer.Deserialize), new[] { typeof(byte[]) });
_serializeType = typeof(ZeroFormatterSerializer)
.GetMethods()
.FirstOrDefault(s => s.Name == nameof(ZeroFormatterSerializer.Serialize) && s.ReturnType == typeof(byte[]));
}
public byte[] Serialize(object obj)
{
if (obj == null)
throw new ArgumentNullException();
return (byte[])_serializeType
.MakeGenericMethod(obj.GetType())
.Invoke(null, new[] { obj });
}
public object Deserialize(Type type, byte[] bytes)
{
return _deserializeType.MakeGenericMethod(type)
.Invoke(null, new object[] { bytes });
}
public TType Deserialize<TType>(byte[] bytes)
{
return ZeroFormatterSerializer.Deserialize<TType>(bytes);
}
}
} | mit | C# |
a2cd27550d6c0df1f25cb053aa5803c15e49d2df | Add TrimToOne | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/String.Trim.cs | source/Nuke.Common/Utilities/String.Trim.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
[Pure]
public static string TrimToOne(this string str, string trim)
{
while (str.Contains(trim + trim))
{
str = str.Replace(trim + trim, trim);
}
return str;
}
[Pure]
public static string TrimEnd(this string str, string trim)
{
return str.EndsWith(trim) ? str.Substring(startIndex: 0, str.Length - trim.Length) : str;
}
[Pure]
public static string TrimStart(this string str, string trim)
{
return str.StartsWith(trim) ? str.Substring(trim.Length) : str;
}
[Pure]
public static string TrimMatchingQuotes(this string str, char quote)
{
if (str.Length < 2)
return str;
if (str[index: 0] != quote || str[str.Length - 1] != quote)
return str;
return str.Substring(startIndex: 1, str.Length - 2);
}
[Pure]
public static string TrimMatchingDoubleQuotes(this string str)
{
return TrimMatchingQuotes(str, quote: '"');
}
[Pure]
public static string TrimMatchingQuotes(this string str)
{
return TrimMatchingQuotes(str, quote: '\'');
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
public static partial class StringExtensions
{
[Pure]
public static string TrimEnd(this string str, string trim)
{
return str.EndsWith(trim) ? str.Substring(startIndex: 0, str.Length - trim.Length) : str;
}
[Pure]
public static string TrimStart(this string str, string trim)
{
return str.StartsWith(trim) ? str.Substring(trim.Length) : str;
}
[Pure]
public static string TrimMatchingQuotes(this string str, char quote)
{
if (str.Length < 2)
return str;
if (str[index: 0] != quote || str[str.Length - 1] != quote)
return str;
return str.Substring(startIndex: 1, str.Length - 2);
}
[Pure]
public static string TrimMatchingDoubleQuotes(this string str)
{
return TrimMatchingQuotes(str, quote: '"');
}
[Pure]
public static string TrimMatchingQuotes(this string str)
{
return TrimMatchingQuotes(str, quote: '\'');
}
}
}
| mit | C# |
91c415f29b693460123762b6e7023c15d32b856c | Fix nullability oversight in `ManiaRulesetConfigManager` | peppy/osu,peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu | osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs | osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore? settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
SetDefault(ManiaRulesetSetting.ScrollTime, 1500.0, DrawableManiaRuleset.MIN_TIME_RANGE, DrawableManiaRuleset.MAX_TIME_RANGE, 5);
SetDefault(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
SetDefault(ManiaRulesetSetting.TimingBasedNoteColouring, false);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime,
scrollTime => new SettingDescription(
rawValue: scrollTime,
name: "Scroll Speed",
value: $"{scrollTime}ms (speed {(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / scrollTime)})"
)
)
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection,
TimingBasedNoteColouring
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using osu.Framework.Configuration.Tracking;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
using osu.Game.Rulesets.Mania.UI;
namespace osu.Game.Rulesets.Mania.Configuration
{
public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting>
{
public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null)
: base(settings, ruleset, variant)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
SetDefault(ManiaRulesetSetting.ScrollTime, 1500.0, DrawableManiaRuleset.MIN_TIME_RANGE, DrawableManiaRuleset.MAX_TIME_RANGE, 5);
SetDefault(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down);
SetDefault(ManiaRulesetSetting.TimingBasedNoteColouring, false);
}
public override TrackedSettings CreateTrackedSettings() => new TrackedSettings
{
new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime,
scrollTime => new SettingDescription(
rawValue: scrollTime,
name: "Scroll Speed",
value: $"{scrollTime}ms (speed {(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / scrollTime)})"
)
)
};
}
public enum ManiaRulesetSetting
{
ScrollTime,
ScrollDirection,
TimingBasedNoteColouring
}
}
| mit | C# |
8d4c9eda489fb5791a2a4b931f7850a57d134108 | Fix attempting to add selection boxes with no selection | naoey/osu,peppy/osu,smoogipoo/osu,DrabWeb/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,ZLima12/osu,NeoAdonis/osu,EVAST9919/osu,Frontear/osuKyzer,Nabile-Rahmani/osu,2yangk23/osu,peppy/osu,naoey/osu,NeoAdonis/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,DrabWeb/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,DrabWeb/osu,EVAST9919/osu,ZLima12/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,naoey/osu,johnneijzen/osu | osu.Game/Screens/Edit/Screens/Compose/Layers/HitObjectMaskLayer.cs | osu.Game/Screens/Edit/Screens/Compose/Layers/HitObjectMaskLayer.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Screens.Edit.Screens.Compose.Layers
{
public class HitObjectMaskLayer : CompositeDrawable
{
private readonly HitObjectComposer composer;
private readonly Container<HitObjectMask> overlayContainer;
public HitObjectMaskLayer(HitObjectComposer composer)
{
this.composer = composer;
RelativeSizeAxes = Axes.Both;
InternalChild = overlayContainer = new Container<HitObjectMask> { RelativeSizeAxes = Axes.Both };
}
/// <summary>
/// Adds an overlay for a <see cref="DrawableHitObject"/> which adds movement support.
/// </summary>
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to create an overlay for.</param>
public void AddOverlay(DrawableHitObject hitObject)
{
var overlay = composer.CreateMaskFor(hitObject);
if (overlay == null)
return;
overlayContainer.Add(overlay);
}
/// <summary>
/// Removes the overlay for a <see cref="DrawableHitObject"/>.
/// </summary>
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to remove the overlay for.</param>
public void RemoveOverlay(DrawableHitObject hitObject)
{
var existing = overlayContainer.FirstOrDefault(h => h.HitObject == hitObject);
if (existing == null)
return;
existing.Hide();
existing.Expire();
}
private SelectionBox currentSelectionBox;
public void AddSelectionOverlay()
{
if (overlayContainer.Count > 0)
AddInternal(currentSelectionBox = composer.CreateSelectionOverlay(overlayContainer));
}
public void RemoveSelectionOverlay()
{
currentSelectionBox?.Hide();
currentSelectionBox?.Expire();
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Screens.Edit.Screens.Compose.Layers
{
public class HitObjectMaskLayer : CompositeDrawable
{
private readonly HitObjectComposer composer;
private readonly Container<HitObjectMask> overlayContainer;
public HitObjectMaskLayer(HitObjectComposer composer)
{
this.composer = composer;
RelativeSizeAxes = Axes.Both;
InternalChild = overlayContainer = new Container<HitObjectMask> { RelativeSizeAxes = Axes.Both };
}
/// <summary>
/// Adds an overlay for a <see cref="DrawableHitObject"/> which adds movement support.
/// </summary>
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to create an overlay for.</param>
public void AddOverlay(DrawableHitObject hitObject)
{
var overlay = composer.CreateMaskFor(hitObject);
if (overlay == null)
return;
overlayContainer.Add(overlay);
}
/// <summary>
/// Removes the overlay for a <see cref="DrawableHitObject"/>.
/// </summary>
/// <param name="hitObject">The <see cref="DrawableHitObject"/> to remove the overlay for.</param>
public void RemoveOverlay(DrawableHitObject hitObject)
{
var existing = overlayContainer.FirstOrDefault(h => h.HitObject == hitObject);
if (existing == null)
return;
existing.Hide();
existing.Expire();
}
private SelectionBox currentSelectionBox;
public void AddSelectionOverlay() => AddInternal(currentSelectionBox = composer.CreateSelectionOverlay(overlayContainer));
public void RemoveSelectionOverlay()
{
currentSelectionBox?.Hide();
currentSelectionBox?.Expire();
}
}
}
| mit | C# |
eb3dd1c72a0202bb0ddc669364b3c4e57e07412d | Fix git remote callbacks | libgit2/libgit2sharp,PKRoma/libgit2sharp | LibGit2Sharp/Core/GitRemoteCallbacks.cs | LibGit2Sharp/Core/GitRemoteCallbacks.cs | using System;
using System.Runtime.InteropServices;
namespace LibGit2Sharp.Core
{
/// <summary>
/// Structure for git_remote_callbacks
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct GitRemoteCallbacks
{
internal uint version;
internal NativeMethods.remote_progress_callback progress;
internal NativeMethods.remote_completion_callback completion;
internal NativeMethods.git_cred_acquire_cb acquire_credentials;
internal NativeMethods.git_transport_certificate_check_cb certificate_check;
internal NativeMethods.git_transfer_progress_callback download_progress;
internal NativeMethods.remote_update_tips_callback update_tips;
internal NativeMethods.git_packbuilder_progress pack_progress;
internal NativeMethods.git_push_transfer_progress push_transfer_progress;
internal NativeMethods.push_update_reference_callback push_update_reference;
internal NativeMethods.push_negotiation_callback push_negotiation;
internal IntPtr transport;
private IntPtr padding; // TODO: add git_remote_ready_cb
internal IntPtr payload;
internal NativeMethods.url_resolve_callback resolve_url;
}
}
| using System;
using System.Runtime.InteropServices;
namespace LibGit2Sharp.Core
{
/// <summary>
/// Structure for git_remote_callbacks
/// </summary>
[StructLayout(LayoutKind.Sequential)]
internal struct GitRemoteCallbacks
{
internal uint version;
internal NativeMethods.remote_progress_callback progress;
internal NativeMethods.remote_completion_callback completion;
internal NativeMethods.git_cred_acquire_cb acquire_credentials;
internal NativeMethods.git_transport_certificate_check_cb certificate_check;
internal NativeMethods.git_transfer_progress_callback download_progress;
internal NativeMethods.remote_update_tips_callback update_tips;
internal NativeMethods.git_packbuilder_progress pack_progress;
internal NativeMethods.git_push_transfer_progress push_transfer_progress;
internal NativeMethods.push_update_reference_callback push_update_reference;
internal NativeMethods.push_negotiation_callback push_negotiation;
internal IntPtr transport;
internal IntPtr payload;
internal NativeMethods.url_resolve_callback resolve_url;
}
}
| mit | C# |
3b98426b9c91a60cddbb53c98cf210546a81828a | rename postgresql processor. | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | src/DotNetCore.CAP.PostgreSql/CAP.PostgreSqlCapOptionsExtension.cs | src/DotNetCore.CAP.PostgreSql/CAP.PostgreSqlCapOptionsExtension.cs | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using DotNetCore.CAP.PostgreSql;
using DotNetCore.CAP.Processor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
internal class PostgreSqlCapOptionsExtension : ICapOptionsExtension
{
private readonly Action<PostgreSqlOptions> _configure;
public PostgreSqlCapOptionsExtension(Action<PostgreSqlOptions> configure)
{
_configure = configure;
}
public void AddServices(IServiceCollection services)
{
services.AddSingleton<CapDatabaseStorageMarkerService>();
services.AddSingleton<IStorage, PostgreSqlStorage>();
services.AddSingleton<IStorageConnection, PostgreSqlStorageConnection>();
services.AddScoped<ICapPublisher, CapPublisher>();
services.AddScoped<ICallbackPublisher, CapPublisher>();
services.AddTransient<ICollectProcessor, PostgreSqlCollectProcessor>();
AddSingletonPostgreSqlOptions(services);
}
private void AddSingletonPostgreSqlOptions(IServiceCollection services)
{
var postgreSqlOptions = new PostgreSqlOptions();
_configure(postgreSqlOptions);
if (postgreSqlOptions.DbContextType != null)
{
services.AddSingleton(x =>
{
using (var scope = x.CreateScope())
{
var provider = scope.ServiceProvider;
var dbContext = (DbContext) provider.GetService(postgreSqlOptions.DbContextType);
postgreSqlOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
return postgreSqlOptions;
}
});
}
else
{
services.AddSingleton(postgreSqlOptions);
}
}
}
} | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using DotNetCore.CAP.PostgreSql;
using DotNetCore.CAP.Processor;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
internal class PostgreSqlCapOptionsExtension : ICapOptionsExtension
{
private readonly Action<PostgreSqlOptions> _configure;
public PostgreSqlCapOptionsExtension(Action<PostgreSqlOptions> configure)
{
_configure = configure;
}
public void AddServices(IServiceCollection services)
{
services.AddSingleton<CapDatabaseStorageMarkerService>();
services.AddSingleton<IStorage, PostgreSqlStorage>();
services.AddSingleton<IStorageConnection, PostgreSqlStorageConnection>();
services.AddScoped<ICapPublisher, CapPublisher>();
services.AddScoped<ICallbackPublisher, CapPublisher>();
services.AddTransient<IAdditionalProcessor, DefaultAdditionalProcessor>();
AddSingletonPostgreSqlOptions(services);
}
private void AddSingletonPostgreSqlOptions(IServiceCollection services)
{
var postgreSqlOptions = new PostgreSqlOptions();
_configure(postgreSqlOptions);
if (postgreSqlOptions.DbContextType != null)
{
services.AddSingleton(x =>
{
using (var scope = x.CreateScope())
{
var provider = scope.ServiceProvider;
var dbContext = (DbContext) provider.GetService(postgreSqlOptions.DbContextType);
postgreSqlOptions.ConnectionString = dbContext.Database.GetDbConnection().ConnectionString;
return postgreSqlOptions;
}
});
}
else
{
services.AddSingleton(postgreSqlOptions);
}
}
}
} | mit | C# |
e2b90b616db2cfd4081e772d14922f81dd9451db | Fix forceMicrogame in MicrogameStage not working | Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare,uulltt/NitoriWare | Assets/Scripts/Stage/MicrogameStage.cs | Assets/Scripts/Stage/MicrogameStage.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicrogameStage : Stage
{
public static string microgameId;
[SerializeField]
private string forceMicrogame;
void Start()
{
}
public override Microgame getMicrogame(int num)
{
Microgame microgame = new Microgame();
microgame.microgameId = !string.IsNullOrEmpty(forceMicrogame) ? forceMicrogame : microgameId;
microgame.baseDifficulty = (num % 3) + 1;
return microgame;
}
public override int getMicrogameDifficulty(Microgame microgame)
{
return microgame.baseDifficulty;
}
public override Interruption[] getInterruptions(int num)
{
if (num == 0 || num % 3 > 0)
return new Interruption[0];
Interruption silentSpeedUp = new Interruption();
silentSpeedUp.speedChange = Interruption.SpeedChange.SpeedUp;
return new Interruption[0].add(silentSpeedUp);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicrogameStage : Stage
{
public static string microgameId;
[SerializeField]
private string forceMicrogame;
void Start()
{
}
public override Microgame getMicrogame(int num)
{
Microgame microgame = new Microgame();
microgame.microgameId = string.IsNullOrEmpty(forceMicrogame) ? forceMicrogame : microgameId;
microgame.baseDifficulty = (num % 3) + 1;
return microgame;
}
public override int getMicrogameDifficulty(Microgame microgame)
{
return microgame.baseDifficulty;
}
public override Interruption[] getInterruptions(int num)
{
if (num == 0 || num % 3 > 0)
return new Interruption[0];
Interruption silentSpeedUp = new Interruption();
silentSpeedUp.speedChange = Interruption.SpeedChange.SpeedUp;
return new Interruption[0].add(silentSpeedUp);
}
}
| mit | C# |
80aad36f9a523c42b401e76f4a7f192de14f7388 | Add support for dynamic resizing of iframe when disqus forum loads | DenverDev/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,opencolorado/.NET-Wrapper-for-CKAN-API,DenverDev/.NET-Wrapper-for-CKAN-API | CkanDotNet.Web/Views/Shared/Package/_Disqus.cshtml | CkanDotNet.Web/Views/Shared/Package/_Disqus.cshtml | @using CkanDotNet.Web.Models.Helpers
<div class="container">
<h2 class="container-title">Comments</h2>
<div class="container-content">
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname
@if (SettingsHelper.GetDisqusDeveloperModeEnabled())
{
<text>var disqus_developer = 1; // developer mode is on</text>
}
@if (SettingsHelper.GetIframeEnabled())
{
<text>
function disqus_config() {
this.callbacks.onNewComment = [function() { resizeFrame() }];
this.callbacks.onReady = [function() { resizeFrame() }];
}
</text>
}
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
| @using CkanDotNet.Web.Models.Helpers
<div class="container">
<h2 class="container-title">Comments</h2>
<div class="container-content">
<div id="disqus_thread"></div>
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = '@SettingsHelper.GetDisqusForumShortName()'; // required: replace example with your forum shortname
@if (SettingsHelper.GetDisqusDeveloperModeEnabled())
{
<text>var disqus_developer = 1; // developer mode is on</text>
}
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
</div>
</div>
| apache-2.0 | C# |
a70c1198d9caba646805c95720d7922b6b1938b1 | Clean Test Lock Files | nkolev92/sdk,nkolev92/sdk | src/Tasks/Microsoft.NETCore.Build.Tasks.UnitTests/TestLockFiles.cs | src/Tasks/Microsoft.NETCore.Build.Tasks.UnitTests/TestLockFiles.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using NuGet.Common;
using NuGet.ProjectModel;
using System.IO;
namespace Microsoft.NETCore.Build.Tasks.UnitTests
{
internal static class TestLockFiles
{
public static LockFile GetLockFile(string lockFilePrefix)
{
string filePath = Path.Combine("LockFiles", $"{lockFilePrefix}.project.lock.json");
return LockFileUtilities.GetLockFile(filePath, NullLogger.Instance);
}
public static LockFile CreateLockFile(string contents, string path = "path/to/project.lock.json")
{
return new LockFileFormat().Parse(contents, path);
}
}
} | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using NuGet.Common;
using NuGet.ProjectModel;
using System.Collections.Generic;
using System;
using System.Linq;
namespace Microsoft.NETCore.Build.Tasks.UnitTests
{
internal static class TestLockFiles
{
public static LockFile GetLockFile(string lockFilePrefix)
{
string filePath = Path.Combine("LockFiles", $"{lockFilePrefix}.project.lock.json");
return LockFileUtilities.GetLockFile(filePath, NullLogger.Instance);
}
public static LockFile CreateLockFile(string contents, string path = "path/to/project.lock.json")
{
return new LockFileFormat().Parse(contents, path);
}
public static string CreateLibrarySnippet(string nameVer, string type = "package", params string [] members)
{
return $@" ""{nameVer}"": {{
""sha512"": ""abcde=="",
""type"": ""{type}"",
""files"": [{ToStringList(members)}]
}}";
}
public static string CreateTargetLibrarySnippet(
string nameVer,
string type = "package",
string[] dependencies = null,
string[] frameworkAssemblies = null,
string[] compile = null,
string[] runtime = null)
{
List<string> parts = new List<string>();
parts.Add($"\"type\": \"{type}\"");
if (frameworkAssemblies != null)
{
parts.Add($"\"frameworkAssemblies\": [{string.Join(",", frameworkAssemblies)}]");
}
Action<string, string[]> addListIfPresent = (label, list) =>
{
if (list != null) parts.Add($"\"{label}\": {{{string.Join(",", list)}}}");
};
addListIfPresent("dependencies", dependencies);
addListIfPresent("compile", compile);
addListIfPresent("runtime", runtime);
return $@" ""{nameVer}"": {{
{string.Join(",", parts)}
}}";
}
private static string ToStringList(params string[] members)
{
return members == null ? string.Empty : string.Join(",", $"\"{members}\"");
}
public static string TargetLibrarySnippet { get; } = @"
{
""locked"": false,
""version"": 2,
""targets"": {},
""libraries"": {},
""projectFileDependencyGroups"": {}
}
";
}
} | mit | C# |
43f3a0efd49149f190f24646cc2237b2e0c919f7 | Fix Generate-Tilemap tile number masking. | Prof9/PixelPet | PixelPet/Commands/GenerateTilemapCmd.cs | PixelPet/Commands/GenerateTilemapCmd.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace PixelPet.Commands {
internal class GenerateTilemapCmd : CliCommand {
public GenerateTilemapCmd()
: base("Generate-Tilemap", new Parameter[] {
new Parameter("palette", "p", false, new ParameterValue("index", "0")),
new Parameter("base-tile", "b", false, new ParameterValue("index", "0")),
new Parameter("first-tile", "f", false, new ParameterValue("tilemap-entry", "-1")),
new Parameter("tile-size", "t", false, new ParameterValue("width", "8"),
new ParameterValue("height", "8")),
}) { }
public override void Run(Workbench workbench, Cli cli) {
int palette = FindNamedParameter("--palette" ).Values[0].ToInt32();
int baseTile = FindNamedParameter("--base-tile" ).Values[0].ToInt32();
int firstTile = FindNamedParameter("--first-tile").Values[0].ToInt32();
int tileWidth = FindNamedParameter("--tile-size" ).Values[0].ToInt32();
int tileHeight = FindNamedParameter("--tile-size" ).Values[1].ToInt32();
cli.Log("Generating tilemap...");
Tilemap tm = new Tilemap(workbench.Bitmap, tileWidth, tileHeight);
tm.Reduce(true);
workbench.SetBitmap(tm.CreateTileset());
workbench.Stream.SetLength(0);
foreach (Tilemap.Entry entry in tm.TileEntries) {
int scrn = 0;
if (firstTile >= 0 && entry.TileNumber == 0) {
scrn = firstTile;
} else {
scrn |= (entry.TileNumber + baseTile) & 0x3FF;
scrn |= entry.FlipHorizontal ? 1 << 10 : 0;
scrn |= entry.FlipVertical ? 1 << 11 : 0;
scrn |= palette << 12;
}
workbench.Stream.WriteByte((byte)(scrn >> 0));
workbench.Stream.WriteByte((byte)(scrn >> 8));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
namespace PixelPet.Commands {
internal class GenerateTilemapCmd : CliCommand {
public GenerateTilemapCmd()
: base("Generate-Tilemap", new Parameter[] {
new Parameter("palette", "p", false, new ParameterValue("index", "0")),
new Parameter("base-tile", "b", false, new ParameterValue("index", "0")),
new Parameter("first-tile", "f", false, new ParameterValue("tilemap-entry", "-1")),
new Parameter("tile-size", "t", false, new ParameterValue("width", "8"),
new ParameterValue("height", "8")),
}) { }
public override void Run(Workbench workbench, Cli cli) {
int palette = FindNamedParameter("--palette" ).Values[0].ToInt32();
int baseTile = FindNamedParameter("--base-tile" ).Values[0].ToInt32();
int firstTile = FindNamedParameter("--first-tile").Values[0].ToInt32();
int tileWidth = FindNamedParameter("--tile-size" ).Values[0].ToInt32();
int tileHeight = FindNamedParameter("--tile-size" ).Values[1].ToInt32();
cli.Log("Generating tilemap...");
Tilemap tm = new Tilemap(workbench.Bitmap, tileWidth, tileHeight);
tm.Reduce(true);
workbench.SetBitmap(tm.CreateTileset());
workbench.Stream.SetLength(0);
foreach (Tilemap.Entry entry in tm.TileEntries) {
int scrn = 0;
if (firstTile >= 0 && entry.TileNumber == 0) {
scrn = firstTile;
} else {
scrn |= (entry.TileNumber + baseTile) & 0x1FF;
scrn |= entry.FlipHorizontal ? 1 << 10 : 0;
scrn |= entry.FlipVertical ? 1 << 11 : 0;
scrn |= palette << 12;
}
workbench.Stream.WriteByte((byte)(scrn >> 0));
workbench.Stream.WriteByte((byte)(scrn >> 8));
}
}
}
}
| mit | C# |
df479f3a08da9442b7edfa3e8d04a98ad6a2e075 | 修复拼接查询参数时会多加一个&符号和多移除最后一位的bug | ctripcorp/apollo.net | Apollo/Util/QueryUtils.cs | Apollo/Util/QueryUtils.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Com.Ctrip.Framework.Apollo.Util
{
static class QueryUtils
{
public static string Build(IReadOnlyCollection<KeyValuePair<string, string>> source)
{
if (source == null || source.Count == 0)
{
return "";
}
var sb = new StringBuilder(source.Count * 32);
foreach (var kv in source)
{
sb.Append('&');
sb.Append(WebUtility.UrlEncode(kv.Key));
sb.Append('=');
sb.Append(WebUtility.UrlEncode(kv.Value));
}
return sb.ToString(1, sb.Length - 1);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Com.Ctrip.Framework.Apollo.Util
{
static class QueryUtils
{
public static string Build(IReadOnlyCollection<KeyValuePair<string, string>> source)
{
var sb = new StringBuilder(source.Count * 32);
foreach (var kv in source)
{
sb.Append('&');
sb.Append(WebUtility.UrlEncode(kv.Key));
sb.Append('=');
sb.Append(WebUtility.UrlEncode(kv.Value));
}
return sb.ToString(0, sb.Length - 1);
}
}
}
| apache-2.0 | C# |
d72a9722a61fc7c0509fdb35d2df09677d97856e | Update SocketServiceInstaller.cs | chucklu/SuperSocket,chucklu/SuperSocket,chucklu/SuperSocket | SocketService/SocketServiceInstaller.cs | SocketService/SocketServiceInstaller.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Configuration.Install;
using System.ServiceProcess;
namespace SuperSocket.SocketService
{
[RunInstaller(true)]
public partial class SocketServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
var serviceDisplayName = ConfigurationManager.AppSettings["ServiceDisplayName"];
if (!string.IsNullOrEmpty(serviceDisplayName))
serviceInstaller.DisplayName = serviceDisplayName;
var serviceDescription = ConfigurationManager.AppSettings["ServiceDescription"];
if (!string.IsNullOrEmpty(serviceDescription))
serviceInstaller.Description = serviceDescription;
var servicesDependedOn = new List<string> { "tcpip" };
var servicesDependedOnConfig = ConfigurationManager.AppSettings["ServicesDependedOn"];
if (!string.IsNullOrEmpty(servicesDependedOnConfig))
servicesDependedOn.AddRange(servicesDependedOnConfig.Split(new char[] { ',', ';' }));
serviceInstaller.ServicesDependedOn = servicesDependedOn.ToArray();
var serviceStartAfterInstall = ConfigurationManager.AppSettings["ServiceStartAfterInstall"];
if (!string.IsNullOrEmpty(serviceStartAfterInstall) && serviceStartAfterInstall.ToLower() == "true")
this.AfterInstall += new InstallEventHandler(ProjectInstaller_AfterInstall);
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController(serviceInstaller.ServiceName);
sc.Start();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Configuration.Install;
using System.ServiceProcess;
namespace SuperSocket.SocketService
{
[RunInstaller(true)]
public partial class SocketServiceInstaller : Installer
{
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
public SocketServiceInstaller()
{
InitializeComponent();
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"];
var serviceDisplayName = ConfigurationManager.AppSettings["ServiceDisplayName"];
if (!string.IsNullOrEmpty(serviceDisplayName))
serviceInstaller.DisplayName = serviceDisplayName;
var serviceDescription = ConfigurationManager.AppSettings["ServiceDescription"];
if (!string.IsNullOrEmpty(serviceDescription))
serviceInstaller.Description = serviceDescription;
var servicesDependedOn = new List<string> { "tcpip" };
var servicesDependedOnConfig = ConfigurationManager.AppSettings["ServicesDependedOn"];
if (!string.IsNullOrEmpty(servicesDependedOnConfig))
servicesDependedOn.AddRange(servicesDependedOnConfig.Split(new char[] { ',', ';' }));
serviceInstaller.ServicesDependedOn = servicesDependedOn.ToArray();
var serviceStartAfterInstall = ConfigurationManager.AppSettings["ServiceStartAfterInstall"];
if (!string.IsNullOrEmpty(serviceStartAfterInstall) && serviceStartAfterInstall.ToLower() == "true")
this.AfterInstall += new InstallEventHandler(ProjectInstaller_AfterInstall);
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
private void ProjectInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceController sc = new ServiceController(serviceInstaller.ServiceName);
sc.Start();
}
}
} | apache-2.0 | C# |
cce68e79123f2fdc9943e7fef0ea3903a51397e1 | Remove #if DESKTOP in Application. | l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto | Source/Eto/Forms/Application.desktop.cs | Source/Eto/Forms/Application.desktop.cs | using System.Collections.Generic;
namespace Eto.Forms
{
public partial interface IApplication
{
void Restart();
void RunIteration();
void CreateStandardMenu(MenuItemCollection menuItems, IEnumerable<Command> commands);
}
public partial class Application
{
public void RunIteration()
{
Handler.RunIteration();
}
public void Restart()
{
Handler.Restart();
}
public void CreateStandardMenu(MenuItemCollection menuItems, IEnumerable<Command> commands = null)
{
Handler.CreateStandardMenu(menuItems, commands ?? GetSystemCommands());
}
}
}
| #if DESKTOP
using System.Collections.Generic;
namespace Eto.Forms
{
public partial interface IApplication
{
void Restart();
void RunIteration();
void CreateStandardMenu(MenuItemCollection menuItems, IEnumerable<Command> commands);
}
public partial class Application
{
public void RunIteration()
{
Handler.RunIteration();
}
public void Restart()
{
Handler.Restart();
}
public void CreateStandardMenu(MenuItemCollection menuItems, IEnumerable<Command> commands = null)
{
Handler.CreateStandardMenu(menuItems, commands ?? GetSystemCommands());
}
}
}
#endif | bsd-3-clause | C# |
eebe816f16af333de15aeeaad0a6a69ec6d17437 | Update GabrielTalavera.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/GabrielTalavera.cs | src/Firehose.Web/Authors/GabrielTalavera.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GabrielTalavera : IAmACommunityMember
{
public string FirstName => "Gabriel";
public string LastName => "Talavera";
public string ShortBioOrTagLine => "Passionate about #PowerShell, Cloud & Automation, DevOps and CyberSecurity | Microsoft Certified Trainer & MCSE Core Infrastructure";
public string StateOrRegion => "Asunción, Paraguay";
public string EmailAddress => string.Empty;
public string TwitterHandle => "gtalavera_ITPro";
public string GravatarHash => "";
public string GitHubHandle => "gabrieltalavera";
public GeoPosition Position => new GeoPosition(-25.2981197,-57.5872534);
public Uri WebSite => new Uri("https://blog.hybridcloud-ops.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://blog.hybridcloud-ops.com/feeds/posts/default/-/powershell?alt=rss"); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class BjornHouben : IAmACommunityMember
{
public string FirstName => "Gabriel";
public string LastName => "Talavera";
public string ShortBioOrTagLine => "Passionate about #PowerShell, Cloud & Automation, DevOps and CyberSecurity | Microsoft Certified Trainer & MCSE Core Infrastructure";
public string StateOrRegion => "Asunción, Paraguay";
public string EmailAddress => string.Empty;
public string TwitterHandle => "gtalavera_ITPro";
public string GravatarHash => "";
public string GitHubHandle => "gabrieltalavera";
public GeoPosition Position => new GeoPosition(-25.2981197,-57.5872534);
public Uri WebSite => new Uri("https://blog.hybridcloud-ops.com");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://blog.hybridcloud-ops.com/feeds/posts/default/-/powershell?alt=rss"); }
}
}
}
| mit | C# |
3963df22948217c584f5f2826400f09f83dcb60d | allow Dot42.Include based on patterns | dot42/api | Dot42/IncludeAttribute.cs | Dot42/IncludeAttribute.cs | // Copyright (C) 2014 dot42
//
// Original filename: IncludeAttribute.cs
//
// 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;
namespace Dot42
{
/// <summary>
/// Indicates that that element to what this attribute is attached should be included in the APK.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
[Ignore]
public sealed class IncludeAttribute : ApplicationRootAttribute
{
/// <summary>
/// When this property is set, the element to what this attribute attached is only included if the type set in this property
/// is included.
/// </summary>
public Type TypeCondition { get; set; }
/// <summary>
/// When this property is set, all types that are instance of the type set in this property are included in the resulting APK.
/// This property can only be used when this attribute is attached to an assembly.
/// </summary>
public Type InstanceOfCondition { get; set; }
/// <summary>
/// Include the given type in the resulting APK.
/// This property can only be used when this attribute is attached to an assembly.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// If set, all members of the type to which this attribute is attached will be included also.
/// </summary>
public bool ApplyToMembers { get; set; }
/// <summary>
/// If set, all types/members matching the pattern will be included. See the documenation
/// on what patterns are supported.
/// <para>
/// This property can only be used when this attribute is attached to an assembly.
/// </para>
/// </summary>
public string Pattern { get; set; }
/// <summary>
/// If true, this conditional will be tried on all types in all assemblies. If false
/// (the default), only types in the assembly containing this attribute are tried.
/// <para>
/// Can be used with <see cref="Pattern"/>.
/// </para>
/// <para>
/// This property can only be used when this attribute is attached to an assembly.
/// </para>
/// </summary>
public bool IsGlobal { get; set; }
}
}
| // Copyright (C) 2014 dot42
//
// Original filename: IncludeAttribute.cs
//
// 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;
namespace Dot42
{
/// <summary>
/// Indicates that that element to what this attribute is attached should be included in the APK.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
[Ignore]
public sealed class IncludeAttribute : ApplicationRootAttribute
{
/// <summary>
/// When this property is set, the element to what this attribute attached is only included if the type set in this property
/// is included.
/// </summary>
public Type TypeCondition { get; set; }
/// <summary>
/// When this property is set, all types that are instance of the type set in this property are included in the resulting APK.
/// This property can only be used when this attribute is attached to an assembly.
/// </summary>
public Type InstanceOfCondition { get; set; }
/// <summary>
/// Include the given type in the resulting APK.
/// This property can only be used when this attribute is attached to an assembly.
/// </summary>
public Type Type { get; set; }
/// <summary>
/// If set, all members of the type to which this attribute is attached will be included also.
/// </summary>
public bool ApplyToMembers { get; set; }
}
}
| apache-2.0 | C# |
7789f86b7229105fed040065058fba6964512aef | Add SupportsReadOnlyMode to package manifest | abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS | src/Umbraco.Core/Models/IDataValueEditor.cs | src/Umbraco.Core/Models/IDataValueEditor.cs | using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
using Umbraco.Cms.Core.Models.Editors;
using Umbraco.Cms.Core.PropertyEditors;
namespace Umbraco.Cms.Core.Models;
/// <summary>
/// Represents an editor for editing data values.
/// </summary>
/// <remarks>This is the base interface for parameter and property value editors.</remarks>
public interface IDataValueEditor
{
/// <summary>
/// Gets the editor view.
/// </summary>
string? View { get; }
/// <summary>
/// Gets the type of the value.
/// </summary>
/// <remarks>The value has to be a valid <see cref="ValueTypes" /> value.</remarks>
string ValueType { get; set; }
/// <summary>
/// Gets a value indicating whether the edited value is read-only.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Gets a value indicating whether to display the associated label.
/// </summary>
bool HideLabel { get; }
/// <summary>
/// Gets a value indicating whether the IDataValueEditor supports readonly mode
/// </summary>
bool SupportsReadOnly => false;
/// <summary>
/// Gets the validators to use to validate the edited value.
/// </summary>
/// <remarks>
/// <para>Use this property to add validators, not to validate. Use <see cref="Validate" /> instead.</para>
/// TODO: replace with AddValidator? WithValidator?
/// </remarks>
List<IValueValidator> Validators { get; }
/// <summary>
/// Validates a property value.
/// </summary>
/// <param name="value">The property value.</param>
/// <param name="required">A value indicating whether the property value is required.</param>
/// <param name="format">A specific format (regex) that the property value must respect.</param>
IEnumerable<ValidationResult> Validate(object? value, bool required, string? format);
/// <summary>
/// Converts a value posted by the editor to a property value.
/// </summary>
object? FromEditor(ContentPropertyData editorValue, object? currentValue);
/// <summary>
/// Converts a property value to a value for the editor.
/// </summary>
object? ToEditor(IProperty property, string? culture = null, string? segment = null);
// TODO: / deal with this when unplugging the xml cache
// why property vs propertyType? services should be injected! etc...
/// <summary>
/// Used for serializing an <see cref="IContent" /> item for packaging
/// </summary>
/// <param name="property"></param>
/// <param name="published"></param>
/// <returns></returns>
IEnumerable<XElement> ConvertDbToXml(IProperty property, bool published);
/// <summary>
/// Used for serializing an <see cref="IContent" /> item for packaging
/// </summary>
/// <param name="propertyType"></param>
/// <param name="value"></param>
/// <returns></returns>
XNode ConvertDbToXml(IPropertyType propertyType, object value);
string ConvertDbToString(IPropertyType propertyType, object? value);
}
| using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
using Umbraco.Cms.Core.Models.Editors;
using Umbraco.Cms.Core.PropertyEditors;
namespace Umbraco.Cms.Core.Models;
/// <summary>
/// Represents an editor for editing data values.
/// </summary>
/// <remarks>This is the base interface for parameter and property value editors.</remarks>
public interface IDataValueEditor
{
/// <summary>
/// Gets the editor view.
/// </summary>
string? View { get; }
/// <summary>
/// Gets the type of the value.
/// </summary>
/// <remarks>The value has to be a valid <see cref="ValueTypes" /> value.</remarks>
string ValueType { get; set; }
/// <summary>
/// Gets a value indicating whether the edited value is read-only.
/// </summary>
bool IsReadOnly { get; }
/// <summary>
/// Gets a value indicating whether to display the associated label.
/// </summary>
bool HideLabel { get; }
/// <summary>
/// Gets the validators to use to validate the edited value.
/// </summary>
/// <remarks>
/// <para>Use this property to add validators, not to validate. Use <see cref="Validate" /> instead.</para>
/// TODO: replace with AddValidator? WithValidator?
/// </remarks>
List<IValueValidator> Validators { get; }
/// <summary>
/// Validates a property value.
/// </summary>
/// <param name="value">The property value.</param>
/// <param name="required">A value indicating whether the property value is required.</param>
/// <param name="format">A specific format (regex) that the property value must respect.</param>
IEnumerable<ValidationResult> Validate(object? value, bool required, string? format);
/// <summary>
/// Converts a value posted by the editor to a property value.
/// </summary>
object? FromEditor(ContentPropertyData editorValue, object? currentValue);
/// <summary>
/// Converts a property value to a value for the editor.
/// </summary>
object? ToEditor(IProperty property, string? culture = null, string? segment = null);
// TODO: / deal with this when unplugging the xml cache
// why property vs propertyType? services should be injected! etc...
/// <summary>
/// Used for serializing an <see cref="IContent" /> item for packaging
/// </summary>
/// <param name="property"></param>
/// <param name="published"></param>
/// <returns></returns>
IEnumerable<XElement> ConvertDbToXml(IProperty property, bool published);
/// <summary>
/// Used for serializing an <see cref="IContent" /> item for packaging
/// </summary>
/// <param name="propertyType"></param>
/// <param name="value"></param>
/// <returns></returns>
XNode ConvertDbToXml(IPropertyType propertyType, object value);
string ConvertDbToString(IPropertyType propertyType, object? value);
}
| mit | C# |
27a7d1463a6140a6decab6f61b7e39e1d184f7fa | Bump assembly version. | izrik/ChamberLib,izrik/ChamberLib,izrik/ChamberLib | AssemblyInfo.cs | AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("ChamberLib")]
[assembly: AssemblyDescription("A cross-platform library to make 3D graphics a little easier.")]
[assembly: AssemblyCompany("Metaphysics Industries, Inc.")]
[assembly: AssemblyCopyright("Copyright 2015 izrik and Metaphysics Industries, Inc.")]
[assembly: AssemblyVersion("0.12")]
| using System.Reflection;
[assembly: AssemblyTitle("ChamberLib")]
[assembly: AssemblyDescription("A cross-platform library to make 3D graphics a little easier.")]
[assembly: AssemblyCompany("Metaphysics Industries, Inc.")]
[assembly: AssemblyCopyright("Copyright 2015 izrik and Metaphysics Industries, Inc.")]
[assembly: AssemblyVersion("0.11")]
| lgpl-2.1 | C# |
749c3ff973cc5a84a792a578d38b2d226e1cb59b | Debug whether we get the controller | Chaojincoolbean/Fly | Fly/Assets/_Script/InputManager.cs | Fly/Assets/_Script/InputManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour {
public GameObject CameraRig;
public GameObject LeftController;
public GameObject RightController;
public Transform LLT; //LLT = LastLeftContollerTransform
public Transform LRT; //LRT = LastRightContollerTransform
public Transform CLT; //CLT = CurrentLeftControllerTransform
public Transform CRT; //CRT = CurrentRightControllerTransform
public float StandandY = 1.4f; //Where the player's arm is on Y position when they raise
public float initTimeDelay = 4f;
// Use this for initialization
void Start () {
LLT.position = Vector3.zero;
LRT.position = Vector3.zero;
}
// Update is called once per frame
void Update () {
if (Time.time > initTimeDelay) {
}
// CLT.position = LeftController.transform.position;
// CRT.position = RightController.transform.position;
//
// if ((CLT.position.y < StandandY) &(LLT.position.y > StandandY)
// &(CRT.position.y < StandandY) & (LRT.position.y > StandandY)) {
//
// CameraRig.gameObject.transform.position = new Vector3 (CameraRig.gameObject.transform.position.x,
// CameraRig.gameObject.transform.position.y + 1f,
// CameraRig.gameObject.transform.position.z);
// }
//
// LLT.position = CLT.position;
// LRT.position = CRT.position;
Debug.Log ("left:"+ LeftController.transform.position);
Debug.Log ("right:"+ RightController.transform.position);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputManager : MonoBehaviour {
public GameObject CameraRig;
public GameObject LeftController;
public GameObject RightController;
public Transform LLT; //LLT = LastLeftContollerTransform
public Transform LRT; //LRT = LastRightContollerTransform
public Transform CLT; //CLT = CurrentLeftControllerTransform
public Transform CRT; //CRT = CurrentRightControllerTransform
public float StandandY = 1.4f; //Where the player's arm is on Y position when they raise
// Use this for initialization
void Start () {
LLT.position = LeftController.transform.position;
LRT.position = RightController.transform.position;
}
// Update is called once per frame
void Update () {
CLT.position = LeftController.transform.position;
CRT.position = RightController.transform.position;
if ((CLT.position.y < StandandY) &(LLT.position.y > StandandY)
&(CRT.position.y < StandandY) & (LRT.position.y > StandandY)) {
CameraRig.gameObject.transform.position = new Vector3 (CameraRig.gameObject.transform.position.x,
CameraRig.gameObject.transform.position.y + 1f,
CameraRig.gameObject.transform.position.z);
}
LLT.position = CLT.position;
LRT.position = CRT.position;
}
}
| unlicense | C# |
468c156f636fcb9043e7574726a81674b55f879d | Initialize BoolToFontWeightConverter with TrueValue=Bold and FalseValue=Normal | thomasgalliker/ValueConverters.NET | ValueConverters.NetFx/BoolToFontWeightConverter.cs | ValueConverters.NetFx/BoolToFontWeightConverter.cs | #if (NETFX || WINDOWS_PHONE)
using System.Windows;
#elif (NETFX_CORE)
using Windows.UI.Text;
#endif
namespace ValueConverters
{
public class BoolToFontWeightConverter : BoolToValueConverter<FontWeight>
{
public BoolToFontWeightConverter()
{
this.TrueValue = FontWeights.Bold;
this.FalseValue = FontWeights.Normal;
}
}
}
| #if (NETFX || WINDOWS_PHONE)
using System.Windows;
#elif (NETFX_CORE)
using Windows.UI.Text;
#endif
namespace ValueConverters
{
public class BoolToFontWeightConverter : BoolToValueConverter<FontWeight>
{
}
}
| mit | C# |
c9c792c6eceb96abb716c2138f6389b91003b845 | Validate product features | dnauck/License.Manager,dnauck/License.Manager | src/License.Manager.Core/Validation/CreateProductValidator.cs | src/License.Manager.Core/Validation/CreateProductValidator.cs | //
// Copyright © 2012 - 2013 Nauck IT KG http://www.nauck-it.de
//
// Author:
// Daniel Nauck <d.nauck(at)nauck-it.de>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System.Collections.Generic;
using System.Linq;
using License.Manager.Core.ServiceModel;
using ServiceStack.FluentValidation;
namespace License.Manager.Core.Validation
{
public class CreateProductValidator : AbstractValidator<CreateProduct>
{
public CreateProductValidator()
{
RuleFor(p => p.Name).NotEmpty();
RuleFor(p => p.ProductFeatures).Must(BeUniqueAndNotEmpty)
.WithMessage("{PropertyName} must be unique.");
}
private static bool BeUniqueAndNotEmpty(List<string> values)
{
var allNotEmpty = values.All(x => !string.IsNullOrWhiteSpace(x));
var unique = values.Distinct().Count() == values.Count;
return allNotEmpty && unique;
}
}
} | //
// Copyright © 2012 - 2013 Nauck IT KG http://www.nauck-it.de
//
// Author:
// Daniel Nauck <d.nauck(at)nauck-it.de>
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using License.Manager.Core.ServiceModel;
using ServiceStack.FluentValidation;
namespace License.Manager.Core.Validation
{
public class CreateProductValidator : AbstractValidator<CreateProduct>
{
public CreateProductValidator()
{
RuleFor(p => p.Name).NotEmpty();
}
}
} | mit | C# |
529c8d99e10d15de1e57eb157b913a025b9ebe1c | Fix typo in CardinalityAggregationDescriptor (issue #673) | SeanKilleen/elasticsearch-net,CSGOpenSource/elasticsearch-net,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,junlapong/elasticsearch-net,abibell/elasticsearch-net,tkirill/elasticsearch-net,joehmchan/elasticsearch-net,jonyadamit/elasticsearch-net,DavidSSL/elasticsearch-net,Grastveit/NEST,CSGOpenSource/elasticsearch-net,gayancc/elasticsearch-net,ststeiger/elasticsearch-net,adam-mccoy/elasticsearch-net,starckgates/elasticsearch-net,mac2000/elasticsearch-net,robertlyson/elasticsearch-net,faisal00813/elasticsearch-net,tkirill/elasticsearch-net,CSGOpenSource/elasticsearch-net,gayancc/elasticsearch-net,SeanKilleen/elasticsearch-net,LeoYao/elasticsearch-net,junlapong/elasticsearch-net,mac2000/elasticsearch-net,starckgates/elasticsearch-net,ststeiger/elasticsearch-net,robertlyson/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,robrich/elasticsearch-net,junlapong/elasticsearch-net,DavidSSL/elasticsearch-net,KodrAus/elasticsearch-net,UdiBen/elasticsearch-net,LeoYao/elasticsearch-net,geofeedia/elasticsearch-net,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,jonyadamit/elasticsearch-net,cstlaurent/elasticsearch-net,Grastveit/NEST,cstlaurent/elasticsearch-net,tkirill/elasticsearch-net,KodrAus/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,UdiBen/elasticsearch-net,wawrzyn/elasticsearch-net,RossLieberman/NEST,jonyadamit/elasticsearch-net,robertlyson/elasticsearch-net,elastic/elasticsearch-net,robrich/elasticsearch-net,Grastveit/NEST,joehmchan/elasticsearch-net,geofeedia/elasticsearch-net,ststeiger/elasticsearch-net,TheFireCookie/elasticsearch-net,SeanKilleen/elasticsearch-net,azubanov/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,abibell/elasticsearch-net,adam-mccoy/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,faisal00813/elasticsearch-net,abibell/elasticsearch-net,DavidSSL/elasticsearch-net,TheFireCookie/elasticsearch-net,starckgates/elasticsearch-net,amyzheng424/elasticsearch-net,amyzheng424/elasticsearch-net,gayancc/elasticsearch-net,cstlaurent/elasticsearch-net,KodrAus/elasticsearch-net,LeoYao/elasticsearch-net,geofeedia/elasticsearch-net | src/Nest/DSL/Aggregations/CardinalityAggregationDescriptor.cs | src/Nest/DSL/Aggregations/CardinalityAggregationDescriptor.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Configuration;
using System.Text;
using Nest.Resolvers;
using Newtonsoft.Json;
namespace Nest
{
public class CardinalityAggregationDescriptor<T> : MetricAggregationBaseDescriptor<CardinalityAggregationDescriptor<T>, T>
where T : class
{
[JsonProperty("precision_threshold")]
internal int? _PrecisionThreshold { get; set; }
public CardinalityAggregationDescriptor<T> PrecisionThreshold(int precisionThreshold)
{
this._PrecisionThreshold = precisionThreshold;
return this;
}
[JsonProperty("rehash")]
internal bool? _Rehash { get; set; }
public CardinalityAggregationDescriptor<T> Rehash(bool rehash = true)
{
this._Rehash = rehash;
return this;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.Configuration;
using System.Text;
using Nest.Resolvers;
using Newtonsoft.Json;
namespace Nest
{
public class CardinalityAggregationDescriptor<T> : MetricAggregationBaseDescriptor<CardinalityAggregationDescriptor<T>, T>
where T : class
{
[JsonProperty("precision_treshold")]
internal int? _PrecisionTreshold { get; set; }
public CardinalityAggregationDescriptor<T> PrecisionTreshold(int precisionTreshold)
{
this._PrecisionTreshold = precisionTreshold;
return this;
}
[JsonProperty("rehash")]
internal bool? _Rehash { get; set; }
public CardinalityAggregationDescriptor<T> Rehash(bool rehash = true)
{
this._Rehash = rehash;
return this;
}
}
}
| apache-2.0 | C# |
f5bd59577c9b5842fcea2b12be80a786e4fb924f | Update package fields | 0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced | src/csharp/Intel/Generator/JavaConstants.cs | src/csharp/Intel/Generator/JavaConstants.cs | // SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors
using System.IO;
using System.Linq;
namespace Generator {
static class JavaConstants {
public const string IcedPackage = "com.github.icedland.iced.x86";
public const string CodeAssemblerPackage = IcedPackage + ".asm";
public const string BlockEncoderPackage = IcedPackage + ".enc";
public const string DecoderPackage = IcedPackage + ".dec";
public const string EncoderPackage = IcedPackage + ".enc";
public const string InstructionInfoPackage = IcedPackage + ".info";
public const string FormatterPackage = IcedPackage + ".fmt";
public const string GasFormatterPackage = FormatterPackage + ".gas";
public const string IntelFormatterPackage = FormatterPackage + ".intel";
public const string MasmFormatterPackage = FormatterPackage + ".masm";
public const string NasmFormatterPackage = FormatterPackage + ".nasm";
public const string FastFormatterPackage = FormatterPackage + ".fast";
public const string IcedInternalPackage = IcedPackage + ".internal";
public const string CodeAssemblerInternalPackage = IcedInternalPackage + ".asm";
public const string BlockEncoderInternalPackage = IcedInternalPackage + ".enc";
public const string DecoderInternalPackage = IcedInternalPackage + ".dec";
public const string EncoderInternalPackage = IcedInternalPackage + ".enc";
public const string InstructionInfoInternalPackage = IcedInternalPackage + ".info";
public const string FormatterInternalPackage = IcedInternalPackage + ".fmt";
public const string GasFormatterInternalPackage = FormatterInternalPackage+ ".gas";
public const string IntelFormatterInternalPackage = FormatterInternalPackage + ".intel";
public const string MasmFormatterInternalPackage = FormatterInternalPackage + ".masm";
public const string NasmFormatterInternalPackage = FormatterInternalPackage + ".nasm";
public const string FastFormatterInternalPackage = FormatterInternalPackage + ".fast";
public static string GetFilename(GenTypes genTypes, string package, params string[] names) =>
Path.Combine(new[] { genTypes.Dirs.JavaDir, "src", "main", "java" }.Concat(package.Split('.')).Concat(names).ToArray());
public static string GetTestFilename(GenTypes genTypes, string package, params string[] names) =>
Path.Combine(new[] { genTypes.Dirs.JavaDir, "src", "test", "java" }.Concat(package.Split('.')).Concat(names).ToArray());
}
}
| // SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors
using System.IO;
using System.Linq;
namespace Generator {
static class JavaConstants {
public const string IcedPackage = "com.github.icedland.iced.x86";
public const string CodeAssemblerPackage = IcedPackage + ".asm";
public const string BlockEncoderPackage = IcedPackage + ".enc";
public const string DecoderPackage = IcedPackage + ".dec";
public const string EncoderPackage = IcedPackage + ".enc";
public const string InstructionInfoPackage = IcedPackage + ".info";
public const string FormatterPackage = IcedPackage + ".fmt";
public const string GasFormatterPackage = IcedPackage + ".fmt.gas";
public const string IntelFormatterPackage = IcedPackage + ".fmt.intel";
public const string MasmFormatterPackage = IcedPackage + ".fmt.masm";
public const string NasmFormatterPackage = IcedPackage + ".fmt.nasm";
public const string FastFormatterPackage = IcedPackage + ".fmt.fast";
public const string IcedInternalPackage = IcedPackage + ".internal";
public const string CodeAssemblerInternalPackage = IcedInternalPackage + ".asm";
public const string BlockEncoderInternalPackage = IcedInternalPackage + ".enc";
public const string DecoderInternalPackage = IcedInternalPackage + ".dec";
public const string EncoderInternalPackage = IcedInternalPackage + ".enc";
public const string InstructionInfoInternalPackage = IcedInternalPackage + ".info";
public const string FormatterInternalPackage = IcedInternalPackage + ".fmt";
public const string GasFormatterInternalPackage = IcedInternalPackage + ".fmt.gas";
public const string IntelFormatterInternalPackage = IcedInternalPackage + ".fmt.intel";
public const string MasmFormatterInternalPackage = IcedInternalPackage + ".fmt.masm";
public const string NasmFormatterInternalPackage = IcedInternalPackage + ".fmt.nasm";
public const string FastFormatterInternalPackage = IcedInternalPackage + ".fmt.fast";
public static string GetFilename(GenTypes genTypes, string package, params string[] names) =>
Path.Combine(new[] { genTypes.Dirs.JavaDir, "src", "main", "java" }.Concat(package.Split('.')).Concat(names).ToArray());
public static string GetTestFilename(GenTypes genTypes, string package, params string[] names) =>
Path.Combine(new[] { genTypes.Dirs.JavaDir, "src", "test", "java" }.Concat(package.Split('.')).Concat(names).ToArray());
}
}
| mit | C# |
e74b7fdaf2a2887c7c69438afc7b33f6328f2fb0 | fix #47 | nerai/CMenu | src/ExampleMenu/Recording/FileRecordStore.cs | src/ExampleMenu/Recording/FileRecordStore.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ExampleMenu.Recording
{
/// <summary>
/// Stores records to files
/// </summary>
public class FileRecordStore : IRecordStore
{
public FileRecordStore ()
{
RecordDirectory = ".\\Records\\";
}
public string RecordDirectory
{
get;
set;
}
public void AddRecord (string name, IEnumerable<string> lines)
{
if (name == null) {
throw new ArgumentNullException ("name");
}
if (lines == null) {
throw new ArgumentNullException ("lines");
}
Directory.CreateDirectory (RecordDirectory);
var path = RecordDirectory + name;
File.WriteAllLines (path, lines);
}
/// <summary>
/// Retrieves the specified record.
///
/// The record chosen is the first one to match, in order, any of the following:
/// a) an exact match
/// b) a record name starting with the specified name
/// c) a record name containing the specified name
/// </summary>
public IEnumerable<string> GetRecord (string name)
{
if (name == null) {
throw new ArgumentNullException ("name");
}
var path = RecordDirectory + name;
if (!File.Exists (path)) {
var rec = GetRecordNames ().FirstOrDefault (n => n.StartsWith (name, StringComparison.InvariantCultureIgnoreCase));
rec = rec ?? GetRecordNames ().FirstOrDefault (n => n.Contains (name));
if (rec == null) {
return null;
}
path = RecordDirectory + rec;
}
var lines = File.ReadAllLines (path);
return lines;
}
public IEnumerable<string> GetRecordNames ()
{
if (!Directory.Exists (RecordDirectory)) {
return new string[0];
}
var files = Directory
.EnumerateFiles (RecordDirectory)
.Select (f => f.Substring (RecordDirectory.Length));
return files;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace ExampleMenu.Recording
{
/// <summary>
/// Stores records to files
/// </summary>
public class FileRecordStore : IRecordStore
{
public FileRecordStore ()
{
RecordDirectory = ".\\Records\\";
}
public string RecordDirectory
{
get;
set;
}
public void AddRecord (string name, IEnumerable<string> lines)
{
if (name == null) {
throw new ArgumentNullException ("name");
}
if (lines == null) {
throw new ArgumentNullException ("lines");
}
Directory.CreateDirectory (RecordDirectory);
var path = RecordDirectory + name;
File.WriteAllLines (path, lines);
}
/// <summary>
/// Retrieves the specified record.
///
/// The record chosen is the first one to match, in order, any of the following:
/// a) an exact match
/// b) a record name starting with the specified name
/// c) a record name containing the specified name
/// </summary>
public IEnumerable<string> GetRecord (string name)
{
if (name == null) {
throw new ArgumentNullException ("name");
}
var path = RecordDirectory + name;
if (!File.Exists (path)) {
name = GetRecordNames ().FirstOrDefault (n => n.StartsWith (name, StringComparison.InvariantCultureIgnoreCase));
name = name ?? GetRecordNames ().FirstOrDefault (n => n.Contains (name));
if (name == null) {
return null;
}
path = RecordDirectory + name;
}
var lines = File.ReadAllLines (path);
return lines;
}
public IEnumerable<string> GetRecordNames ()
{
if (!Directory.Exists (RecordDirectory)) {
return new string[0];
}
var files = Directory
.EnumerateFiles (RecordDirectory)
.Select (f => f.Substring (RecordDirectory.Length));
return files;
}
}
}
| mit | C# |
6edc4b1ff05f604bf000374541ed6da07236638b | bump assembly version | cgerrior/recurly-client-net,jvalladolid/recurly-client-net | Library/Properties/AssemblyInfo.cs | Library/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("Recurly Client Library")]
[assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recurly, Inc.")]
[assembly: AssemblyProduct("Recurly")]
[assembly: AssemblyCopyright("")]
[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("25932cc0-45c7-4db4-b8d5-dd172555522c")]
// 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.3")]
[assembly: AssemblyFileVersion("1.0.0.3")]
| 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("Recurly Client Library")]
[assembly: AssemblyDescription("Recurly makes subscription billing easy for .NET developers.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Recurly, Inc.")]
[assembly: AssemblyProduct("Recurly")]
[assembly: AssemblyCopyright("")]
[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("25932cc0-45c7-4db4-b8d5-dd172555522c")]
// 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.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
| mit | C# |
d8559f1ad7670279438d12daabd8eefffee55fdd | Change the port to 8000 so we can run as non-admin. | Code-Sharp/uHttpSharp,habibmasuro/uhttpsharp,int6/uhttpsharp,raistlinthewiz/uhttpsharp,lstefano71/uhttpsharp,lstefano71/uhttpsharp,raistlinthewiz/uhttpsharp,int6/uhttpsharp,habibmasuro/uhttpsharp,Code-Sharp/uHttpSharp | uhttpsharp-demo/Program.cs | uhttpsharp-demo/Program.cs | /*
* Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library 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
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using uhttpsharp.Embedded;
namespace uhttpsharpdemo
{
class Program
{
static void Main(string[] args)
{
HttpServer.Instance.Port = 8000;
HttpServer.Instance.StartUp();
Console.ReadLine();
}
}
}
| /*
* Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library 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
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using uhttpsharp.Embedded;
namespace uhttpsharpdemo
{
class Program
{
static void Main(string[] args)
{
HttpServer.Instance.StartUp();
Console.ReadLine();
}
}
}
| lgpl-2.1 | C# |
5c671627fe12265929a12c6076c9e17f0bd1617e | make the track id part of the route | odedw/game-of-music,odedw/game-of-music | GameOfMusicV2/App_Start/RouteConfig.cs | GameOfMusicV2/App_Start/RouteConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace GameOfMusicV2
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Main",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace GameOfMusicV2
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| mit | C# |
dfcb60eb341b8a3122445415da84855efee87e5b | Use procedural instead of event-driven approach | treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk | NET/Demos/Console/Blink/Program.cs | NET/Demos/Console/Blink/Program.cs | using System;
using Treehopper;
using System.Threading.Tasks;
using Treehopper.Desktop;
using System.Windows.Threading;
namespace Blink
{
/// <summary>
/// This demo blinks the built-in LED using async programming.
/// </summary>
class Program
{
static TreehopperUsb Board;
//[MTAThread]
static void Main(string[] args)
{
// We can't do async calls from the Console's Main() function, so we run all our code in a separate async method.
Task.Run(RunBlink).Wait();
}
static async Task RunBlink()
{
while (true)
{
Console.Write("Waiting for board...");
// Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected.
Board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Found board: " + Board);
Console.WriteLine("Version: " + Board.Version);
// You must explicitly connect to a board before communicating with it
await Board.ConnectAsync();
Console.WriteLine("Start blinking. Press any key to stop.");
while (Board.IsConnected && !Console.KeyAvailable)
{
// toggle the LED.
Board.Led = !Board.Led;
await Task.Delay(100);
}
Console.ReadKey();
Board.Disconnect();
}
}
}
}
| using System;
using Treehopper;
using System.Threading.Tasks;
using Treehopper.Desktop;
using System.Windows.Threading;
namespace Blink
{
/// <summary>
/// This demo blinks the built-in LED using async programming.
/// </summary>
class Program
{
static TreehopperUsb Board;
//[MTAThread]
static void Main(string[] args)
{
// We can't do async calls from the Console's Main() function, so we run all our code in a separate async method.
ConnectionService.Instance.Boards.CollectionChanged += async (o, s) =>
{
if(s.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
Board = (TreehopperUsb)s.NewItems[0];
Console.WriteLine("Found board: " + Board);
Console.WriteLine("Version: " + Board.Version);
// You must explicitly connect to a board before communicating with it
await Board.ConnectAsync();
Console.WriteLine("Start blinking. Press any key to stop.");
while (Board.IsConnected && !Console.KeyAvailable)
{
// toggle the LED.
Board.Led = !Board.Led;
await Task.Delay(100);
}
} else if(s.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove){
Console.WriteLine("Board removed");
}
};
//RunBlink().Wait();
}
static async Task RunBlink()
{
while (true)
{
Console.Write("Waiting for board...");
// Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected.
Board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Found board: " + Board);
Console.WriteLine("Version: " + Board.Version);
// You must explicitly connect to a board before communicating with it
await Board.ConnectAsync();
Console.WriteLine("Start blinking. Press any key to stop.");
while (Board.IsConnected && !Console.KeyAvailable)
{
// toggle the LED.
Board.Led = !Board.Led;
await Task.Delay(100);
}
}
}
}
}
| mit | C# |
39112b679ad584c2d3eb22161b235e7ed6f5fc68 | Fix StatsPublisher error on silo shutdown | yevhen/OrleansDashboard,OrleansContrib/OrleansDashboard,yevhen/OrleansDashboard,OrleansContrib/OrleansDashboard,OrleansContrib/OrleansDashboard,yevhen/OrleansDashboard | OrleansDashboard/StatsPublisher.cs | OrleansDashboard/StatsPublisher.cs | using Orleans;
using Orleans.Providers;
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace OrleansDashboard
{
public class StatCounter
{
public string Name { get; set; }
public string Value { get; set; }
public string Delta { get; set; }
}
public class StatsPublisher : IConfigurableStatisticsPublisher, IStatisticsPublisher, IProvider, ISiloMetricsDataPublisher
{
public string Name { get; private set; }
public IProviderRuntime ProviderRuntime { get; private set; }
public Task Close()
{
return TaskDone.Done;
}
public async Task ReportStats(List<ICounter> statsCounters)
{
var grain = this.ProviderRuntime.GrainFactory.GetGrain<ISiloGrain>(this.ProviderRuntime.ToSiloAddress());
var values = statsCounters.Select(x => new StatCounter { Name = x.Name, Value = x.GetValueString(), Delta = x.IsValueDelta ? x.GetDeltaString() : null}).OrderBy(x => x.Name).ToArray();
await Dispatch(async () => {
await grain.ReportCounters(values);
});
}
public void AddConfiguration(string deploymentId, bool isSilo, string siloName, SiloAddress address, IPEndPoint gateway, string hostName)
{ }
public Task Init(bool isSilo, string storageConnectionString, string deploymentId, string address, string siloName, string hostName)
{
throw new NotImplementedException();
}
public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
this.Name = name;
this.ProviderRuntime = providerRuntime;
return TaskDone.Done;
}
public Task Init(string deploymentId, string storageConnectionString, SiloAddress siloAddress, string siloName, IPEndPoint gateway, string hostName)
{
throw new NotImplementedException();
}
public Task ReportMetrics(ISiloPerformanceMetrics metricsData)
{
return TaskDone.Done;
}
Task Dispatch(Func<Task> func)
{
var scheduler = Dashboard.OrleansScheduler;
return scheduler == null
? TaskDone.Done
: Task.Factory.StartNew(func, CancellationToken.None, TaskCreationOptions.None, scheduler);
}
}
}
| using Orleans;
using Orleans.Providers;
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace OrleansDashboard
{
public class StatCounter
{
public string Name { get; set; }
public string Value { get; set; }
public string Delta { get; set; }
}
public class StatsPublisher : IConfigurableStatisticsPublisher, IStatisticsPublisher, IProvider, ISiloMetricsDataPublisher
{
public string Name { get; private set; }
public IProviderRuntime ProviderRuntime { get; private set; }
public Task Close()
{
return TaskDone.Done;
}
public async Task ReportStats(List<ICounter> statsCounters)
{
var grain = this.ProviderRuntime.GrainFactory.GetGrain<ISiloGrain>(this.ProviderRuntime.ToSiloAddress());
var values = statsCounters.Select(x => new StatCounter { Name = x.Name, Value = x.GetValueString(), Delta = x.IsValueDelta ? x.GetDeltaString() : null}).OrderBy(x => x.Name).ToArray();
await Dispatch(async () => {
await grain.ReportCounters(values);
});
}
public void AddConfiguration(string deploymentId, bool isSilo, string siloName, SiloAddress address, IPEndPoint gateway, string hostName)
{ }
public Task Init(bool isSilo, string storageConnectionString, string deploymentId, string address, string siloName, string hostName)
{
throw new NotImplementedException();
}
public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
{
this.Name = name;
this.ProviderRuntime = providerRuntime;
return TaskDone.Done;
}
public Task Init(string deploymentId, string storageConnectionString, SiloAddress siloAddress, string siloName, IPEndPoint gateway, string hostName)
{
throw new NotImplementedException();
}
public Task ReportMetrics(ISiloPerformanceMetrics metricsData)
{
return TaskDone.Done;
}
Task Dispatch(Func<Task> func)
{
return Task.Factory.StartNew(func, CancellationToken.None, TaskCreationOptions.None, scheduler: Dashboard.OrleansScheduler);
}
}
}
| mit | C# |
8f1993d3c3ba6ed2cfa4b6965a917e525791d9f0 | Fix a bug in RelabelingFunction | lou1306/CIV,lou1306/CIV | CIV.Ccs/Helpers/RelabelingFunction.cs | CIV.Ccs/Helpers/RelabelingFunction.cs | using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace CIV.Ccs
{
public class RelabelingFunction : ICollection<KeyValuePair<string, string>>, IEquatable<RelabelingFunction>
{
readonly IDictionary<string, string> dict = new SortedDictionary<string, string>();
public int Count => dict.Count;
public bool IsReadOnly => dict.IsReadOnly;
/// <summary>
/// Allows square-bracket indexing, i.e. relabeling[key].
/// </summary>
/// <param name="key">The key to access or set.</param>
public string this[string key] => dict[key];
internal bool ContainsKey(string label) => dict.ContainsKey(label);
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
=> dict.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => dict.GetEnumerator();
public void Add(string action, string relabeled)
{
if (action == Const.tau)
{
throw new ArgumentException("Cannot relabel tau");
}
dict.Add(action, relabeled);
// f('a) = 'f(a)
dict.Add(action.Coaction(), relabeled.Coaction());
}
public void Add(KeyValuePair<string, string> item) => Add(item.Key, item.Value);
public void Clear() => dict.Clear();
public bool Contains(KeyValuePair<string, string> item) => dict.Contains(item);
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
=> dict.CopyTo(array, arrayIndex);
public bool Remove(KeyValuePair<string, string> item) => dict.Remove(item);
public bool Equals(RelabelingFunction other)
{
// https://stackoverflow.com/questions/3804367/
// We can use this solution because dict is a value-type dictionary,
// i.e. <string, string>
return dict.Count == other.dict.Count
&& !dict.Except(other.dict).Any();
}
public override string ToString()
{
var relabels = dict
.Select(x => $"{x.Value}{Const.relab}{x.Key}")
.ToList();
return String.Join(",", relabels);
}
}
}
| using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
namespace CIV.Ccs
{
public class RelabelingFunction : ICollection<KeyValuePair<string, string>>, IEquatable<RelabelingFunction>
{
readonly IDictionary<string, string> dict = new SortedDictionary<string, string>();
public int Count => dict.Count;
public bool IsReadOnly => dict.IsReadOnly;
/// <summary>
/// Allows square-bracket indexing, i.e. relabeling[key].
/// </summary>
/// <param name="key">The key to access or set.</param>
public string this[string key] => dict[key];
internal bool ContainsKey(string label) => dict.ContainsKey(label);
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
=> dict.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => dict.GetEnumerator();
public void Add(string action, string relabeled)
{
if (action == Const.tau)
{
throw new ArgumentException("Cannot relabel tau");
}
if (action.IsOutput())
{
action = action.Coaction();
relabeled = relabeled.Coaction();
}
dict.Add(action, relabeled);
}
public void Add(KeyValuePair<string, string> item) => Add(item.Key, item.Value);
public void Clear() => dict.Clear();
public bool Contains(KeyValuePair<string, string> item) => dict.Contains(item);
public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex)
=> dict.CopyTo(array, arrayIndex);
public bool Remove(KeyValuePair<string, string> item) => dict.Remove(item);
public bool Equals(RelabelingFunction other)
{
// https://stackoverflow.com/questions/3804367/
// We can use this solution because dict is a value-type dictionary,
// i.e. <string, string>
return dict.Count == other.dict.Count
&& !dict.Except(other.dict).Any();
}
public override string ToString()
{
var relabels = dict
.Select(x => $"{x.Value}{Const.relab}{x.Key}")
.ToList();
return String.Join(",", relabels);
}
}
}
| mit | C# |
8c726af9b3128454a6d76de3816908bb57a16f3a | update version to 2.0.2.0 | unvell/ReoGrid,unvell/ReoGrid | ReoGrid/Properties/AssemblyInfo.cs | ReoGrid/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("ReoGrid")]
[assembly: AssemblyDescription(".NET Spreadsheet Control")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("unvell.com")]
[assembly: AssemblyProduct("ReoGrid")]
[assembly: AssemblyCopyright("Copyright © 2012-2016 unvell.com, All Rights Seserved.")]
[assembly: AssemblyTrademark("ReoGrid.NET")]
[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("a9997b8f-e41f-4358-98a9-876e2354c0b9")]
// 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("2.0.2.0")]
[assembly: AssemblyFileVersion("2.0.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("ReoGrid")]
[assembly: AssemblyDescription(".NET Spreadsheet Control")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("unvell.com")]
[assembly: AssemblyProduct("ReoGrid")]
[assembly: AssemblyCopyright("Copyright © 2012-2016 unvell.com, All Rights Seserved.")]
[assembly: AssemblyTrademark("ReoGrid.NET")]
[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("a9997b8f-e41f-4358-98a9-876e2354c0b9")]
// 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("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| mit | C# |
66eed75400f0fce0242cbe7e9da472735e88de6d | Update NotesRepository.cs | CarmelSoftware/MVCDataRepositoryXML | Models/NotesRepository.cs | Models/NotesRepository.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
namespace IoCDependencyInjection.Models
{
public class NotesRepository : INotesRepository
{
private List<Note> notes = new List<Note>();
private int iNumberOfEntries = 1;
private XDocument doc;
| mit | C# |
2e9a963bba44c3d42228779c47f38dc981de35d4 | Update SplitProgress.cs | wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter | SimpleWavSplitter/SplitProgress.cs | SimpleWavSplitter/SplitProgress.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.
namespace SimpleWavSplitter
{
#region References
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Threading;
using WavFile;
#endregion
#region SplitProgress
public class SplitProgress : IProgress
{
#region Properties
public ProgressBar ProgressBar { get; private set; }
public Dispatcher Dispatcher { get; private set; }
#endregion
#region Constructor
public SplitProgress(ProgressBar progressBar, Dispatcher dispatcher)
{
this.ProgressBar = progressBar;
this.Dispatcher = dispatcher;
}
#endregion
#region IProgress
public void Update(double value)
{
Dispatcher.Invoke((Action)delegate()
{
this.ProgressBar.Value = value;
});
}
#endregion
}
#endregion
}
| /*
* SimpleWavSplitter
* Copyright © Wiesław Šoltés 2010-2012. All Rights Reserved
*/
namespace SimpleWavSplitter
{
#region References
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Threading;
using WavFile;
#endregion
#region SplitProgress
public class SplitProgress : IProgress
{
#region Properties
public ProgressBar ProgressBar { get; private set; }
public Dispatcher Dispatcher { get; private set; }
#endregion
#region Constructor
public SplitProgress(ProgressBar progressBar, Dispatcher dispatcher)
{
this.ProgressBar = progressBar;
this.Dispatcher = dispatcher;
}
#endregion
#region IProgress
public void Update(double value)
{
Dispatcher.Invoke((Action)delegate()
{
this.ProgressBar.Value = value;
});
}
#endregion
}
#endregion
}
| mit | C# |
59e413e194552d03d5101c679aa18d06538b0b65 | Fix Asyinc Build | CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos | source/Cosmos.VS.DebugEngine/AD7Util.cs | source/Cosmos.VS.DebugEngine/AD7Util.cs | using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Task = System.Threading.Tasks.Task;
using VSUtilities = Cosmos.VS.DebugEngine.Utilities.VS;
namespace Cosmos.VS.DebugEngine
{
public static class AD7Util
{
public static void Log(string message, params object[] args)
{
// this method doesn't do anything normally, but keep it for debugging
// File.AppendAllText(@"c:\data\sources\ad7.log", DateTime.Now.ToString("HH:mm:ss.ffffff: ") + String.Format(message, args) + Environment.NewLine);
}
public static async Task ShowMessageAsync(string message, string title = "Cosmos Debug Engine")
{
await VSUtilities.MessageBox.ShowAsync(title, message);
}
public static void ShowMessage(string message, string title = "Cosmos Debug Engine")
{
VSUtilities.MessageBox.Show(title, message);
}
public static async Task ShowWarningAsync(string message, string title = "Cosmos Debug Engine")
{
await VSUtilities.MessageBox.ShowWarningAsync(title, message);
}
public static void ShowWarning(string message, string title = "Cosmos Debug Engine")
{
VSUtilities.MessageBox.ShowWarning(title, message);
}
public static async Task ShowErrorAsync(string message, string title = "Cosmos Debug Engine")
{
await VSUtilities.MessageBox.ShowErrorAsync(title, message);
}
public static void ShowError(string message, string title = "Cosmos Debug Engine")
{
VSUtilities.MessageBox.ShowError(title, message);
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using VSUtilities = Cosmos.VS.DebugEngine.Utilities.VS;
namespace Cosmos.VS.DebugEngine
{
public static class AD7Util
{
public static void Log(string message, params object[] args)
{
// this method doesn't do anything normally, but keep it for debugging
// File.AppendAllText(@"c:\data\sources\ad7.log", DateTime.Now.ToString("HH:mm:ss.ffffff: ") + String.Format(message, args) + Environment.NewLine);
}
public static async Task ShowMessageAsync(string message, string title = "Cosmos Debug Engine")
{
await VSUtilities.MessageBox.ShowAsync(title, message);
}
public static void ShowMessage(string message, string title = "Cosmos Debug Engine")
{
VSUtilities.MessageBox.Show(title, message);
}
public static async Task ShowWarningAsync(string message, string title = "Cosmos Debug Engine")
{
await VSUtilities.MessageBox.ShowWarningAsync(title, message);
}
public static void ShowWarning(string message, string title = "Cosmos Debug Engine")
{
VSUtilities.MessageBox.ShowWarning(title, message);
}
public static async Task ShowErrorAsync(string message, string title = "Cosmos Debug Engine")
{
await VSUtilities.MessageBox.ShowErrorAsync(title, message);
}
public static void ShowError(string message, string title = "Cosmos Debug Engine")
{
VSUtilities.MessageBox.ShowError(title, message);
}
}
}
| bsd-3-clause | C# |
2475dcf9d92cd4793f102b353d53ccb408862f07 | add todo | IdentityModel/IdentityModel2,IdentityModel/IdentityModel,IdentityModel/IdentityModel2,IdentityModel/IdentityModelv2,IdentityModel/IdentityModel,IdentityModel/IdentityModelv2 | src/IdentityModel/Client/DiscoveryPolicy.cs | src/IdentityModel/Client/DiscoveryPolicy.cs | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityModel.Client
{
public class DiscoveryPolicy
{
internal string Authority;
public bool ValidateIssuerName { get; set; } = true;
public bool ValidateEndpoints { get; set; } = true;
public bool RequireHttps { get; set; } = true;
// todo: implement
public bool AllowHttpOnLoopback { get; set; } = true;
}
} | // Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace IdentityModel.Client
{
public class DiscoveryPolicy
{
internal string Authority;
public bool ValidateIssuerName { get; set; } = true;
public bool ValidateEndpoints { get; set; } = true;
public bool RequireHttps { get; set; } = true;
}
} | apache-2.0 | C# |
3291163bdd2153c66ec1c7bbd0c9b0f1fbe1e459 | Update ShellAttributeBase.cs | tiksn/TIKSN-Framework | TIKSN.Core/Shell/ShellAttributeBase.cs | TIKSN.Core/Shell/ShellAttributeBase.cs | using System;
using Microsoft.Extensions.Localization;
using TIKSN.Localization;
namespace TIKSN.Shell
{
public abstract class ShellAttributeBase : Attribute
{
private readonly int? _integerNameKey;
private readonly string _stringNameKey;
protected ShellAttributeBase(int nameKey) => this._integerNameKey = nameKey;
protected ShellAttributeBase(string nameKey) => this._stringNameKey = nameKey;
public string GetName(IStringLocalizer stringLocalizer)
{
if (this._integerNameKey.HasValue)
{
return stringLocalizer.GetRequiredString(this._integerNameKey.Value);
}
if (Guid.TryParse(this._stringNameKey, out var key))
{
return stringLocalizer.GetRequiredString(key);
}
return stringLocalizer.GetRequiredString(this._stringNameKey);
}
}
}
| using Microsoft.Extensions.Localization;
using System;
using TIKSN.Localization;
namespace TIKSN.Shell
{
public abstract class ShellAttributeBase : Attribute
{
private readonly int? _integerNameKey;
private readonly string _stringNameKey;
protected ShellAttributeBase(int nameKey)
{
_integerNameKey = nameKey;
}
protected ShellAttributeBase(string nameKey)
{
_stringNameKey = nameKey;
}
public string GetName(IStringLocalizer stringLocalizer)
{
if (_integerNameKey.HasValue)
return stringLocalizer.GetRequiredString(_integerNameKey.Value);
else if (Guid.TryParse(_stringNameKey, out Guid key))
return stringLocalizer.GetRequiredString(key);
else
return stringLocalizer.GetRequiredString(_stringNameKey);
}
}
} | mit | C# |
3fe60f3358078741a6801de4dcd8c8bbd0f5c5c5 | Bump version | rabbit-link/rabbit-link,rabbit-link/rabbit-link | src/RabbitLink/Properties/AssemblyInfo.cs | src/RabbitLink/Properties/AssemblyInfo.cs | #region Usings
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("RabbitLink")]
[assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RabbitLink")]
[assembly: AssemblyCopyright("Copyright © Artur Kraev 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("b2148830-a507-44a5-bc99-efda7f36e21d")]
// 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.2.5.0")]
[assembly: AssemblyFileVersion("0.2.5.0")] | #region Usings
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("RabbitLink")]
[assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RabbitLink")]
[assembly: AssemblyCopyright("Copyright © Artur Kraev 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("b2148830-a507-44a5-bc99-efda7f36e21d")]
// 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.2.4.0")]
[assembly: AssemblyFileVersion("0.2.4.0")] | mit | C# |
427618412526ab11b36f117489854a2d2565dc3f | Fix missing 'async' suffix for function | timeanddate/libtad-net | TimeAndDate.Services/AccountService.cs | TimeAndDate.Services/AccountService.cs | using System;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Net;
using TimeAndDate.Services.Common;
using System.Collections.Generic;
using System.Xml;
using TimeAndDate.Services.DataTypes.Account;
namespace TimeAndDate.Services
{
public class AccountService : BaseService
{
/// <summary>
/// The accounts service can be used to retrieve information about the
/// API account in use, remaining request credits and current packages.
/// </summary>
/// <param name='accessKey'>
/// Access key.
/// </param>
/// <param name='secretKey'>
/// Secret key.
/// </param>
public AccountService (string accessKey, string secretKey) : base(accessKey, secretKey, "account")
{
XmlElemName = "account";
}
/// <summary>
/// Gets information about account in use.
/// </summary>
/// <returns>
/// The account.
/// </returns>
public Account GetAccount ()
{
return CallService<Account> (new NameValueCollection ());
}
/// <summary>
/// Gets information about account in use.
/// </summary>
/// <returns>
/// The account.
/// </returns>
public async Task<Account> GetAccountAsync ()
{
return CallServiceAsync<Account> (new NameValueCollection ());
}
protected override Account FromString<Account> (string result)
{
var xml = new XmlDocument();
xml.LoadXml (result);
var node = xml.SelectSingleNode ("data");
node = node.SelectSingleNode ("account");
var instance = Activator.CreateInstance(typeof(Account), new object[] { node });
return (Account) instance;
}
}
}
| using System;
using System.Threading.Tasks;
using System.Collections.Specialized;
using System.Net;
using TimeAndDate.Services.Common;
using System.Collections.Generic;
using System.Xml;
using TimeAndDate.Services.DataTypes.Account;
namespace TimeAndDate.Services
{
public class AccountService : BaseService
{
/// <summary>
/// The accounts service can be used to retrieve information about the
/// API account in use, remaining request credits and current packages.
/// </summary>
/// <param name='accessKey'>
/// Access key.
/// </param>
/// <param name='secretKey'>
/// Secret key.
/// </param>
public AccountService (string accessKey, string secretKey) : base(accessKey, secretKey, "account")
{
XmlElemName = "account";
}
/// <summary>
/// Gets information about account in use.
/// </summary>
/// <returns>
/// The account.
/// </returns>
public Account GetAccount ()
{
return CallService<Account> (new NameValueCollection ());
}
/// <summary>
/// Gets information about account in use.
/// </summary>
/// <returns>
/// The account.
/// </returns>
public async Task<Account> GetAccount ()
{
return CallServiceAsync<Account> (new NameValueCollection ());
}
protected override Account FromString<Account> (string result)
{
var xml = new XmlDocument();
xml.LoadXml (result);
var node = xml.SelectSingleNode ("data");
node = node.SelectSingleNode ("account");
var instance = Activator.CreateInstance(typeof(Account), new object[] { node });
return (Account) instance;
}
}
}
| mit | C# |
2e691d5294ea8ba525a22ce35a68bbc5c9b37248 | Make LogoutCommand implement ICommand | appharbor/appharbor-cli | src/AppHarbor/Commands/LogoutCommand.cs | src/AppHarbor/Commands/LogoutCommand.cs | using System;
namespace AppHarbor.Commands
{
public class LogoutCommand : ICommand
{
public void Execute(string[] arguments)
{
throw new NotImplementedException();
}
}
}
| namespace AppHarbor.Commands
{
public class LogoutCommand
{
}
}
| mit | C# |
2ac592569ff305eb3dc4d47b2c913a00dcb39383 | fix bug with default sorting | mdavid626/artemis | src/Artemis.Data/CarAdvertRepository.cs | src/Artemis.Data/CarAdvertRepository.cs | using Artemis.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic;
using System.Reflection;
namespace Artemis.Data
{
public class CarAdvertRepository : ICarAdvertRepository, IDisposable
{
private CarAdvertDbContext dbContext;
public CarAdvertRepository(ICarAdvertDbContextProvider dbContextProvider)
{
this.dbContext = dbContextProvider.Provide();
}
public CarAdvert Get(int id)
{
return dbContext.CarAdverts.FirstOrDefault(c => c.Id == id);
}
public IEnumerable<CarAdvert> Get(string orderBy = null, string direction = null)
{
var ordering = GetOrdering(orderBy, direction);
return dbContext.CarAdverts.OrderBy(ordering);
}
public void Update(CarAdvert carAdvert)
{
dbContext.SaveChanges();
}
public void Create(CarAdvert carAdvert)
{
dbContext.CarAdverts.Add(carAdvert);
dbContext.SaveChanges();
}
public void Delete(CarAdvert carAdvert)
{
dbContext.CarAdverts.Remove(carAdvert);
dbContext.SaveChanges();
}
public void Dispose()
{
dbContext.Dispose();
}
private string GetOrdering(string orderBy, string direction)
{
var ascending = true;
if (direction?.ToLower() == "desc")
ascending = false;
var directionText = ascending
? " asc"
: " desc";
var allowedProps = typeof(CarAdvert)
.GetProperties()
.Where(p => p.GetCustomAttribute<SortableAttribute>() != null)
.Select(p => p.Name.ToLower());
var prop = allowedProps.Intersect(new string[] { orderBy?.ToLower() });
if (prop.Any())
{
return orderBy + directionText;
}
return nameof(CarAdvert.Id) + directionText;
}
}
}
| using Artemis.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic;
using System.Reflection;
namespace Artemis.Data
{
public class CarAdvertRepository : ICarAdvertRepository, IDisposable
{
private CarAdvertDbContext dbContext;
public CarAdvertRepository(ICarAdvertDbContextProvider dbContextProvider)
{
this.dbContext = dbContextProvider.Provide();
}
public CarAdvert Get(int id)
{
return dbContext.CarAdverts.FirstOrDefault(c => c.Id == id);
}
public IEnumerable<CarAdvert> Get(string orderBy = null, string direction = null)
{
var ordering = GetOrdering(orderBy, direction);
return dbContext.CarAdverts.OrderBy(ordering);
}
public void Update(CarAdvert carAdvert)
{
dbContext.SaveChanges();
}
public void Create(CarAdvert carAdvert)
{
dbContext.CarAdverts.Add(carAdvert);
dbContext.SaveChanges();
}
public void Delete(CarAdvert carAdvert)
{
dbContext.CarAdverts.Remove(carAdvert);
dbContext.SaveChanges();
}
public void Dispose()
{
dbContext.Dispose();
}
private string GetOrdering(string orderBy, string direction)
{
var ascending = true;
if (direction?.ToLower() == "desc")
ascending = false;
var directionText = ascending
? " asc"
: " desc";
var allowedProps = typeof(CarAdvert)
.GetProperties()
.Where(p => p.GetCustomAttribute<SortableAttribute>() != null)
.Select(p => p.Name.ToLower());
var prop = allowedProps.Intersect(new string[] { orderBy?.ToLower() });
if (prop.Any())
{
return orderBy + directionText;
}
return nameof(CarAdvert.Id);
}
}
}
| mit | C# |
aa60c82cdb707b035bcbd1d1967dc2a8c4f7e355 | Use the default razor engine, not isolated | yetanotherchris/SignalrTypescriptGenerator | src/SignalrTypescriptGenerator/Program.cs | src/SignalrTypescriptGenerator/Program.cs | using System;
using System.IO;
using System.Reflection;
using RazorEngine;
using RazorEngine.Templating;
using SignalrTypescriptGenerator.Models;
namespace SignalrTypescriptGenerator
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("SignalrTypescriptGenerator.exe [path to assembly or exe]");
Environment.Exit(1);
}
try
{
var signalrHelper = new SignalrHubinator(args[0]);
var model = new TypesModel();
model.Hubs = signalrHelper.GetHubs();
model.ServiceContracts = signalrHelper.GetServiceContracts();
model.Clients = signalrHelper.GetClients();
model.DataContracts = signalrHelper.GetDataContracts();
model.Enums = signalrHelper.GetEnums();
string template = ReadEmbeddedFile("template.cshtml");
string result = Engine.Razor.RunCompile(template, "templateKey", null, model);
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e);
Environment.Exit(1);
}
}
static string ReadEmbeddedFile(string file)
{
string resourcePath = string.Format("{0}.{1}", typeof(Program).Namespace, file);
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
if (stream == null)
throw new InvalidOperationException(string.Format("Unable to find '{0}' as an embedded resource", resourcePath));
string textContent = "";
using (StreamReader reader = new StreamReader(stream))
{
textContent = reader.ReadToEnd();
}
return textContent;
}
}
}
| using System;
using System.IO;
using System.Reflection;
using RazorEngine;
using RazorEngine.Templating;
using SignalrTypescriptGenerator.Models;
namespace SignalrTypescriptGenerator
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("SignalrTypescriptGenerator.exe [path to assembly or exe]");
Environment.Exit(1);
}
try
{
var signalrHelper = new SignalrHubinator(args[0]);
var model = new TypesModel();
model.Hubs = signalrHelper.GetHubs();
model.ServiceContracts = signalrHelper.GetServiceContracts();
model.Clients = signalrHelper.GetClients();
model.DataContracts = signalrHelper.GetDataContracts();
model.Enums = signalrHelper.GetEnums();
string template = ReadEmbeddedFile("template.cshtml");
string result = Engine.IsolatedRazor.RunCompile(template, "templateKey", null, model);
Console.WriteLine(result);
}
catch (Exception e)
{
Console.WriteLine(e);
Environment.Exit(1);
}
}
static string ReadEmbeddedFile(string file)
{
string resourcePath = string.Format("{0}.{1}", typeof(Program).Namespace, file);
Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
if (stream == null)
throw new InvalidOperationException(string.Format("Unable to find '{0}' as an embedded resource", resourcePath));
string textContent = "";
using (StreamReader reader = new StreamReader(stream))
{
textContent = reader.ReadToEnd();
}
return textContent;
}
}
}
| mit | C# |
dd82b36e64438d8989e5ce28e25693b5c1f9b448 | Update AllanRitchie Details (#725) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/AllanRitchie.cs | src/Firehose.Web/Authors/AllanRitchie.cs | using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AllanRitchie : IAmAXamarinMVP, IAmAMicrosoftMVP, IFilterMyBlogPosts
{
public string FirstName => "Allan";
public string LastName => "Ritchie";
public string StateOrRegion => "Toronto, Canada";
public string EmailAddress => "[email protected]";
public string ShortBioOrTagLine => "OSS Maintainer of Shiny.NET - Microsoft/Xamarin MVP";
public Uri WebSite => new Uri("https://aritchie.github.io");
public string TwitterHandle => "allanritchie911";
public string GitHubHandle => "aritchie";
public string GravatarHash => "5f22bd04ca38ed4d0a5225d0825e0726";
public GeoPosition Position => new GeoPosition(43.6425701,-79.3892455);
public string FeedLanguageCode => "en";
// my feed is prebuilt by wyam and has a dedicated rss feed for xamarin content - thus all items are "good"
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://aritchie.github.io/Xamarin.rss"); } }
public bool Filter(SyndicationItem item) => true;
}
}
| using System;
using System.Collections.Generic;
using System.ServiceModel.Syndication;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AllanRitchie : IAmAXamarinMVP, IAmAMicrosoftMVP, IFilterMyBlogPosts
{
public string FirstName => "Allan";
public string LastName => "Ritchie";
public string StateOrRegion => "Toronto, Canada";
public string EmailAddress => "[email protected]";
public string ShortBioOrTagLine => "";
public Uri WebSite => new Uri("https://allancritchie.net");
public string TwitterHandle => "allanritchie911";
public string GitHubHandle => "aritchie";
public string GravatarHash => "5f22bd04ca38ed4d0a5225d0825e0726";
public GeoPosition Position => new GeoPosition(43.6425701,-79.3892455);
public string FeedLanguageCode => "en";
// my feed is prebuilt by wyam and has a dedicated rss feed for xamarin content - thus all items are "good"
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://allancritchie.net/feed.rss"); } }
public bool Filter(SyndicationItem item) => true;
}
}
| mit | C# |
4cf48c7dedcc7d0da3c8d505bb5026041601719b | Document GetOverrideTargetsResponse.OverrideTargetName | mispencer/OmniSharpServer,corngood/omnisharp-server,x335/omnisharp-server,svermeulen/omnisharp-server,syl20bnr/omnisharp-server,syl20bnr/omnisharp-server,corngood/omnisharp-server,OmniSharp/omnisharp-server,x335/omnisharp-server | OmniSharp/AutoComplete/Overrides/GetOverrideTargetsResponse.cs | OmniSharp/AutoComplete/Overrides/GetOverrideTargetsResponse.cs | using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
using OmniSharp.AutoComplete.Overrides;
namespace OmniSharp.AutoComplete.Overrides {
public class GetOverrideTargetsResponse {
public GetOverrideTargetsResponse() {}
public GetOverrideTargetsResponse
( IMember m
, CSharpTypeResolveContext resolveContext) {
if (resolveContext == null)
throw new ArgumentNullException("overrideContext");
if (m == null)
throw new ArgumentNullException("m");
var builder = new TypeSystemAstBuilder
(new CSharpResolver(resolveContext));
this.OverrideTargetName =
builder.ConvertEntity(m).GetText()
// Builder automatically adds a trailing newline
.TrimEnd(Environment.NewLine.ToCharArray());
}
/// <summary>
/// A human readable signature of the member that is to be
/// overridden.
/// </summary>
public string OverrideTargetName {get; set;}
}
}
| using System;
using System.Collections.Generic;
using ICSharpCode.NRefactory.CSharp.Refactoring;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem;
using OmniSharp.AutoComplete.Overrides;
namespace OmniSharp.AutoComplete.Overrides {
public class GetOverrideTargetsResponse {
public GetOverrideTargetsResponse() {}
public GetOverrideTargetsResponse
( IMember m
, CSharpTypeResolveContext resolveContext) {
if (resolveContext == null)
throw new ArgumentNullException("overrideContext");
if (m == null)
throw new ArgumentNullException("m");
var builder = new TypeSystemAstBuilder
(new CSharpResolver(resolveContext));
this.OverrideTargetName =
builder.ConvertEntity(m).GetText()
// Builder automatically adds a trailing newline
.TrimEnd(Environment.NewLine.ToCharArray());
}
/// <summary>
/// TODO
/// </summary>
public string OverrideTargetName {get; set;}
}
}
| mit | C# |
6dce425ef82d7151d60b413469fd7617ff00d058 | use bool[] instead of HashSet<char> to lookup specials | mvbalaw/EtlGate,mvbalaw/EtlGate,mvbalaw/EtlGate | src/EtlGate.Core/StreamTokenizer.cs | src/EtlGate.Core/StreamTokenizer.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace EtlGate.Core
{
public interface IStreamTokenizer
{
IEnumerable<Token> Tokenize(Stream stream, params char[] specials);
}
public class StreamTokenizer : IStreamTokenizer
{
public const string ErrorSpecialCharactersMustBeSpecified = "Special characters must be specified.";
public const string ErrorStreamCannotBeNull = "Stream cannot be null.";
public IEnumerable<Token> Tokenize(Stream stream, params char[] specials)
{
if (stream == null)
{
throw new ArgumentException(ErrorStreamCannotBeNull, "stream");
}
if (specials == null)
{
throw new ArgumentException(ErrorSpecialCharactersMustBeSpecified, "specials");
}
var lookup = new bool[char.MaxValue];
foreach (var ch in specials)
{
lookup[ch] = true;
}
var data = new StringBuilder();
using (var reader = new StreamReader(stream))
{
var next = new char[1];
int count;
do
{
count = reader.Read(next, 0, 1);
if (count == 0)
{
break;
}
if (!lookup[next[0]])
{
data.Append(next[0]);
continue;
}
if (data.Length > 0)
{
yield return new Token(TokenType.Data, data.ToString());
data.Length = 0;
}
yield return new Token(TokenType.Special, new String(next));
} while (count > 0);
}
if (data.Length > 0)
{
yield return new Token(TokenType.Data, data.ToString());
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace EtlGate.Core
{
public interface IStreamTokenizer
{
IEnumerable<Token> Tokenize(Stream stream, params char[] specials);
}
public class StreamTokenizer : IStreamTokenizer
{
public const string ErrorSpecialCharactersMustBeSpecified = "Special characters must be specified.";
public const string ErrorStreamCannotBeNull = "Stream cannot be null.";
public IEnumerable<Token> Tokenize(Stream stream, params char[] specials)
{
if (stream == null)
{
throw new ArgumentException(ErrorStreamCannotBeNull, "stream");
}
if (specials == null)
{
throw new ArgumentException(ErrorSpecialCharactersMustBeSpecified, "specials");
}
var specialsHash = new HashSet<char>(specials);
var data = new StringBuilder();
using (var reader = new StreamReader(stream))
{
var next = new char[1];
int count;
do
{
count = reader.Read(next, 0, 1);
if (count == 0)
{
break;
}
if (!specialsHash.Contains(next[0]))
{
data.Append(next[0]);
continue;
}
if (data.Length > 0)
{
yield return new Token(TokenType.Data, data.ToString());
data.Length = 0;
}
yield return new Token(TokenType.Special, new String(next));
} while (count > 0);
}
if (data.Length > 0)
{
yield return new Token(TokenType.Data, data.ToString());
}
}
}
} | mit | C# |
558554ff9f71b7771722f9d5b1dbd9b153b28b5e | Update AaronNelson.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/AaronNelson.cs | src/Firehose.Web/Authors/AaronNelson.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AaronNelson : IAmAMicrosoftMVP, IFilterMyBlogPosts
{
public string FirstName => "Aaron";
public string LastName => "Nelson";
public string ShortBioOrTagLine => "Microsoft SQL Server (Data Platform) MVP and leader of the PowerShell Virtual Group of PASS";
public string StateOrRegion => "Georgia, USA";
public string EmailAddress => "";
public string TwitterHandle => "SQLvariant";
public string GitHubHandle => "SQLvariant";
public string GravatarHash => "2b18aa0a254cd01e09918c4b24274e21";
public GeoPosition Position => new GeoPosition(34.058389, -84.286303);
public Uri WebSite => new Uri("http://SQLvariant.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://feeds.feedburner.com/Sqlvariations"); } }
public bool Filter(SyndicationItem item)
{
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class AaronNelson : IAmAMicrosoftMVP, IFilterMyBlogPosts
{
public string FirstName => "Aaron";
public string LastName => "Nelson";
public string ShortBioOrTagLine => "Microsoft SQL Server (Data Platform) MVP and leader of the PowerShell Virtual Group of PASS";
public string StateOrRegion => "Georgia, USA";
public string EmailAddress => "";
public string TwitterHandle => "SQLvariant";
public string GitHubHandle => "SQLvariant";
public string GravatarHash => "";
public GeoPosition Position => new GeoPosition(34.058389, -84.286303);
public Uri WebSite => new Uri("http://SQLvariant.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://feeds.feedburner.com/Sqlvariations"); } }
public bool Filter(SyndicationItem item)
{
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell"));
}
}
} | mit | C# |
b422a5348e8f5d514fcea122860a6f2ce0f9b498 | Update DateContextEnum.cs | ADAPT/ADAPT | source/ADAPT/Common/DateContextEnum.cs | source/ADAPT/Common/DateContextEnum.cs | /*******************************************************************************
* Copyright (C) 2015 AgGateway and ADAPT Contributors
* Copyright (C) 2015 Deere and Company
* Copyright (C) 2019 Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* Tarak Reddy, Tim Shearouse - initial API and implementation
* Kathleen Oneal - added additional values
* R. Andres Ferreyra - added PAIL / OM-related values, and comments.
*******************************************************************************/
namespace AgGateway.ADAPT.ApplicationDataModel.Common
{
public enum DateContextEnum
{
Approval,
ProposedStart,
ProposedEnd,
CropSeason, // Interval
TimingEvent, // Interval
ActualStart,
ActualEnd,
RequestedStart,
RequestedEnd,
Expiration,
Creation,
Modification,
ValidityRange, // Interval. Used for Recommendation documents, also for specialized ISO 19156 Observations (such as forecasts)
RequestedShipping,
ActualShipping,
Calibration,
Load,
Unload,
Suspend,
Resume,
Unspecified,
Installation, // When was the device, sensor, etc. installed?
Maintenance, // When was maintenance performed on the device, sensor, etc.?
PhenomenonTime, // Important attribute of an ISO 19156 Observation
ResultTime // Interval. Important attribute of an ISO 19156 Observation
}
}
| /*******************************************************************************
* Copyright (C) 2015 AgGateway and ADAPT Contributors
* Copyright (C) 2015 Deere and Company
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* Tarak Reddy, Tim Shearouse - initial API and implementation
* Kathleen Oneal - added additional values
* R. Andres Ferreyra - added PAIL / OM-related values, and comments.
*******************************************************************************/
namespace AgGateway.ADAPT.ApplicationDataModel.Common
{
public enum DateContextEnum
{
Approval,
ProposedStart,
ProposedEnd,
CropSeason,
TimingEvent,
ActualStart,
ActualEnd,
RequestedStart,
RequestedEnd,
Expiration,
Creation,
Modification,
ValidityRange, // Used for Recommendation documents, also for specialized ISO 19156 Observations (such as forecasts)
RequestedShipping,
ActualShipping,
Calibration,
Load,
Unload,
Suspend,
Resume,
Unspecified,
Installation, // When was the device, sensor, etc. installed?
Maintenance, // When was maintenance performed on the device, sensor, etc.?
PhenomenonTime, // Important attribute of an ISO 19156 Observation
ResultTime // Important attribute od an ISO 19156 Observation
}
}
| epl-1.0 | C# |
09a6f74eedde55289a449ceab490b9ab4d96153b | Use a different check before calling SetDllDirectory. | dlemstra/Magick.NET,dlemstra/Magick.NET | src/Magick.NET/Windows/MagickNET.cs | src/Magick.NET/Windows/MagickNET.cs | // Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace ImageMagick
{
/// <summary>
/// Class that can be used to initialize Magick.NET.
/// </summary>
public static partial class MagickNET
{
/// <summary>
/// Sets the directory that contains the Native library. This currently only works on Windows.
/// </summary>
/// <param name="path">The path of the directory that contains the native library.</param>
public static void SetNativeLibraryDirectory(string path)
{
#if NETSTANDARD
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
NativeWindowsMethods.SetDllDirectory(FileHelper.GetFullPath(path));
#else
NativeWindowsMethods.SetDllDirectory(FileHelper.GetFullPath(path));
#endif
}
private static class NativeWindowsMethods
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Target = "NativeWindowsMethods", Justification = "This method should not be in the same class as the rest of the NativeMethods.")]
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string lpPathName);
}
}
} | // Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
#if WINDOWS_BUILD
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
namespace ImageMagick
{
/// <summary>
/// Class that can be used to initialize Magick.NET.
/// </summary>
public static partial class MagickNET
{
/// <summary>
/// Sets the directory that contains the Native library.
/// </summary>
/// <param name="path">The path of the directory that contains the native library.</param>
public static void SetNativeLibraryDirectory(string path) => NativeWindowsMethods.SetDllDirectory(FileHelper.GetFullPath(path));
private static class NativeWindowsMethods
{
[SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass", Target = "NativeWindowsMethods", Justification = "This method should not be in the same class as the rest of the NativeMethods.")]
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetDllDirectory(string lpPathName);
}
}
}
#endif | apache-2.0 | C# |
9995316089d8725d8f1af97726892a24c6943c2f | Update version number. | Damnae/storybrew | editor/Properties/AssemblyInfo.cs | editor/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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.71.*")]
| 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("storybrew editor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("storybrew editor")]
[assembly: AssemblyCopyright("Copyright © Damnae 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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")]
// 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.70.*")]
| mit | C# |
e9895a62dfdc8ce416ad987955909f71ddfee4b5 | remove ApplicationUserManager link from HomeController | joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | Joinrpg/Controllers/HomeController.cs | Joinrpg/Controllers/HomeController.cs | using System.Threading.Tasks;
using System.Web.Mvc;
using JoinRpg.Data.Interfaces;
using JoinRpg.WebPortal.Managers;
namespace JoinRpg.Web.Controllers
{
public class HomeController : Common.ControllerBase
{
private ProjectListManager ProjectListManager { get; }
private const int ProjectsOnHomePage = 9;
public HomeController(IUserRepository userRepository,
ProjectListManager projectListManager) : base(userRepository)
{
ProjectListManager = projectListManager;
}
public async Task<ActionResult> Index() =>
View(await ProjectListManager.LoadModel(false, ProjectsOnHomePage));
public ActionResult Terms() => View();
public ActionResult About() => View();
public ActionResult Support() => View();
public ActionResult Funding2016() => View();
public ActionResult HowToHelp() => View();
public ActionResult FromAllrpgInfo() => View();
public async Task<ActionResult> BrowseGames() => View(await ProjectListManager.LoadModel());
public async Task<ActionResult> GameArchive() =>
View("BrowseGames", await ProjectListManager.LoadModel(true));
}
}
| using System.Threading.Tasks;
using System.Web.Mvc;
using JoinRpg.Data.Interfaces;
using JoinRpg.WebPortal.Managers;
namespace JoinRpg.Web.Controllers
{
public class HomeController : Common.ControllerBase
{
private ProjectListManager ProjectListManager { get; }
private const int ProjectsOnHomePage = 9;
public HomeController(ApplicationUserManager userManager,
IUserRepository userRepository,
ProjectListManager projectListManager) : base(userRepository)
{
ProjectListManager = projectListManager;
}
public async Task<ActionResult> Index() =>
View(await ProjectListManager.LoadModel(false, ProjectsOnHomePage));
public ActionResult Terms() => View();
public ActionResult About() => View();
public ActionResult Support() => View();
public ActionResult Funding2016() => View();
public ActionResult HowToHelp() => View();
public ActionResult FromAllrpgInfo() => View();
public async Task<ActionResult> BrowseGames() => View(await ProjectListManager.LoadModel());
public async Task<ActionResult> GameArchive() =>
View("BrowseGames", await ProjectListManager.LoadModel(true));
}
}
| mit | C# |
c2ea3876c8cac87744d377846fa4f516621e2e4e | delete unused references | WorldCommerce/WorldCart,WorldCommerce/WorldCart | src/WorldCart/App_Start/BundleConfig.cs | src/WorldCart/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace WorldCart
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
}
}
} | using System.Web;
using System.Web.Optimization;
namespace WorldCart
{
public class BundleConfig
{
// For more information on Bundling, visit http://go.microsoft.com/fwlink/?LinkId=254725
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
}
}
} | mit | C# |
1063f0fb6be95821eb08494154ba8633da935811 | Format file via VisualStudio autoformat | hkcomputer/shopware-csharp-api-connector | LenzShopwareApi/ApiRequestExecutor.cs | LenzShopwareApi/ApiRequestExecutor.cs | using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lenz.ShopwareApi
{
public class ApiRequestExecutor
{
public ApiResponse<TResponse> execute<TResponse> ( IRestClient client, ApiRequest apiRequest )
{
var restRequest = new RestRequest( apiRequest.Url, apiRequest.Method );
restRequest.RequestFormat = DataFormat.Json;
if ( apiRequest.Parameters != null )
{
foreach ( KeyValuePair<string, string> parameter in apiRequest.Parameters )
{
restRequest.AddUrlSegment( parameter.Key, parameter.Value ); // replaces matching token in request.Resource
}
}
// send body if it is available
restRequest.AddParameter( "application/json; charset=utf-8", apiRequest.Body, ParameterType.RequestBody );
// execute the request
IRestResponse response = client.Execute( restRequest );
if ( response.ErrorException != null )
{
throw response.ErrorException;
}
string content = response.Content; // raw content as string
Debug.WriteLine( content );
ApiResponse<TResponse> apiResponse = convertResponseStringToObject<TResponse>( content );
return apiResponse;
}
private ApiResponse<TModel> convertResponseStringToObject<TModel> ( string responseString )
{
return JsonConvert.DeserializeObject<ApiResponse<TModel>>( responseString, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
} );
}
}
}
| using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lenz.ShopwareApi
{
public class ApiRequestExecutor
{
public ApiResponse<TResponse> execute<TResponse>(IRestClient client, ApiRequest apiRequest)
{
var restRequest = new RestRequest(apiRequest.Url, apiRequest.Method);
restRequest.RequestFormat = DataFormat.Json;
if (apiRequest.Parameters != null)
{
foreach (KeyValuePair<String, String> parameter in apiRequest.Parameters)
{
restRequest.AddUrlSegment(parameter.Key, parameter.Value); // replaces matching token in request.Resource
}
}
// send body if it is available
restRequest.AddParameter("application/json; charset=utf-8", apiRequest.Body, ParameterType.RequestBody);
// execute the request
IRestResponse response = client.Execute(restRequest);
if (response.ErrorException != null)
{
Debug.WriteLine("Api Error:");
Debug.WriteLine(response.ErrorException.Message);
}
else
{
string content = response.Content; // raw content as string
Debug.WriteLine(content);
ApiResponse<TResponse> apiResponse = this.convertResponseStringToObject<TResponse>(content);
return apiResponse;
}
return null;
}
private ApiResponse<A> convertResponseStringToObject<A>(string responseString)
{
return JsonConvert.DeserializeObject<ApiResponse<A>>(responseString, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
}
}
}
| mit | C# |
0b775f46f887d7330060e4de2d26b0e70ea7d789 | Remove unused method | AmadeusW/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,physhi/roslyn,mavasani/roslyn,tmat/roslyn,sharwell/roslyn,tmat/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,heejaechang/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,heejaechang/roslyn,gafter/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,physhi/roslyn,jmarolf/roslyn,reaction1989/roslyn,dotnet/roslyn,agocke/roslyn,mgoertz-msft/roslyn,agocke/roslyn,AmadeusW/roslyn,agocke/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,sharwell/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,physhi/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,weltkante/roslyn,tannergooding/roslyn,wvdd007/roslyn,stephentoub/roslyn,nguerrera/roslyn,diryboy/roslyn,stephentoub/roslyn,nguerrera/roslyn,wvdd007/roslyn,eriawan/roslyn,KevinRansom/roslyn,aelij/roslyn,davkean/roslyn,gafter/roslyn,weltkante/roslyn,genlu/roslyn,diryboy/roslyn,sharwell/roslyn,bartdesmet/roslyn,abock/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,genlu/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,tannergooding/roslyn,gafter/roslyn,weltkante/roslyn,aelij/roslyn,reaction1989/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,brettfo/roslyn,tmat/roslyn,aelij/roslyn,brettfo/roslyn,AlekseyTs/roslyn,brettfo/roslyn,dotnet/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,diryboy/roslyn,abock/roslyn,davkean/roslyn,abock/roslyn,panopticoncentral/roslyn | src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ParseOptionChangedEventSource.cs | src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ParseOptionChangedEventSource.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class ParseOptionChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
{
public ParseOptionChangedEventSource(ITextBuffer subjectBuffer, TaggerDelay delay)
: base(subjectBuffer, delay)
{
}
protected override void ConnectToWorkspace(Workspace workspace)
{
workspace.WorkspaceChanged += OnWorkspaceChanged;
}
protected override void DisconnectFromWorkspace(Workspace workspace)
{
workspace.WorkspaceChanged -= OnWorkspaceChanged;
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.ProjectChanged)
{
var oldProject = e.OldSolution.GetProject(e.ProjectId);
var newProject = e.NewSolution.GetProject(e.ProjectId);
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
var workspace = e.NewSolution.Workspace;
var documentIds = workspace.GetRelatedDocumentIds(SubjectBuffer.AsTextContainer());
if (documentIds.Any(d => d.ProjectId == e.ProjectId))
{
this.RaiseChanged();
}
}
}
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class ParseOptionChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
{
private readonly object _gate = new object();
public ParseOptionChangedEventSource(ITextBuffer subjectBuffer, TaggerDelay delay)
: base(subjectBuffer, delay)
{
}
protected override void ConnectToWorkspace(Workspace workspace)
{
workspace.WorkspaceChanged += OnWorkspaceChanged;
}
protected override void DisconnectFromWorkspace(Workspace workspace)
{
workspace.WorkspaceChanged -= OnWorkspaceChanged;
}
private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
{
if (e.Kind == WorkspaceChangeKind.ProjectChanged)
{
var oldProject = e.OldSolution.GetProject(e.ProjectId);
var newProject = e.NewSolution.GetProject(e.ProjectId);
if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions))
{
var workspace = e.NewSolution.Workspace;
var documentIds = workspace.GetRelatedDocumentIds(SubjectBuffer.AsTextContainer());
if (documentIds.Any(d => d.ProjectId == e.ProjectId))
{
this.RaiseChanged();
}
}
}
}
}
}
}
| mit | C# |
bb85124af670d07aac163dba8fbe2772a7067a23 | Add a column Read() method | modulexcite/dnlib,Arthur2e5/dnlib,0xd4d/dnlib,kiootic/dnlib,ZixiangBoy/dnlib,ilkerhalil/dnlib,picrap/dnlib,yck1509/dnlib,jorik041/dnlib | dot10/dotNET/ColumnInfo.cs | dot10/dotNET/ColumnInfo.cs | using System;
using System.IO;
namespace dot10.dotNET {
/// <summary>
/// Info about one column in a MD table
/// </summary>
public class ColumnInfo {
byte offset;
ColumnSize columnSize;
byte size;
string name;
/// <summary>
/// Returns the column offset within the table row
/// </summary>
public int Offset {
get { return offset; }
internal set { offset = (byte)value; }
}
/// <summary>
/// Returns the column size
/// </summary>
public int Size {
get { return size; }
internal set { size = (byte)value; }
}
/// <summary>
/// Returns the column name
/// </summary>
public string Name {
get { return name; }
}
/// <summary>
/// Returns the ColumnSize enum value
/// </summary>
public ColumnSize ColumnSize {
get { return columnSize; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">The column name</param>
/// <param name="columnSize">Column size</param>
public ColumnInfo(string name, ColumnSize columnSize) {
this.name = name;
this.columnSize = columnSize;
}
/// <summary>
/// Reads the column
/// </summary>
/// <param name="reader">A reader positioned on this column</param>
/// <returns>The column value</returns>
public uint Read(BinaryReader reader) {
switch (size) {
case 1: return reader.ReadByte();
case 2: return reader.ReadUInt16();
case 4: return reader.ReadUInt32();
default: throw new ApplicationException("Invalid column size");
}
}
/// <inheritdoc/>
public override string ToString() {
return string.Format("{0} {1} {2}", offset, size, name);
}
}
}
| namespace dot10.dotNET {
/// <summary>
/// Info about one column in a MD table
/// </summary>
public class ColumnInfo {
byte offset;
ColumnSize columnSize;
byte size;
string name;
/// <summary>
/// Returns the column offset within the table row
/// </summary>
public int Offset {
get { return offset; }
internal set { offset = (byte)value; }
}
/// <summary>
/// Returns the column size
/// </summary>
public int Size {
get { return size; }
internal set { size = (byte)value; }
}
/// <summary>
/// Returns the column name
/// </summary>
public string Name {
get { return name; }
}
/// <summary>
/// Returns the ColumnSize enum value
/// </summary>
public ColumnSize ColumnSize {
get { return columnSize; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">The column name</param>
/// <param name="columnSize">Column size</param>
public ColumnInfo(string name, ColumnSize columnSize) {
this.name = name;
this.columnSize = columnSize;
}
/// <inheritdoc/>
public override string ToString() {
return string.Format("{0} {1} {2}", offset, size, name);
}
}
}
| mit | C# |
014409e7bf7e3d9edc817a81f6db46104dfb0646 | Use IBinaryReader | picrap/dnlib,kiootic/dnlib,yck1509/dnlib,ilkerhalil/dnlib,Arthur2e5/dnlib,modulexcite/dnlib,jorik041/dnlib,0xd4d/dnlib,ZixiangBoy/dnlib | dot10/dotNET/ColumnInfo.cs | dot10/dotNET/ColumnInfo.cs | using System;
using System.IO;
using dot10.IO;
namespace dot10.dotNET {
/// <summary>
/// Info about one column in a MD table
/// </summary>
public class ColumnInfo {
byte offset;
ColumnSize columnSize;
byte size;
string name;
/// <summary>
/// Returns the column offset within the table row
/// </summary>
public int Offset {
get { return offset; }
internal set { offset = (byte)value; }
}
/// <summary>
/// Returns the column size
/// </summary>
public int Size {
get { return size; }
internal set { size = (byte)value; }
}
/// <summary>
/// Returns the column name
/// </summary>
public string Name {
get { return name; }
}
/// <summary>
/// Returns the ColumnSize enum value
/// </summary>
public ColumnSize ColumnSize {
get { return columnSize; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">The column name</param>
/// <param name="columnSize">Column size</param>
public ColumnInfo(string name, ColumnSize columnSize) {
this.name = name;
this.columnSize = columnSize;
}
/// <summary>
/// Reads the column
/// </summary>
/// <param name="reader">A reader positioned on this column</param>
/// <returns>The column value</returns>
public uint Read(IBinaryReader reader) {
switch (size) {
case 1: return reader.ReadByte();
case 2: return reader.ReadUInt16();
case 4: return reader.ReadUInt32();
default: throw new ApplicationException("Invalid column size");
}
}
/// <inheritdoc/>
public override string ToString() {
return string.Format("{0} {1} {2}", offset, size, name);
}
}
}
| using System;
using System.IO;
namespace dot10.dotNET {
/// <summary>
/// Info about one column in a MD table
/// </summary>
public class ColumnInfo {
byte offset;
ColumnSize columnSize;
byte size;
string name;
/// <summary>
/// Returns the column offset within the table row
/// </summary>
public int Offset {
get { return offset; }
internal set { offset = (byte)value; }
}
/// <summary>
/// Returns the column size
/// </summary>
public int Size {
get { return size; }
internal set { size = (byte)value; }
}
/// <summary>
/// Returns the column name
/// </summary>
public string Name {
get { return name; }
}
/// <summary>
/// Returns the ColumnSize enum value
/// </summary>
public ColumnSize ColumnSize {
get { return columnSize; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">The column name</param>
/// <param name="columnSize">Column size</param>
public ColumnInfo(string name, ColumnSize columnSize) {
this.name = name;
this.columnSize = columnSize;
}
/// <summary>
/// Reads the column
/// </summary>
/// <param name="reader">A reader positioned on this column</param>
/// <returns>The column value</returns>
public uint Read(BinaryReader reader) {
switch (size) {
case 1: return reader.ReadByte();
case 2: return reader.ReadUInt16();
case 4: return reader.ReadUInt32();
default: throw new ApplicationException("Invalid column size");
}
}
/// <inheritdoc/>
public override string ToString() {
return string.Format("{0} {1} {2}", offset, size, name);
}
}
}
| mit | C# |
b9f0cb1205f0269aac53387c44c474dab5a1d0d0 | Fix dependency of environment gap | garafu/ExcelExtension | AddIn/Command/MakeGridCommand.cs | AddIn/Command/MakeGridCommand.cs | namespace ExcelX.AddIn.Command
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExcelX.AddIn.Config;
using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
/// 「方眼紙」コマンド
/// </summary>
public class MakeGridCommand : ICommand
{
/// <summary>
/// コマンドを実行します。
/// </summary>
public void Execute()
{
// グリッドサイズはピクセル指定
var size = ConfigDocument.Current.Edit.Grid.Size;
// ワークシートを取得
var application = Globals.ThisAddIn.Application;
Excel.Workbook book = application.ActiveWorkbook;
Excel.Worksheet sheet = book.ActiveSheet;
// 環境値の取得
var cell = sheet.Range["A1"];
double x1 = 10, x2 = 20, y1, y2, a, b;
cell.ColumnWidth = x1;
y1 = cell.Width;
cell.ColumnWidth = x2;
y2 = cell.Width;
a = (y2 - y1) / (x2 - x1);
b = y2 - (y2 - y1) / (x2 - x1) * x2;
// すべてのセルサイズを同一に設定
Excel.Range all = sheet.Cells;
all.ColumnWidth = (size * 0.75 - b) / a;
all.RowHeight = size * 0.75;
}
}
}
| namespace ExcelX.AddIn.Command
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExcelX.AddIn.Config;
using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
/// 「方眼紙」コマンド
/// </summary>
public class MakeGridCommand : ICommand
{
/// <summary>
/// コマンドを実行します。
/// </summary>
public void Execute()
{
// グリッドサイズはピクセル指定
var size = ConfigDocument.Current.Edit.Grid.Size;
// ワークシートを取得
var application = Globals.ThisAddIn.Application;
Excel.Workbook book = application.ActiveWorkbook;
Excel.Worksheet sheet = book.ActiveSheet;
// すべてのセルサイズを同一に設定
Excel.Range all = sheet.Cells;
all.ColumnWidth = size * 0.118;
all.RowHeight = size * 0.75;
}
}
}
| mit | C# |
af32a0294d17926f8ad2ec6834925fe2b4815c94 | Update BankAccountServiceTest.cs | open-pay/openpay-dotnet,EzyWebwerkstaden/openpay-dotnet | OpenpayTest/BankAccountServiceTest.cs | OpenpayTest/BankAccountServiceTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Openpay;
using Openpay.Entities;
using System.Collections.Generic;
namespace OpenpayTest
{
[TestClass]
public class BankAccountServiceTest
{
private static readonly string customer_id = "adyytoegxm6boiusecxm";
[TestMethod]
public void TestAsCustomer_CreateGetDelete()
{
OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID);
BankAccount bankAccount = new BankAccount();
bankAccount.CLABE = "012298026516924616";
bankAccount.HolderName = "Testing";
BankAccount bankAccountCreated = openpayAPI.BankAccountService.Create(customer_id, bankAccount);
Assert.IsNotNull(bankAccountCreated.Id);
Assert.IsNull(bankAccountCreated.Alias);
Assert.AreEqual(bankAccount.CLABE, bankAccountCreated.CLABE);
BankAccount bankAccountGet = openpayAPI.BankAccountService.Get(customer_id, bankAccountCreated.Id);
Assert.AreEqual("012XXXXXXXXXX24616", bankAccountGet.CLABE);
List<BankAccount> accounts = openpayAPI.BankAccountService.List(customer_id);
Assert.AreEqual(1, accounts.Count);
openpayAPI.BankAccountService.Delete(customer_id, bankAccountGet.Id);
}
// [TestMethod]
public void TestAsMerchant_CreateGetDelete()
{
OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID);
string bank_account_id = "bypzo1cstk5xynsuzjxo";
BankAccount bankAccountGet = openpayAPI.BankAccountService.Get(bank_account_id);
Assert.AreEqual("012XXXXXXXXXX24616", bankAccountGet.CLABE);
openpayAPI.BankAccountService.Delete(bankAccountGet.Id);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Openpay;
using Openpay.Entities;
using System.Collections.Generic;
namespace OpenpayTest
{
[TestClass]
public class BankAccountServiceTest
{
private static readonly string customer_id = "adyytoegxm6boiusecxm";
[TestMethod]
public void TestAsCustomer_CreateGetDelete()
{
OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID);
BankAccount bankAccount = new BankAccount();
bankAccount.CLABE = "012298026516924616";
bankAccount.HolderName = "Testing";
BankAccount bankAccountCreated = openpayAPI.BankAccountService.Create(customer_id, bankAccount);
Assert.IsNotNull(bankAccountCreated.Id);
Assert.IsNull(bankAccountCreated.Alias);
Assert.AreEqual(bankAccount.CLABE, bankAccountCreated.CLABE);
BankAccount bankAccountGet = openpayAPI.BankAccountService.Get(customer_id, bankAccountCreated.Id);
Assert.AreEqual(bankAccount.CLABE, bankAccountGet.CLABE);
List<BankAccount> accounts = openpayAPI.BankAccountService.List(customer_id);
Assert.AreEqual(1, accounts.Count);
openpayAPI.BankAccountService.Delete(customer_id, bankAccountGet.Id);
}
// [TestMethod]
public void TestAsMerchant_CreateGetDelete()
{
OpenpayAPI openpayAPI = new OpenpayAPI(Constants.API_KEY, Constants.MERCHANT_ID);
string bank_account_id = "bypzo1cstk5xynsuzjxo";
BankAccount bankAccountGet = openpayAPI.BankAccountService.Get(bank_account_id);
Assert.AreEqual("012298026516924616", bankAccountGet.CLABE);
openpayAPI.BankAccountService.Delete(bankAccountGet.Id);
}
}
}
| apache-2.0 | C# |
3cb3be2b8fcd6bfd81cc28e18fe39dd3f894cc29 | check for empty | bitsummation/pickaxe,bitsummation/pickaxe | Pickaxe.Runtime/SelectDownloadPage.cs | Pickaxe.Runtime/SelectDownloadPage.cs | /* Copyright 2015 Brock Reeve
* 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 Pickaxe.Runtime.Dom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pickaxe.Runtime
{
public class SelectDownloadPage : LazyDownloadPage
{
public SelectDownloadPage(ThreadedDownloadTable parent) : base(parent)
{
}
public override bool CssWhere(ref DownloadPage page, string selector)
{
CssSelector = selector;
page = this;
return true;
}
protected override void ApplyCssSelector(IEnumerable<HtmlElement> nodes)
{
if(nodes.Count() > 0)
Inner.nodes = new DownloadedNodes(nodes.First().QuerySelectorAll(CssSelector));
}
public override void Clear()
{
Inner.Clear();
Inner = null;
}
}
}
| /* Copyright 2015 Brock Reeve
* 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 Pickaxe.Runtime.Dom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pickaxe.Runtime
{
public class SelectDownloadPage : LazyDownloadPage
{
public SelectDownloadPage(ThreadedDownloadTable parent) : base(parent)
{
}
public override bool CssWhere(ref DownloadPage page, string selector)
{
CssSelector = selector;
page = this;
return true;
}
protected override void ApplyCssSelector(IEnumerable<HtmlElement> nodes)
{
Inner.nodes = new DownloadedNodes(nodes.First().QuerySelectorAll(CssSelector));
}
public override void Clear()
{
Inner.Clear();
Inner = null;
}
}
}
| apache-2.0 | C# |
1e6428919fb41e1095e0cffb16c2883e35a9a792 | Bump the version. | darrencauthon/AutoMoq,darrencauthon/AutoMoq,darrencauthon/AutoMoq | src/AutoMoq/Properties/AssemblyInfo.cs | src/AutoMoq/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("AutoMoq")]
[assembly: AssemblyDescription("Automocker for Moq.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AutoMoq")]
[assembly: AssemblyCopyright("Copyright Darren Cauthon 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("e6f813c5-0225-4f79-824c-ac21b49decc9")]
// 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.7.0.0")]
[assembly: AssemblyFileVersion("1.7.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AutoMoq")]
[assembly: AssemblyDescription("Automocker for Moq.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DEG")]
[assembly: AssemblyProduct("AutoMoq")]
[assembly: AssemblyCopyright("Copyright Darren Cauthon 2010")]
[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("e6f813c5-0225-4f79-824c-ac21b49decc9")]
// 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.6.2.0")]
[assembly: AssemblyFileVersion("1.6.2.0")]
| mit | C# |
1a9558a28a7946a496cdf2d089f7a8cc91c29d8b | fix naming | jkoritzinsky/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex | src/Avalonia.X11/XEmbedTrayIconImpl.cs | src/Avalonia.X11/XEmbedTrayIconImpl.cs | using System;
using Avalonia.Controls.Platform;
using Avalonia.Logging;
using Avalonia.Platform;
namespace Avalonia.X11
{
internal class XEmbedTrayIconImpl
{
public XEmbedTrayIconImpl()
{
}
private bool _isCalled;
private void NotImplemented()
{
if(_isCalled) return;
Logger.TryGet(LogEventLevel.Error, LogArea.X11Platform)
?.Log(this,
"TODO: XEmbed System Tray Icons is not implemented yet. Tray icons won't be available on this system.");
_isCalled = true;
}
public void Dispose()
{
NotImplemented();
}
public void SetIcon(IWindowIconImpl? icon)
{
NotImplemented();
}
public void SetToolTipText(string? text)
{
NotImplemented();
}
public void SetIsVisible(bool visible)
{
NotImplemented();
}
public INativeMenuExporter? MenuExporter { get; }
public Action? OnClicked { get; set; }
}
}
| using System;
using Avalonia.Controls.Platform;
using Avalonia.Logging;
using Avalonia.Platform;
namespace Avalonia.X11
{
internal class XEmbedTrayIconImpl
{
public XEmbedTrayIconImpl()
{
}
private bool IsCalled;
private void NotImplemented()
{
if(IsCalled) return;
Logger.TryGet(LogEventLevel.Error, LogArea.X11Platform)
?.Log(this,
"TODO: XEmbed System Tray Icons is not implemented yet. Tray icons won't be available on this system.");
IsCalled = true;
}
public void Dispose()
{
NotImplemented();
}
public void SetIcon(IWindowIconImpl? icon)
{
NotImplemented();
}
public void SetToolTipText(string? text)
{
NotImplemented();
}
public void SetIsVisible(bool visible)
{
NotImplemented();
}
public INativeMenuExporter? MenuExporter { get; }
public Action? OnClicked { get; set; }
}
}
| mit | C# |
094dfc698fc994fa24f75e3fe272453de853b026 | Create a prefix for Git-Tfs metadata | NathanLBCooper/git-tfs,WolfVR/git-tfs,kgybels/git-tfs,modulexcite/git-tfs,irontoby/git-tfs,steveandpeggyb/Public,bleissem/git-tfs,guyboltonking/git-tfs,adbre/git-tfs,TheoAndersen/git-tfs,modulexcite/git-tfs,bleissem/git-tfs,andyrooger/git-tfs,timotei/git-tfs,kgybels/git-tfs,allansson/git-tfs,timotei/git-tfs,jeremy-sylvis-tmg/git-tfs,codemerlin/git-tfs,TheoAndersen/git-tfs,timotei/git-tfs,WolfVR/git-tfs,spraints/git-tfs,spraints/git-tfs,kgybels/git-tfs,pmiossec/git-tfs,jeremy-sylvis-tmg/git-tfs,vzabavnov/git-tfs,allansson/git-tfs,modulexcite/git-tfs,git-tfs/git-tfs,hazzik/git-tfs,codemerlin/git-tfs,guyboltonking/git-tfs,codemerlin/git-tfs,spraints/git-tfs,steveandpeggyb/Public,TheoAndersen/git-tfs,NathanLBCooper/git-tfs,TheoAndersen/git-tfs,irontoby/git-tfs,adbre/git-tfs,allansson/git-tfs,allansson/git-tfs,bleissem/git-tfs,hazzik/git-tfs,PKRoma/git-tfs,irontoby/git-tfs,jeremy-sylvis-tmg/git-tfs,NathanLBCooper/git-tfs,adbre/git-tfs,hazzik/git-tfs,guyboltonking/git-tfs,steveandpeggyb/Public,WolfVR/git-tfs,hazzik/git-tfs | GitTfs/GitTfsConstants.cs | GitTfs/GitTfsConstants.cs | using System.Text.RegularExpressions;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
public const string GitTfsPrefix = "git-tfs";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
GitTfsPrefix +
"-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
}
}
| using System.Text.RegularExpressions;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
"git-tfs-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
}
}
| apache-2.0 | C# |
81478ca03697c705f4a08b9520bccf63d8b004ab | Bump version for release | programcsharp/griddly,jehhynes/griddly,programcsharp/griddly,jehhynes/griddly,programcsharp/griddly | Build/CommonAssemblyInfo.cs | Build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Griddly")]
[assembly: AssemblyCopyright("Copyright © 2013-2018 Chris Hynes and Data Research Group")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.1.0")]
[assembly: AssemblyFileVersion("2.1.0")]
//[assembly: AssemblyInformationalVersion("2.0-alpha6")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Griddly")]
[assembly: AssemblyCopyright("Copyright © 2013-2018 Chris Hynes and Data Research Group")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("2.0.3")]
[assembly: AssemblyFileVersion("2.0.3")]
//[assembly: AssemblyInformationalVersion("2.0-alpha6")]
| mit | C# |
9d42d5f95784279c3d12b02e7e50d8437fef03de | fix movapic.com preview | azyobuzin/Mystique,fin-alice/Mystique | Casket/Resolvers/MovaPic.cs | Casket/Resolvers/MovaPic.cs | using Acuerdo.External.Uploader;
namespace Casket.Resolvers
{
public class MovaPic : IResolver
{
public bool IsResolvable(string url)
{
return url.StartsWith("http://movapic.com/pic/");
}
public string Resolve(string url)
{
if (IsResolvable(url))
{
return "http://image.movapic.com/pic/m_" + url.Substring(23) + ".jpeg";
}
else
{
return null;
}
}
}
}
| using Acuerdo.External.Uploader;
namespace Casket.Resolvers
{
public class MovaPic : IResolver
{
public bool IsResolvable(string url)
{
return url.StartsWith("http://movapic.com/pic/");
}
public string Resolve(string url)
{
if (IsResolvable(url))
{
return "http://image.movapic.com/pic/s_" + url.Substring(23);
}
else
{
return null;
}
}
}
}
| mit | C# |
bd3c037ebe868afa0d3b2d7f87f04bdaccd41c9a | build fix | beforan/illNES,beforan/illNES,beforan/illNES | src/illNES.CPU/Types/Instruction.cs | src/illNES.CPU/Types/Instruction.cs | namespace illNES.CPU.Types
{
/// <summary>
/// Data structure for a single CPU instruction
/// </summary>
internal class Instruction
{
public Instruction(Ops execCode, AddressModes mode, ushort length, int cycles)
{
ExecCode = execCode;
Mode = mode;
Length = length;
Cycles = cycles;
}
/// <summary>
/// The friendly Mnemonic for this instruction.
/// This is not unique as some Mnemonics are
/// multiple ops with different addressing modes.
/// </summary>
public string Mnemonic => ExecCode.ToString();
/// <summary>
/// Enum value for the OpCode.
/// - Allows our code to read more nicely,
/// - Provides Mnemonic automatically without magic strings
/// </summary>
public Ops ExecCode { get; private set; }
/// <summary>
/// The addressing mode of this instruction
/// </summary>
public AddressModes Mode { get; private set; }
/// <summary>
/// The byte length of this instruction in memory
/// </summary>
public ushort Length { get; private set; }
/// <summary>
/// The default number of CPU cycles this instruction expends.
/// Extra cycles may be conditionally expended.
/// </summary>
public int Cycles{ get; private set; }
}
}
| namespace illNES.CPU.Types
{
/// <summary>
/// Data structure for a single CPU instruction
/// </summary>
internal class Instruction
{
public Instruction(Ops execCode, AddressModes mode, int length, int cycles)
{
ExecCode = execCode;
Mode = mode;
Length = length;
Cycles = cycles;
}
/// <summary>
/// The friendly Mnemonic for this instruction.
/// This is not unique as some Mnemonics are
/// multiple ops with different addressing modes.
/// </summary>
public string Mnemonic => ExecCode.ToString();
/// <summary>
/// Enum value for the OpCode.
/// - Allows our code to read more nicely,
/// - Provides Mnemonic automatically without magic strings
/// </summary>
public Ops ExecCode { get; private set; }
/// <summary>
/// The addressing mode of this instruction
/// </summary>
public AddressModes Mode { get; private set; }
/// <summary>
/// The byte length of this instruction in memory
/// </summary>
public ushort Length { get; private set; }
/// <summary>
/// The default number of CPU cycles this instruction expends.
/// Extra cycles may be conditionally expended.
/// </summary>
public int Cycles{ get; private set; }
}
}
| mit | C# |
28c17c3ab1ff40009d99ad7ef897f34d09012eda | set attributes | stwalkerster/eyeinthesky,stwalkerster/eyeinthesky,stwalkerster/eyeinthesky | EyeInTheSky/StalkLogItem.cs | EyeInTheSky/StalkLogItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace EyeInTheSky
{
class StalkLogItem
{
private string stalk;
private RecentChange rc;
public StalkLogItem(string flag, RecentChange rcitem)
{
stalk = flag;
rc = rcitem;
}
public string Stalk
{
get { return stalk; }
}
public RecentChange RecentChangeItem
{
get { return rc; }
}
public XmlElement toXmlFragment(XmlDocument doc, string xmlns)
{
XmlElement esli = doc.CreateElement("log", xmlns);
esli.SetAttribute("stalkflag", this.stalk);
esli.SetAttribute("timestamp", DateTime.Now.ToString());
throw new NotImplementedException();
}
public override string ToString()
{
throw new NotImplementedException();
}
internal static StalkLogItem newFromXmlElement(XmlElement element)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace EyeInTheSky
{
class StalkLogItem
{
private string stalk;
private RecentChange rc;
public StalkLogItem(string flag, RecentChange rcitem)
{
stalk = flag;
rc = rcitem;
}
public string Stalk
{
get { return stalk; }
}
public RecentChange RecentChangeItem
{
get { return rc; }
}
public XmlElement toXmlFragment(XmlDocument doc, string xmlns)
{
XmlElement esli = doc.CreateElement("log", xmlns);
throw new NotImplementedException();
}
public override string ToString()
{
throw new NotImplementedException();
}
internal static StalkLogItem newFromXmlElement(XmlElement element)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
ec1cf8b50848ce1dfa60b163ca2f2a69eb8c2f9e | Change version to 2.3.1. | yolanother/DockPanelSuite | WinFormsUI/Properties/AssemblyInfo.cs | WinFormsUI/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")]
[assembly: AssemblyDescription(".Net Docking Library for Windows Forms")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weifen Luo")]
[assembly: AssemblyProduct("DockPanel Suite")]
[assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")]
[assembly: AssemblyVersion("2.3.1.*")]
[assembly: AssemblyFileVersion("2.3.1.0")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")] | using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
[assembly: AssemblyTitle("DockPanel Suite for .Net 2.0")]
[assembly: AssemblyDescription(".Net Docking Library for Windows Forms")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Weifen Luo")]
[assembly: AssemblyProduct("DockPanel Suite")]
[assembly: AssemblyCopyright("Copyright © Weifen Luo 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: Guid("9d690ef9-ce19-4c69-874c-e24d8eb36aff")]
[assembly: AssemblyVersion("2.3.*")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Scope = "namespace", Target = "WeifenLuo.WinFormsUI.Docking", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Weifen")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Luo")]
[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "WeifenLuo.WinFormsUI.Docking.Strings.resources", MessageId = "Dockable")] | mit | C# |
269b486db86a507c65eeb99921c824ae3d88903d | order usings in Xbehave.Test/Api.cs | xbehave/xbehave.net,adamralph/xbehave.net | tests/Xbehave.Test/Api.cs | tests/Xbehave.Test/Api.cs | namespace Xbehave.Test
{
using PublicApiGenerator;
using Xbehave;
using Xbehave.Test.Infrastructure;
using Xunit;
public class Api
{
[Fact]
public void IsUnchanged() =>
#if NETCOREAPP2_1
AssertFile.Contains(ApiGenerator.GeneratePublicApi(typeof(ScenarioAttribute).Assembly), "../../../api-netcoreapp2_1.txt");
#endif
#if NET472
AssertFile.Contains(ApiGenerator.GeneratePublicApi(typeof(ScenarioAttribute).Assembly), "../../../api-net472.txt");
#endif
}
}
| namespace Xbehave.Test
{
using Xbehave;
using PublicApiGenerator;
using Xunit;
using Xbehave.Test.Infrastructure;
public class Api
{
[Fact]
public void IsUnchanged() =>
#if NETCOREAPP2_1
AssertFile.Contains(ApiGenerator.GeneratePublicApi(typeof(ScenarioAttribute).Assembly), "../../../api-netcoreapp2_1.txt");
#endif
#if NET472
AssertFile.Contains(ApiGenerator.GeneratePublicApi(typeof(ScenarioAttribute).Assembly), "../../../api-net472.txt");
#endif
}
}
| mit | C# |
375c88a2512fa55f4ec505ce1132b613a735b224 | Add support for older versions API | mainefremov/vk,Soniclev/vk,vknet/vk,kadkin/vk,kkohno/vk,rassvet85/vk,vknet/vk | VkNet/Model/AudioAlbum.cs | VkNet/Model/AudioAlbum.cs | using VkNet.Utils;
namespace VkNet.Model
{
/// <summary>
/// Информация об аудиоальбоме.
/// </summary>
/// <remarks>
/// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>.
/// </remarks>
public class AudioAlbum
{
/// <summary>
/// Идентификатор владельца альбома.
/// </summary>
public long? OwnerId { get; set; }
/// <summary>
/// Идентификатор альбома.
/// </summary>
public long? AlbumId { get; set; }
/// <summary>
/// Название альбома.
/// </summary>
public string Title { get; set; }
#region Методы
/// <summary>
/// Разобрать из json.
/// </summary>
/// <param name="response">Ответ сервера.</param>
/// <returns></returns>
internal static AudioAlbum FromJson(VkResponse response)
{
var album = new AudioAlbum
{
OwnerId = response["owner_id"],
AlbumId = response["album_id"] ?? response["id"],
Title = response["title"]
};
return album;
}
#endregion
}
} | using VkNet.Utils;
namespace VkNet.Model
{
/// <summary>
/// Информация об аудиоальбоме.
/// </summary>
/// <remarks>
/// Страница документации ВКонтакте <see href="http://vk.com/dev/audio.getAlbums"/>.
/// </remarks>
public class AudioAlbum
{
/// <summary>
/// Идентификатор владельца альбома.
/// </summary>
public long? OwnerId { get; set; }
/// <summary>
/// Идентификатор альбома.
/// </summary>
public long? AlbumId { get; set; }
/// <summary>
/// Название альбома.
/// </summary>
public string Title { get; set; }
#region Методы
/// <summary>
/// Разобрать из json.
/// </summary>
/// <param name="response">Ответ сервера.</param>
/// <returns></returns>
internal static AudioAlbum FromJson(VkResponse response)
{
var album = new AudioAlbum
{
OwnerId = response["owner_id"],
AlbumId = response["id"],
Title = response["title"]
};
return album;
}
#endregion
}
} | mit | C# |
e77a4e30a549835d507efefe9a8c5e3f7ec7198a | Use static factory method for constructing Context class | pawotter/mastodon-api-cs | Mastodon.API/Entities/Context.cs | Mastodon.API/Entities/Context.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Mastodon.API
{
/// <summary>
/// Context.
/// https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#card
/// </summary>
public class Context
{
[JsonProperty(PropertyName = "ancestors")]
public IList<Status> Ancestors { get; set; }
[JsonProperty(PropertyName = "descendants")]
public IList<Status> Descendants { get; set; }
internal Context() { }
Context(IList<Status> ancestors, IList<Status> descendants)
{
Ancestors = ancestors;
Descendants = descendants;
}
public static Context create(IList<Status> ancestors, IList<Status> descendants)
{
return new Context(ancestors, descendants);
}
public override string ToString()
{
return string.Format("[Context: Ancestors={0}, Descendants={1}]", Ancestors, Descendants);
}
public override bool Equals(object obj)
{
var o = obj as Context;
if (o == null) return false;
return Object.SequenceEqual(Ancestors, o.Ancestors) &&
Object.SequenceEqual(Descendants, o.Descendants);
}
public override int GetHashCode()
{
return Object.GetHashCode(Ancestors, Descendants);
}
}
}
| using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Mastodon.API
{
/// <summary>
/// Context.
/// https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#card
/// </summary>
public class Context
{
[JsonProperty(PropertyName = "ancestors")]
public IList<Status> Ancestors { get; set; }
[JsonProperty(PropertyName = "descendants")]
public IList<Status> Descendants { get; set; }
public override string ToString()
{
return string.Format("[Context: Ancestors={0}, Descendants={1}]", Ancestors, Descendants);
}
public override bool Equals(object obj)
{
var o = obj as Context;
if (o == null) return false;
return Object.SequenceEqual(Ancestors, o.Ancestors) &&
Object.SequenceEqual(Descendants, o.Descendants);
}
public override int GetHashCode()
{
return Object.GetHashCode(Ancestors, Descendants);
}
}
}
| mit | C# |
20c4bc5c12b1b9325cf8f5c285812287382ce80a | Add utilities to Lives. | dirty-casuals/LD38-A-Small-World | Assets/Scripts/World/Lives.cs | Assets/Scripts/World/Lives.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class LivesEvent : UnityEvent<int> {
}
public class Lives : MonoBehaviour {
[SerializeField]
private int numberStartLives = 5;
[SerializeField]
private int playerId = 0;
public int numberLivesRemaining;
[SerializeField]
private LivesEvent onLivesChanged;
[SerializeField]
private LivesEvent onLivesEmptyEvent;
private static Dictionary<int, Lives> livesByPlayerId;
public int PlayerId {
get { return playerId; }
set { playerId = value; }
}
public int NumberStartLives {
get { return numberStartLives; }
set { numberStartLives = value; }
}
private void Awake() {
numberLivesRemaining = NumberStartLives;
}
private void RemoveLife() {
numberLivesRemaining = numberLivesRemaining - 1;
}
private bool OutOfLives() {
return numberLivesRemaining <= 0;
}
private void OnCollisionEnter( Collision other ) {
var ball = other.transform.GetComponent<Ball>();
if( !ball ) {
return;
}
RemoveLife();
if( OutOfLives() ) {
onLivesEmptyEvent.Invoke( PlayerId );
}
}
public void AddOutOfLivesListener( UnityAction<int> listener ) {
onLivesEmptyEvent.AddListener( listener );
}
public void AddLivesChangedListener( UnityAction<int> listener ) {
onLivesChanged.AddListener( listener );
}
public static Lives GetLivesForPlayer( int playerId ) {
if( livesByPlayerId == null ) {
livesByPlayerId = new Dictionary<int, Lives>();
}
Lives lives = null;
livesByPlayerId.TryGetValue( playerId, out lives );
if( !lives ) {
Lives[] allLives = FindObjectsOfType<Lives>();
foreach( Lives currentLives in allLives ) {
livesByPlayerId[currentLives.playerId] = currentLives;
if( currentLives.playerId == playerId ) {
lives = currentLives;
}
}
}
return lives;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[System.Serializable]
public class LivesEvent : UnityEvent<int> {
}
public class Lives : MonoBehaviour {
[SerializeField]
private int numberStartLives = 5;
[SerializeField]
private int playerId = 0;
public int numberLivesRemaining;
[SerializeField]
private LivesEvent onLivesChanged;
[SerializeField]
private LivesEvent onLivesEmptyEvent;
private void Awake() {
numberLivesRemaining = numberStartLives;
}
private void RemoveLife() {
numberLivesRemaining = numberLivesRemaining - 1;
}
private bool OutOfLives() {
return numberLivesRemaining <= 0;
}
private void OnCollisionEnter( Collision other ) {
var ball = other.transform.GetComponent<Ball>();
if( !ball ) {
return;
}
RemoveLife();
if( OutOfLives() ) {
onLivesEmptyEvent.Invoke( playerId );
}
}
public void AddOutOfLivesListener( UnityAction<int> listener ) {
onLivesEmptyEvent.AddListener( listener );
}
public void AddLivesChangedListener( UnityAction<int> listener ) {
onLivesChanged.AddListener( listener );
}
}
| mit | C# |
5f949efb562040b2c9309effaa7dd681f441418b | Make stash provide strictly | Miruken-DotNet/Miruken | Source/Miruken/Api/Stash.cs | Source/Miruken/Api/Stash.cs | namespace Miruken.Api
{
using System;
using System.Collections.Generic;
using Callback;
[Unmanaged]
public class Stash : Handler
{
private readonly bool _root;
private readonly Dictionary<Type, object> _data;
public Stash(bool root = false)
{
_root = root;
_data = new Dictionary<Type, object>();
}
[Provides(Strict = true)]
public T Provides<T>() where T : class
{
return _data.TryGetValue(typeof(T), out var data)
? (T)data : null;
}
[Provides]
public StashOf<T> Wraps<T>(IHandler composer) where T : class
{
return new StashOf<T>(composer);
}
[Handles]
public object Get(StashAction.Get get)
{
if (_data.TryGetValue(get.Type, out var data))
{
get.Value = data;
return true;
}
return _root ? (object)true : null;
}
[Handles]
public void Put(StashAction.Put put)
{
_data[put.Type] = put.Value;
}
[Handles]
public void Drop(StashAction.Drop drop)
{
_data.Remove(drop.Type);
}
}
}
| namespace Miruken.Api
{
using System;
using System.Collections.Generic;
using Callback;
[Unmanaged]
public class Stash : Handler
{
private readonly bool _root;
private readonly Dictionary<Type, object> _data;
public Stash(bool root = false)
{
_root = root;
_data = new Dictionary<Type, object>();
}
[Provides]
public T Provides<T>() where T : class
{
return _data.TryGetValue(typeof(T), out var data)
? (T)data : null;
}
[Provides]
public StashOf<T> Wraps<T>(IHandler composer) where T : class
{
return new StashOf<T>(composer);
}
[Handles]
public object Get(StashAction.Get get)
{
if (_data.TryGetValue(get.Type, out var data))
{
get.Value = data;
return true;
}
return _root ? (object)true : null;
}
[Handles]
public void Put(StashAction.Put put)
{
_data[put.Type] = put.Value;
}
[Handles]
public void Drop(StashAction.Drop drop)
{
_data.Remove(drop.Type);
}
}
}
| mit | C# |
d3fa4040c442d2dfd0f6ac8e79f2b476e6b7cfc4 | Increment version | markembling/MarkEmbling.Utils,markembling/MarkEmbling.Utilities | MarkEmbling.Utils/Properties/AssemblyInfo.cs | MarkEmbling.Utils/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("MarkEmbling.Utils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.Utils")]
[assembly: AssemblyCopyright("Copyright © Mark Embling 2013-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("1b3bb4fe-1808-45b5-aab8-58f3474ef3b5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.7.0")]
[assembly: AssemblyFileVersion("0.0.7.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("MarkEmbling.Utils")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.Utils")]
[assembly: AssemblyCopyright("Copyright © Mark Embling 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("1b3bb4fe-1808-45b5-aab8-58f3474ef3b5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.6.0")]
[assembly: AssemblyFileVersion("0.0.6.0")]
| mit | C# |
a1495d9ff1c8665db24120b413d04f0aacc9f776 | use NullLoggerFactory.Instance in AbpDateTimeModelBinder | ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate | src/Abp.AspNetCore/AspNetCore/Mvc/ModelBinding/AbpDateTimeModelBinder.cs | src/Abp.AspNetCore/AspNetCore/Mvc/ModelBinding/AbpDateTimeModelBinder.cs | using System;
using System.Threading.Tasks;
using Abp.Timing;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using Microsoft.Extensions.Logging.Abstractions;
namespace Abp.AspNetCore.Mvc.ModelBinding
{
public class AbpDateTimeModelBinder : IModelBinder
{
private readonly Type _type;
private readonly SimpleTypeModelBinder _simpleTypeModelBinder;
public AbpDateTimeModelBinder(Type type)
{
_type = type;
//TODO: Core3.0 update -> Should we replace NullLoggerFactory.Instance ?
_simpleTypeModelBinder = new SimpleTypeModelBinder(type, NullLoggerFactory.Instance);
}
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
await _simpleTypeModelBinder.BindModelAsync(bindingContext);
if (!bindingContext.Result.IsModelSet)
{
return;
}
if (_type == typeof(DateTime))
{
var dateTime = (DateTime)bindingContext.Result.Model;
bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime));
}
else
{
var dateTime = (DateTime?)bindingContext.Result.Model;
if (dateTime != null)
{
bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime.Value));
}
}
}
}
} | using System;
using System.Threading.Tasks;
using Abp.Timing;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
namespace Abp.AspNetCore.Mvc.ModelBinding
{
public class AbpDateTimeModelBinder : IModelBinder
{
private readonly Type _type;
private readonly SimpleTypeModelBinder _simpleTypeModelBinder;
public AbpDateTimeModelBinder(Type type)
{
_type = type;
// TODO: Core3.0 update
_simpleTypeModelBinder = new SimpleTypeModelBinder(type, null);
}
public async Task BindModelAsync(ModelBindingContext bindingContext)
{
await _simpleTypeModelBinder.BindModelAsync(bindingContext);
if (!bindingContext.Result.IsModelSet)
{
return;
}
if (_type == typeof(DateTime))
{
var dateTime = (DateTime)bindingContext.Result.Model;
bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime));
}
else
{
var dateTime = (DateTime?)bindingContext.Result.Model;
if (dateTime != null)
{
bindingContext.Result = ModelBindingResult.Success(Clock.Normalize(dateTime.Value));
}
}
}
}
} | mit | C# |
04fc6b261c54226c9d8a4f91c9b35cdde5bed1d9 | Fix handling of CAST in type completion provider | terrajobst/nquery-vnext | src/NQuery.Authoring/Completion/Providers/TypeCompletionProvider.cs | src/NQuery.Authoring/Completion/Providers/TypeCompletionProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Syntax;
namespace NQuery.Authoring.Completion.Providers
{
internal sealed class TypeCompletionProvider : ICompletionProvider
{
public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
var token = syntaxTree.Root.FindTokenOnLeft(position);
var castExpression = token.Parent.AncestorsAndSelf()
.OfType<CastExpressionSyntax>()
.FirstOrDefault(c => !c.AsKeyword.IsMissing && c.AsKeyword.Span.End <= position);
if (castExpression == null)
return Enumerable.Empty<CompletionItem>();
return from typeName in SyntaxFacts.GetTypeNames()
select GetCompletionItem(typeName);
}
private static CompletionItem GetCompletionItem(string typeName)
{
return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Syntax;
namespace NQuery.Authoring.Completion.Providers
{
internal sealed class TypeCompletionProvider : ICompletionProvider
{
public IEnumerable<CompletionItem> GetItems(SemanticModel semanticModel, int position)
{
var syntaxTree = semanticModel.Compilation.SyntaxTree;
var token = syntaxTree.Root.FindTokenOnLeft(position);
var castExpression = token.Parent.AncestorsAndSelf()
.OfType<CastExpressionSyntax>()
.FirstOrDefault(c => c.AsKeyword.Span.End <= position);
if (castExpression == null)
return Enumerable.Empty<CompletionItem>();
return from typeName in SyntaxFacts.GetTypeNames()
select GetCompletionItem(typeName);
}
private static CompletionItem GetCompletionItem(string typeName)
{
return new CompletionItem(typeName, typeName, typeName, NQueryGlyph.Type);
}
}
} | mit | C# |
d32292269e43254928839447798ae8fa7e919c99 | Remove comment | inputfalken/Sharpy | Sharpy/src/Implementation/NumberGenerator.cs | Sharpy/src/Implementation/NumberGenerator.cs | using System;
namespace Sharpy.Implementation {
/// <summary>
/// </summary>
internal sealed class NumberGenerator : Unique<int> {
internal NumberGenerator(Random random)
: base(random) { }
internal int RandomNumber(int min, int max, bool unique = false) {
var next = Random.Next(min, max);
return unique ? CreateUniqueNumber(next, min, max) : next;
}
private int CreateUniqueNumber(int number, int min, int max) {
var resets = 0;
while (HashSet.Contains(number))
if (number < max) {
number++;
}
else {
number = min;
if (resets++ == 2) return -1;
}
HashSet.Add(number);
return number;
}
}
} | using System;
namespace Sharpy.Implementation {
// ReSharper disable once ClassNeverInstantiated.Global
// Is generated from json
/// <summary>
/// </summary>
internal sealed class NumberGenerator : Unique<int> {
internal NumberGenerator(Random random)
: base(random) { }
internal int RandomNumber(int min, int max, bool unique = false) {
var next = Random.Next(min, max);
return unique ? CreateUniqueNumber(next, min, max) : next;
}
private int CreateUniqueNumber(int number, int min, int max) {
var resets = 0;
while (HashSet.Contains(number))
if (number < max) {
number++;
}
else {
number = min;
if (resets++ == 2) return -1;
}
HashSet.Add(number);
return number;
}
}
} | mit | C# |
4dc85826d1ab89638d469acdbb019f8a2c920e0e | Improve thread safety of value propagation from `SafeAreaProvidingContainer` | peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework | osu.Framework/Graphics/Containers/SafeAreaDefiningContainer.cs | osu.Framework/Graphics/Containers/SafeAreaDefiningContainer.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Platform;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A <see cref="Container"/> that is automatically cached and provides a <see cref="BindableSafeArea"/> representing
/// the desired safe area margins. Should be used in conjunction with child <see cref="SafeAreaContainer"/>s.
/// The root of the scenegraph contains an instance of this container, with <see cref="BindableSafeArea"/> automatically bound
/// to the host <see cref="IWindow"/>'s <see cref="IWindow.SafeAreaPadding"/>.
/// </summary>
[Cached(typeof(ISafeArea))]
public class SafeAreaDefiningContainer : Container<Drawable>, ISafeArea
{
private readonly bool usesCustomBinding;
private readonly BindableSafeArea safeArea = new BindableSafeArea();
/// <summary>
/// Initialises a <see cref="SafeAreaDefiningContainer"/> by optionally providing a custom <see cref="BindableSafeArea"/>.
/// If no such binding is provided, the container will default to <see cref="OsuTKWindow.SafeAreaPadding"/>.
/// </summary>
/// <param name="safeArea">The custom <see cref="BindableSafeArea"/> to bind to, if required.</param>
public SafeAreaDefiningContainer(BindableSafeArea safeArea = null)
{
if (safeArea != null)
{
usesCustomBinding = true;
this.safeArea.BindTo(safeArea);
}
}
[Resolved]
private GameHost host { get; set; }
private IBindable<MarginPadding> hostSafeArea;
protected override void LoadComplete()
{
base.LoadComplete();
if (usesCustomBinding || host.Window == null)
return;
hostSafeArea = host.Window.SafeAreaPadding.GetBoundCopy();
hostSafeArea.BindValueChanged(_ => Scheduler.AddOnce(updateSafeAreaFromHost));
updateSafeAreaFromHost();
}
private void updateSafeAreaFromHost() => safeArea.Value = hostSafeArea.Value;
#region ISafeArea Implementation
RectangleF ISafeArea.AvailableNonSafeSpace => DrawRectangle;
Quad ISafeArea.ExpandRectangleToSpaceOfOtherDrawable(IDrawable other) => ToSpaceOfOtherDrawable(DrawRectangle, other);
BindableSafeArea ISafeArea.SafeAreaPadding => safeArea;
#endregion
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Platform;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// A <see cref="Container"/> that is automatically cached and provides a <see cref="BindableSafeArea"/> representing
/// the desired safe area margins. Should be used in conjunction with child <see cref="SafeAreaContainer"/>s.
/// The root of the scenegraph contains an instance of this container, with <see cref="BindableSafeArea"/> automatically bound
/// to the host <see cref="IWindow"/>'s <see cref="IWindow.SafeAreaPadding"/>.
/// </summary>
[Cached(typeof(ISafeArea))]
public class SafeAreaDefiningContainer : Container<Drawable>, ISafeArea
{
private readonly bool usesCustomBinding;
private readonly BindableSafeArea safeArea = new BindableSafeArea();
/// <summary>
/// Initialises a <see cref="SafeAreaDefiningContainer"/> by optionally providing a custom <see cref="BindableSafeArea"/>.
/// If no such binding is provided, the container will default to <see cref="OsuTKWindow.SafeAreaPadding"/>.
/// </summary>
/// <param name="safeArea">The custom <see cref="BindableSafeArea"/> to bind to, if required.</param>
public SafeAreaDefiningContainer(BindableSafeArea safeArea = null)
{
if (safeArea != null)
{
usesCustomBinding = true;
this.safeArea.BindTo(safeArea);
}
}
[BackgroundDependencyLoader]
private void load(GameHost host)
{
if (!usesCustomBinding && host.Window != null)
safeArea.BindTo(host.Window.SafeAreaPadding);
}
#region ISafeArea Implementation
RectangleF ISafeArea.AvailableNonSafeSpace => DrawRectangle;
Quad ISafeArea.ExpandRectangleToSpaceOfOtherDrawable(IDrawable other) => ToSpaceOfOtherDrawable(DrawRectangle, other);
BindableSafeArea ISafeArea.SafeAreaPadding => safeArea;
#endregion
}
}
| mit | C# |
824fdc7c2db8a2f92a38e800ba67881478e4a461 | Test Commit for a GitHub from VS2015 | Microsoft/o365rwsclient | ReportObject.cs | ReportObject.cs | using Microsoft.Office365.ReportingWebServiceClient.Utils;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Microsoft.Office365.ReportingWebServiceClient
{
/// <summary>
/// This is representing an object of the RWS Report returned
/// </summary>
public class ReportObject
{
protected Dictionary<string, string> properties = new Dictionary<string, string>();
// This is a Date property
public DateTime Date
{
get;
set;
}
public virtual void LoadFromXml(XmlNode node)
{
properties = new Dictionary<string, string>();
foreach (XmlNode p in node)
{
string key = p.Name.Replace("d:", "");
properties[key] = p.InnerText.ToString();
}
this.Date = StringUtil.TryParseDateTime(TryGetValue("Date"), DateTime.MinValue);
}
public string ConvertToXml()
{
string retval = null;
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
new XmlSerializer(this.GetType()).Serialize(writer, this);
}
retval = sb.ToString();
return retval;
}
protected string TryGetValue(string key)
{
if (properties.ContainsKey(key))
{
return properties[key];
}
return null;
}
}
} | using Microsoft.Office365.ReportingWebServiceClient.Utils;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Microsoft.Office365.ReportingWebServiceClient
{
/// <summary>
/// This is representing an object of the RWS Report returned
/// </summary>
public class ReportObject
{
protected Dictionary<string, string> properties = new Dictionary<string, string>();
public DateTime Date
{
get;
set;
}
public virtual void LoadFromXml(XmlNode node)
{
properties = new Dictionary<string, string>();
foreach (XmlNode p in node)
{
string key = p.Name.Replace("d:", "");
properties[key] = p.InnerText.ToString();
}
this.Date = StringUtil.TryParseDateTime(TryGetValue("Date"), DateTime.MinValue);
}
public string ConvertToXml()
{
string retval = null;
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb, new XmlWriterSettings() { OmitXmlDeclaration = true }))
{
new XmlSerializer(this.GetType()).Serialize(writer, this);
}
retval = sb.ToString();
return retval;
}
protected string TryGetValue(string key)
{
if (properties.ContainsKey(key))
{
return properties[key];
}
return null;
}
}
} | mit | C# |
c3cfe85d1007166d93a895f672763dd668e47c62 | Include Apple Team Id | bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity | test/mobile/features/fixtures/maze_runner/Assets/Scripts/Builder.cs | test/mobile/features/fixtures/maze_runner/Assets/Scripts/Builder.cs | using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Callbacks;
public class Builder : MonoBehaviour
{
// Generates mazerunner.apk
public static void AndroidBuild()
{
Debug.Log("Building Android app...");
PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "com.bugsnag.mazerunner");
var opts = CommonOptions("mazerunner.apk");
opts.target = BuildTarget.Android;
var result = BuildPipeline.BuildPlayer(opts);
Debug.Log("Result: " + result);
}
// Generates mazerunner.apk
public static void IosBuild()
{
Debug.Log("Building iOS app...");
PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.bugsnag.mazerunner");
PlayerSettings.SetAdditionalIl2CppArgs("--linker-flags=ObjC");
PlayerSettings.iOS.appleDeveloperTeamID = "372ZUL2ZB7";
var opts = CommonOptions("mazerunner_xcode");
opts.target = BuildTarget.iOS;
var result = BuildPipeline.BuildPlayer(opts);
Debug.Log("Result: " + result);
}
private static BuildPlayerOptions CommonOptions(string outputFile)
{
var scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray();
PlayerSettings.defaultInterfaceOrientation = UIOrientation.Portrait;
BuildPlayerOptions opts = new BuildPlayerOptions();
opts.scenes = scenes;
opts.locationPathName = Application.dataPath + "/../" + outputFile;
opts.options = BuildOptions.None;
return opts;
}
[PostProcessBuildAttribute(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
Debug.Log("SKW:" + pathToBuiltProject);
}
}
#endif
| using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.Callbacks;
public class Builder : MonoBehaviour
{
// Generates mazerunner.apk
public static void AndroidBuild()
{
Debug.Log("Building Android app...");
PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, "com.bugsnag.mazerunner");
var opts = CommonOptions("mazerunner.apk");
opts.target = BuildTarget.Android;
var result = BuildPipeline.BuildPlayer(opts);
Debug.Log("Result: " + result);
}
// Generates mazerunner.apk
public static void IosBuild()
{
Debug.Log("Building iOS app...");
PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, "com.bugsnag.mazerunner");
PlayerSettings.SetAdditionalIl2CppArgs("--linker-flags=ObjC");
var opts = CommonOptions("mazerunner_xcode");
opts.target = BuildTarget.iOS;
var result = BuildPipeline.BuildPlayer(opts);
Debug.Log("Result: " + result);
}
private static BuildPlayerOptions CommonOptions(string outputFile)
{
var scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray();
PlayerSettings.defaultInterfaceOrientation = UIOrientation.Portrait;
BuildPlayerOptions opts = new BuildPlayerOptions();
opts.scenes = scenes;
opts.locationPathName = Application.dataPath + "/../" + outputFile;
opts.options = BuildOptions.None;
return opts;
}
[PostProcessBuildAttribute(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
Debug.Log("SKW:" + pathToBuiltProject);
}
}
#endif
| mit | C# |
3f1b9edabe20478578e05f85476d8acaf06eb62d | Fix regression in android build parsing behaviour | NeoAdonis/osu,ppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,peppy/osu | osu.Android/OsuGameAndroid.cs | osu.Android/OsuGameAndroid.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Android.App;
using Android.OS;
using osu.Game;
using osu.Game.Updater;
namespace osu.Android
{
public class OsuGameAndroid : OsuGame
{
public override Version AssemblyVersion
{
get
{
var packageInfo = Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0);
try
{
// We store the osu! build number in the "VersionCode" field to better support google play releases.
// If we were to use the main build number, it would require a new submission each time (similar to TestFlight).
// In order to do this, we should split it up and pad the numbers to still ensure sequential increase over time.
//
// We also need to be aware that older SDK versions store this as a 32bit int.
//
// Basic conversion format (as done in Fastfile): 2020.606.0 -> 202006060
// https://stackoverflow.com/questions/52977079/android-sdk-28-versioncode-in-packageinfo-has-been-deprecated
string versionName = string.Empty;
if (Build.VERSION.SdkInt >= BuildVersionCodes.P)
{
versionName = packageInfo.LongVersionCode.ToString();
versionName = versionName.Substring(versionName.Length - 9);
}
else
{
#pragma warning disable CS0618 // Type or member is obsolete
// this is required else older SDKs will report missing method exception.
versionName = packageInfo.VersionCode.ToString();
#pragma warning restore CS0618 // Type or member is obsolete
}
// undo play store version garbling (as mentioned above).
return new Version(int.Parse(versionName.Substring(0, 4)), int.Parse(versionName.Substring(4, 4)), int.Parse(versionName.Substring(8, 1)));
}
catch
{
}
return new Version(packageInfo.VersionName);
}
}
protected override UpdateManager CreateUpdateManager() => new SimpleUpdateManager();
}
} | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Android.App;
using osu.Game;
using osu.Game.Updater;
namespace osu.Android
{
public class OsuGameAndroid : OsuGame
{
public override Version AssemblyVersion
{
get
{
var packageInfo = Application.Context.ApplicationContext.PackageManager.GetPackageInfo(Application.Context.ApplicationContext.PackageName, 0);
try
{
// todo: needs checking before play store redeploy.
string versionName = packageInfo.VersionName;
// undo play store version garbling
return new Version(int.Parse(versionName.Substring(0, 4)), int.Parse(versionName.Substring(4, 4)), int.Parse(versionName.Substring(8, 1)));
}
catch
{
}
return new Version(packageInfo.VersionName);
}
}
protected override UpdateManager CreateUpdateManager() => new SimpleUpdateManager();
}
} | mit | C# |
d7a61f7982a61c994595c6fe3e0c08c496d212bc | Add ChangeOutputInheritence test | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Tests/UnitTests/BlockchainAnalysis/CoinJoinAnonscoreTests.cs | WalletWasabi.Tests/UnitTests/BlockchainAnalysis/CoinJoinAnonscoreTests.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Tests.Helpers;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BlockchainAnalysis
{
public class CoinJoinAnonscoreTests
{
[Fact]
public void BasicCalculation()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// 10 participant, 1 is you, your anonset is 10.
Assert.Equal(10, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void Inheritence()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 100) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(100, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// 10 participants, 1 is you, your anonset is 10 and you inherit 99 anonset,
// because you don't want to count yourself twice.
Assert.Equal(109, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void ChangeOutput()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(6.2m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(5m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var active = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var change = tx.WalletOutputs.First(x => x.Amount == Money.Coins(5m));
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(10, active.HdPubKey.AnonymitySet);
Assert.Equal(1, change.HdPubKey.AnonymitySet);
}
[Fact]
public void ChangeOutputInheritence()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
// Also test with inheritence.
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(6.2m), 100) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(5m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var active = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var change = tx.WalletOutputs.First(x => x.Amount == Money.Coins(5m));
Assert.Equal(100, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(109, active.HdPubKey.AnonymitySet);
Assert.Equal(100, change.HdPubKey.AnonymitySet);
}
}
}
| using NBitcoin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.Blockchain.Transactions;
using WalletWasabi.Tests.Helpers;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.BlockchainAnalysis
{
public class CoinJoinAnonscoreTests
{
[Fact]
public void BasicCalculation()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// 10 participant, 1 is you, your anonset is 10.
Assert.Equal(10, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void Inheritence()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(1.1m), 100) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
Assert.Equal(100, tx.WalletInputs.First().HdPubKey.AnonymitySet);
// 10 participants, 1 is you, your anonset is 10 and you inherit 99 anonset,
// because you don't want to count yourself twice.
Assert.Equal(109, tx.WalletOutputs.First().HdPubKey.AnonymitySet);
}
[Fact]
public void ChangeOutput()
{
var analyser = BitcoinMock.RandomBlockchainAnalyzer();
var tx = BitcoinMock.RandomSmartTransaction(9, Enumerable.Repeat(Money.Coins(1m), 9), new[] { (Money.Coins(6.2m), 1) }, new[] { (Money.Coins(1m), HdPubKey.DefaultHighAnonymitySet), (Money.Coins(5m), HdPubKey.DefaultHighAnonymitySet) });
analyser.Analyze(tx);
var active = tx.WalletOutputs.First(x => x.Amount == Money.Coins(1m));
var change = tx.WalletOutputs.First(x => x.Amount == Money.Coins(5m));
Assert.Equal(1, tx.WalletInputs.First().HdPubKey.AnonymitySet);
Assert.Equal(10, active.HdPubKey.AnonymitySet);
Assert.Equal(1, change.HdPubKey.AnonymitySet);
}
}
}
| mit | C# |
3840563a69af59bd31a54567a75e89d5810c68c2 | Update Program.cs | runnersQueue/3minutes | SubFolderTest/TestGit/Program.cs | SubFolderTest/TestGit/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Urho;
using Urho.Gui;
using Urho.Resources;
using Urho.Shapes;
namespace TestGit
{
class Program : SimpleApplication
{
Program(ApplicationOptions options = null) :base(options) { }
protected override void Start()
{
//Insert Garbage here
}
static void Main(string[] args)
{
var app = new Program(new ApplicationOptions("Data")
{
TouchEmulation = true,
WindowedMode = true
});
app.Run();
}
public void MyNoReturnMethod()
{
}
static void CaseHarmfull()
{
//Harmfull
//Harmfull2You
System.Console.WriteLine("Hello");
int num = 0;
for (int i = 0; i < 5; i++)
{
System.Console.WriteLine(i);
num += i;
}
int newbie = ThisShouldBeHarmlessSantana(num, 7);
System.Console.WriteLine(newbie);
}
static int ThisShouldBeHarmlessSantana(int a, int b)
{
return a + b;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Urho;
using Urho.Gui;
using Urho.Resources;
using Urho.Shapes;
namespace TestGit
{
class Program : SimpleApplication
{
Program(ApplicationOptions options = null) :base(options) { }
static void Main(string[] args)
{
var app = new Program(new ApplicationOptions("Data")
{
TouchEmulation = true,
WindowedMode = true
});
app.Run();
}
public void MyNoReturnMethod()
{
}
static void CaseHarmfull()
{
//Harmfull
//Harmfull2You
System.Console.WriteLine("Hello");
int num = 0;
for (int i = 0; i < 5; i++)
{
System.Console.WriteLine(i);
num += i;
}
int newbie = ThisShouldBeHarmlessSantana(num, 7);
System.Console.WriteLine(newbie);
}
static int ThisShouldBeHarmlessSantana(int a, int b)
{
return a + b;
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.