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
ca25cfbfa5020dc37607b97b7f4d0bc9e9089910
update iframework.foundatioLock version number
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/iFramework.Plugins/IFramework.FoundatioLock/Properties/AssemblyInfo.cs
Src/iFramework.Plugins/IFramework.FoundatioLock/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("IFramework.FoundatioLock")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IFramework.FoundatioLock")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ed7dc1bf-939f-43c8-aedf-89589ae3701d")] // 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")]
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("IFramework.FoundatioLock")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IFramework.FoundatioLock")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ed7dc1bf-939f-43c8-aedf-89589ae3701d")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
mit
C#
c371e67d705df820ded3c66344a27cf3d1b07b20
Update diffcalc test to match ground-truth formula
peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,ppy/osu
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.4164199087433484d, "diffcalc-test")] [TestCase(1.0028132594779837d, "zero-length-sliders")] public void Test(double expected, string name) => base.Test(expected, name); [TestCase(8.0749334911818469d, "diffcalc-test")] [TestCase(1.2251606765323657d, "zero-length-sliders")] public void TestClockRateAdjusted(double expected, string name) => Test(expected, name, new OsuModDoubleTime()); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Osu.Difficulty; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Osu.Tests { [TestFixture] public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest { protected override string ResourceAssembly => "osu.Game.Rulesets.Osu"; [TestCase(6.7568168283591499d, "diffcalc-test")] [TestCase(1.0348244046058293d, "zero-length-sliders")] public void Test(double expected, string name) => base.Test(expected, name); [TestCase(8.4783236764532557d, "diffcalc-test")] [TestCase(1.2708532136987165d, "zero-length-sliders")] public void TestClockRateAdjusted(double expected, string name) => Test(expected, name, new OsuModDoubleTime()); protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap); protected override Ruleset CreateRuleset() => new OsuRuleset(); } }
mit
C#
801c46ea042f96b729a28c133b35de5c72e83095
Fix data migration code for UserRecord
jersiovic/Orchard,planetClaire/Orchard-LETS,qt1/orchard4ibn,KeithRaven/Orchard,grapto/Orchard.CloudBust,DonnotRain/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,qt1/orchard4ibn,planetClaire/Orchard-LETS,SzymonSel/Orchard,hbulzy/Orchard,m2cms/Orchard,SouleDesigns/SouleDesigns.Orchard,jchenga/Orchard,JRKelso/Orchard,fortunearterial/Orchard,stormleoxia/Orchard,vairam-svs/Orchard,TaiAivaras/Orchard,spraiin/Orchard,salarvand/Portal,jaraco/orchard,SzymonSel/Orchard,xkproject/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,Sylapse/Orchard.HttpAuthSample,aaronamm/Orchard,yersans/Orchard,bigfont/orchard-continuous-integration-demo,armanforghani/Orchard,Anton-Am/Orchard,TalaveraTechnologySolutions/Orchard,ehe888/Orchard,jerryshi2007/Orchard,Anton-Am/Orchard,Codinlab/Orchard,jagraz/Orchard,vairam-svs/Orchard,hannan-azam/Orchard,OrchardCMS/Orchard,rtpHarry/Orchard,SouleDesigns/SouleDesigns.Orchard,kouweizhong/Orchard,IDeliverable/Orchard,salarvand/orchard,dcinzona/Orchard,qt1/orchard4ibn,geertdoornbos/Orchard,LaserSrl/Orchard,enspiral-dev-academy/Orchard,Praggie/Orchard,aaronamm/Orchard,bigfont/orchard-cms-modules-and-themes,emretiryaki/Orchard,arminkarimi/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard-Harvest-Website,geertdoornbos/Orchard,TaiAivaras/Orchard,harmony7/Orchard,rtpHarry/Orchard,vairam-svs/Orchard,Cphusion/Orchard,cooclsee/Orchard,enspiral-dev-academy/Orchard,grapto/Orchard.CloudBust,emretiryaki/Orchard,gcsuk/Orchard,MpDzik/Orchard,MetSystem/Orchard,omidnasri/Orchard,KeithRaven/Orchard,smartnet-developers/Orchard,ehe888/Orchard,Lombiq/Orchard,LaserSrl/Orchard,asabbott/chicagodevnet-website,hbulzy/Orchard,qt1/Orchard,AEdmunds/beautiful-springtime,brownjordaninternational/OrchardCMS,OrchardCMS/Orchard-Harvest-Website,IDeliverable/Orchard,SzymonSel/Orchard,yersans/Orchard,xiaobudian/Orchard,AEdmunds/beautiful-springtime,infofromca/Orchard,NIKASoftwareDevs/Orchard,spraiin/Orchard,SzymonSel/Orchard,TalaveraTechnologySolutions/Orchard,RoyalVeterinaryCollege/Orchard,escofieldnaxos/Orchard,fortunearterial/Orchard,vard0/orchard.tan,Lombiq/Orchard,qt1/orchard4ibn,OrchardCMS/Orchard-Harvest-Website,tobydodds/folklife,OrchardCMS/Orchard-Harvest-Website,mgrowan/Orchard,angelapper/Orchard,austinsc/Orchard,yersans/Orchard,sfmskywalker/Orchard,MpDzik/Orchard,huoxudong125/Orchard,IDeliverable/Orchard,sfmskywalker/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,qt1/Orchard,TaiAivaras/Orchard,jerryshi2007/Orchard,dcinzona/Orchard,AndreVolksdorf/Orchard,dozoft/Orchard,cryogen/orchard,alejandroaldana/Orchard,TalaveraTechnologySolutions/Orchard,DonnotRain/Orchard,MetSystem/Orchard,cooclsee/Orchard,oxwanawxo/Orchard,caoxk/orchard,armanforghani/Orchard,vard0/orchard.tan,andyshao/Orchard,Dolphinsimon/Orchard,bigfont/orchard-cms-modules-and-themes,jtkech/Orchard,Ermesx/Orchard,yonglehou/Orchard,grapto/Orchard.CloudBust,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,jimasp/Orchard,grapto/Orchard.CloudBust,infofromca/Orchard,sebastienros/msc,dcinzona/Orchard-Harvest-Website,andyshao/Orchard,ericschultz/outercurve-orchard,Serlead/Orchard,cryogen/orchard,jtkech/Orchard,enspiral-dev-academy/Orchard,dcinzona/Orchard-Harvest-Website,hhland/Orchard,andyshao/Orchard,Lombiq/Orchard,TalaveraTechnologySolutions/Orchard,rtpHarry/Orchard,omidnasri/Orchard,jagraz/Orchard,bedegaming-aleksej/Orchard,escofieldnaxos/Orchard,KeithRaven/Orchard,angelapper/Orchard,dozoft/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,ericschultz/outercurve-orchard,JRKelso/Orchard,luchaoshuai/Orchard,AndreVolksdorf/Orchard,cooclsee/Orchard,yonglehou/Orchard,Inner89/Orchard,johnnyqian/Orchard,marcoaoteixeira/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,jtkech/Orchard,sfmskywalker/Orchard,MetSystem/Orchard,SeyDutch/Airbrush,hannan-azam/Orchard,AdvantageCS/Orchard,brownjordaninternational/OrchardCMS,spraiin/Orchard,Morgma/valleyviewknolls,jagraz/Orchard,smartnet-developers/Orchard,jersiovic/Orchard,NIKASoftwareDevs/Orchard,harmony7/Orchard,Anton-Am/Orchard,ehe888/Orchard,SouleDesigns/SouleDesigns.Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,dburriss/Orchard,ehe888/Orchard,hannan-azam/Orchard,TalaveraTechnologySolutions/Orchard,RoyalVeterinaryCollege/Orchard,Praggie/Orchard,salarvand/orchard,kgacova/Orchard,neTp9c/Orchard,stormleoxia/Orchard,brownjordaninternational/OrchardCMS,Cphusion/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,DonnotRain/Orchard,OrchardCMS/Orchard-Harvest-Website,jtkech/Orchard,oxwanawxo/Orchard,Fogolan/OrchardForWork,tobydodds/folklife,fassetar/Orchard,angelapper/Orchard,li0803/Orchard,li0803/Orchard,emretiryaki/Orchard,TaiAivaras/Orchard,ericschultz/outercurve-orchard,emretiryaki/Orchard,jersiovic/Orchard,Inner89/Orchard,vard0/orchard.tan,LaserSrl/Orchard,qt1/Orchard,MetSystem/Orchard,vard0/orchard.tan,harmony7/Orchard,hbulzy/Orchard,Lombiq/Orchard,hhland/Orchard,Dolphinsimon/Orchard,abhishekluv/Orchard,salarvand/orchard,Cphusion/Orchard,OrchardCMS/Orchard,AEdmunds/beautiful-springtime,jimasp/Orchard,hhland/Orchard,dburriss/Orchard,mvarblow/Orchard,asabbott/chicagodevnet-website,gcsuk/Orchard,fassetar/Orchard,fortunearterial/Orchard,sfmskywalker/Orchard,Cphusion/Orchard,marcoaoteixeira/Orchard,neTp9c/Orchard,DonnotRain/Orchard,armanforghani/Orchard,smartnet-developers/Orchard,openbizgit/Orchard,Anton-Am/Orchard,bedegaming-aleksej/Orchard,Ermesx/Orchard,dcinzona/Orchard-Harvest-Website,Dolphinsimon/Orchard,sfmskywalker/Orchard,spraiin/Orchard,Inner89/Orchard,bigfont/orchard-cms-modules-and-themes,Cphusion/Orchard,Ermesx/Orchard,TalaveraTechnologySolutions/Orchard,jimasp/Orchard,omidnasri/Orchard,yersans/Orchard,AdvantageCS/Orchard,escofieldnaxos/Orchard,Serlead/Orchard,li0803/Orchard,JRKelso/Orchard,xkproject/Orchard,Codinlab/Orchard,SeyDutch/Airbrush,stormleoxia/Orchard,princeppy/JPYSites-Orchard-Azure-Live-SourceCode,TalaveraTechnologySolutions/Orchard,phillipsj/Orchard,jagraz/Orchard,bedegaming-aleksej/Orchard,jersiovic/Orchard,dcinzona/Orchard,MpDzik/Orchard,Praggie/Orchard,phillipsj/Orchard,kgacova/Orchard,geertdoornbos/Orchard,aaronamm/Orchard,alejandroaldana/Orchard,grapto/Orchard.CloudBust,hannan-azam/Orchard,rtpHarry/Orchard,dburriss/Orchard,austinsc/Orchard,jimasp/Orchard,jaraco/orchard,hannan-azam/Orchard,angelapper/Orchard,johnnyqian/Orchard,marcoaoteixeira/Orchard,OrchardCMS/Orchard,Dolphinsimon/Orchard,RoyalVeterinaryCollege/Orchard,tobydodds/folklife,phillipsj/Orchard,dburriss/Orchard,kgacova/Orchard,patricmutwiri/Orchard,OrchardCMS/Orchard,mvarblow/Orchard,sebastienros/msc,dcinzona/Orchard,Praggie/Orchard,planetClaire/Orchard-LETS,yersans/Orchard,mvarblow/Orchard,li0803/Orchard,patricmutwiri/Orchard,hhland/Orchard,neTp9c/Orchard,MpDzik/Orchard,vard0/orchard.tan,stormleoxia/Orchard,JRKelso/Orchard,AdvantageCS/Orchard,arminkarimi/Orchard,patricmutwiri/Orchard,Serlead/Orchard,geertdoornbos/Orchard,patricmutwiri/Orchard,Anton-Am/Orchard,asabbott/chicagodevnet-website,abhishekluv/Orchard,dozoft/Orchard,emretiryaki/Orchard,vairam-svs/Orchard,SouleDesigns/SouleDesigns.Orchard,salarvand/orchard,Ermesx/Orchard,SeyDutch/Airbrush,luchaoshuai/Orchard,kouweizhong/Orchard,marcoaoteixeira/Orchard,aaronamm/Orchard,fortunearterial/Orchard,NIKASoftwareDevs/Orchard,RoyalVeterinaryCollege/Orchard,SzymonSel/Orchard,omidnasri/Orchard,OrchardCMS/Orchard,arminkarimi/Orchard,Inner89/Orchard,huoxudong125/Orchard,andyshao/Orchard,grapto/Orchard.CloudBust,dcinzona/Orchard,escofieldnaxos/Orchard,KeithRaven/Orchard,sfmskywalker/Orchard,AndreVolksdorf/Orchard,asabbott/chicagodevnet-website,infofromca/Orchard,andyshao/Orchard,harmony7/Orchard,yonglehou/Orchard,dcinzona/Orchard-Harvest-Website,cooclsee/Orchard,patricmutwiri/Orchard,oxwanawxo/Orchard,salarvand/orchard,dozoft/Orchard,caoxk/orchard,brownjordaninternational/OrchardCMS,mgrowan/Orchard,TaiAivaras/Orchard,openbizgit/Orchard,Serlead/Orchard,JRKelso/Orchard,Serlead/Orchard,m2cms/Orchard,vairam-svs/Orchard,Fogolan/OrchardForWork,dmitry-urenev/extended-orchard-cms-v10.1,abhishekluv/Orchard,yonglehou/Orchard,kouweizhong/Orchard,Sylapse/Orchard.HttpAuthSample,huoxudong125/Orchard,Codinlab/Orchard,infofromca/Orchard,dozoft/Orchard,hbulzy/Orchard,Morgma/valleyviewknolls,omidnasri/Orchard,AndreVolksdorf/Orchard,mvarblow/Orchard,arminkarimi/Orchard,fassetar/Orchard,salarvand/Portal,openbizgit/Orchard,qt1/Orchard,tobydodds/folklife,mgrowan/Orchard,stormleoxia/Orchard,openbizgit/Orchard,xkproject/Orchard,kgacova/Orchard,qt1/orchard4ibn,dmitry-urenev/extended-orchard-cms-v10.1,jimasp/Orchard,luchaoshuai/Orchard,Fogolan/OrchardForWork,qt1/orchard4ibn,oxwanawxo/Orchard,tobydodds/folklife,austinsc/Orchard,Fogolan/OrchardForWork,SeyDutch/Airbrush,dmitry-urenev/extended-orchard-cms-v10.1,kgacova/Orchard,xiaobudian/Orchard,bigfont/orchard-continuous-integration-demo,infofromca/Orchard,jerryshi2007/Orchard,MpDzik/Orchard,IDeliverable/Orchard,dburriss/Orchard,angelapper/Orchard,MetSystem/Orchard,escofieldnaxos/Orchard,kouweizhong/Orchard,Morgma/valleyviewknolls,jtkech/Orchard,jchenga/Orchard,caoxk/orchard,ehe888/Orchard,phillipsj/Orchard,abhishekluv/Orchard,bigfont/orchard-continuous-integration-demo,salarvand/Portal,qt1/Orchard,salarvand/Portal,austinsc/Orchard,jaraco/orchard,sfmskywalker/Orchard,johnnyqian/Orchard,austinsc/Orchard,mgrowan/Orchard,bigfont/orchard-cms-modules-and-themes,planetClaire/Orchard-LETS,AdvantageCS/Orchard,caoxk/orchard,neTp9c/Orchard,neTp9c/Orchard,abhishekluv/Orchard,mvarblow/Orchard,luchaoshuai/Orchard,Sylapse/Orchard.HttpAuthSample,SouleDesigns/SouleDesigns.Orchard,omidnasri/Orchard,jerryshi2007/Orchard,m2cms/Orchard,omidnasri/Orchard,jersiovic/Orchard,luchaoshuai/Orchard,kouweizhong/Orchard,bigfont/orchard-continuous-integration-demo,NIKASoftwareDevs/Orchard,enspiral-dev-academy/Orchard,xiaobudian/Orchard,li0803/Orchard,jchenga/Orchard,cooclsee/Orchard,openbizgit/Orchard,smartnet-developers/Orchard,sfmskywalker/Orchard,AdvantageCS/Orchard,hbulzy/Orchard,huoxudong125/Orchard,mgrowan/Orchard,m2cms/Orchard,sebastienros/msc,jagraz/Orchard,harmony7/Orchard,cryogen/orchard,Fogolan/OrchardForWork,yonglehou/Orchard,LaserSrl/Orchard,xiaobudian/Orchard,johnnyqian/Orchard,johnnyqian/Orchard,SeyDutch/Airbrush,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Ermesx/Orchard,gcsuk/Orchard,jchenga/Orchard,abhishekluv/Orchard,sebastienros/msc,sebastienros/msc,tobydodds/folklife,cryogen/orchard,Morgma/valleyviewknolls,m2cms/Orchard,omidnasri/Orchard,aaronamm/Orchard,fortunearterial/Orchard,fassetar/Orchard,brownjordaninternational/OrchardCMS,bedegaming-aleksej/Orchard,MpDzik/Orchard,hhland/Orchard,jchenga/Orchard,Praggie/Orchard,gcsuk/Orchard,bigfont/orchard-cms-modules-and-themes,ericschultz/outercurve-orchard,Lombiq/Orchard,fassetar/Orchard,huoxudong125/Orchard,jerryshi2007/Orchard,geertdoornbos/Orchard,jaraco/orchard,KeithRaven/Orchard,planetClaire/Orchard-LETS,armanforghani/Orchard,xkproject/Orchard,alejandroaldana/Orchard,xiaobudian/Orchard,AEdmunds/beautiful-springtime,dcinzona/Orchard-Harvest-Website,smartnet-developers/Orchard,Sylapse/Orchard.HttpAuthSample,omidnasri/Orchard,OrchardCMS/Orchard-Harvest-Website,arminkarimi/Orchard,DonnotRain/Orchard,Dolphinsimon/Orchard,xkproject/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,LaserSrl/Orchard,Inner89/Orchard,enspiral-dev-academy/Orchard,NIKASoftwareDevs/Orchard,rtpHarry/Orchard,oxwanawxo/Orchard,phillipsj/Orchard,gcsuk/Orchard,Codinlab/Orchard,armanforghani/Orchard,vard0/orchard.tan,Codinlab/Orchard,IDeliverable/Orchard,spraiin/Orchard,alejandroaldana/Orchard,dcinzona/Orchard-Harvest-Website,salarvand/Portal,AndreVolksdorf/Orchard,RoyalVeterinaryCollege/Orchard,Morgma/valleyviewknolls,marcoaoteixeira/Orchard,alejandroaldana/Orchard,Sylapse/Orchard.HttpAuthSample,TalaveraTechnologySolutions/Orchard,bedegaming-aleksej/Orchard
src/Orchard.Web/Modules/Orchard.Users/DataMigrations/UsersDataMigration.cs
src/Orchard.Web/Modules/Orchard.Users/DataMigrations/UsersDataMigration.cs
using Orchard.Data.Migration; namespace Orchard.Users.DataMigrations { public class UsersDataMigration : DataMigrationImpl { public int Create() { //CREATE TABLE Orchard_Users_UserRecord (Id INTEGER not null, UserName TEXT, Email TEXT, NormalizedUserName TEXT, Password TEXT, PasswordFormat TEXT, PasswordSalt TEXT, primary key (Id)); SchemaBuilder.CreateTable("UserRecord", table => table .ContentPartRecord() .Column<string>("UserName") .Column<string>("Email") .Column<string>("NormalizedUserName") .Column<string>("Password") .Column<string>("PasswordFormat") .Column<string>("HashAlgorithm") .Column<string>("PasswordSalt") ); return 0010; } } }
using Orchard.Data.Migration; namespace Orchard.Users.DataMigrations { public class UsersDataMigration : DataMigrationImpl { public int Create() { //CREATE TABLE Orchard_Users_UserRecord (Id INTEGER not null, UserName TEXT, Email TEXT, NormalizedUserName TEXT, Password TEXT, PasswordFormat TEXT, PasswordSalt TEXT, primary key (Id)); SchemaBuilder.CreateTable("UserRecord", table => table .ContentPartRecord() .Column<string>("UserName") .Column<string>("Email") .Column<string>("NormalizedUserName") .Column<string>("Password") .Column<string>("PasswordFormat") .Column<string>("PasswordSalt") ); return 0010; } } }
bsd-3-clause
C#
ba3b1b96507833255259a6874239c3f5f936da2f
Comment added
xavierfoucrier/gmail-notifier,xavierfoucrier/gmail-notifier
code/Program.cs
code/Program.cs
using System; using System.Globalization; using System.Threading; using System.Windows.Forms; using notifier.Languages; using notifier.Properties; namespace notifier { static class Program { /// <summary> /// Mutex associated to the application instance /// </summary> static Mutex mutex = new Mutex(true, "gmailnotifier-115e363ecbfefd771e55c6874680bc0a"); [STAThread] static void Main(string[] args) { // initializes the configuration file with setup installer settings if (args.Length == 3 && args[0] == "install") { // language application setting switch (args[1]) { default: case "en": Settings.Default.Language = "English"; break; case "fr": Settings.Default.Language = "Français"; break; case "de": Settings.Default.Language = "Deutsch"; break; } // start with Windows setting Settings.Default.RunAtWindowsStartup = args[2] == "auto"; // commits changes to the configuration file Settings.Default.Save(); return; } // initializes the interface with the specified culture, depending on the user settings switch (Settings.Default.Language) { default: case "English": Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); break; case "Français": Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR"); break; case "Deutsch": Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE"); break; } // check if there is an instance running if (!mutex.WaitOne(TimeSpan.Zero, true)) { MessageBox.Show(translation.mutexError, translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // sets some default properties Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // run the main window Application.Run(new Main()); // releases the mutex instance mutex.ReleaseMutex(); } } }
using System; using System.Globalization; using System.Threading; using System.Windows.Forms; using notifier.Languages; using notifier.Properties; namespace notifier { static class Program { /// <summary> /// Mutex associated to the application instance /// </summary> static Mutex mutex = new Mutex(true, "gmailnotifier-115e363ecbfefd771e55c6874680bc0a"); [STAThread] static void Main(string[] args) { // initializes the configuration file with setup installer settings if (args.Length == 3 && args[0] == "install") { // language application setting switch (args[1]) { default: case "en": Settings.Default.Language = "English"; break; case "fr": Settings.Default.Language = "Français"; break; case "de": Settings.Default.Language = "Deutsch"; break; } // start with Windows setting Settings.Default.RunAtWindowsStartup = args[2] == "auto"; // commits changes to the configuration file Settings.Default.Save(); return; } // initializes the interface with the specified culture, depending on the user settings switch (Settings.Default.Language) { default: case "English": Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); break; case "Français": Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR"); break; case "Deutsch": Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE"); break; } // check if there is an instance running if (!mutex.WaitOne(TimeSpan.Zero, true)) { MessageBox.Show(translation.mutexError, translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // sets some default properties Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // run the main window Application.Run(new Main()); mutex.ReleaseMutex(); } } }
mit
C#
f828c2d60dc358a4bae89e43cc097e5513037667
Update ProductAssemblyInfo.cs
mattiasnordqvist/Web-Anchor
ProductAssemblyInfo.cs
ProductAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyProduct("WebAnchor")] [assembly: AssemblyCompany("Spinit AB, Mattias Nordqvist, Carl Berg and contributors")] [assembly: AssemblyCopyright("Copyright Spinit AB, Mattias Nordqvist, Carl Berg and contributors 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] /* File versions are set by CI build */ [assembly: AssemblyVersion("6.4.0")] [assembly: AssemblyFileVersion("6.4.0")] [assembly: AssemblyInformationalVersion("6.4.0")]
using System.Reflection; [assembly: AssemblyProduct("WebAnchor")] [assembly: AssemblyCompany("Spinit AB, Mattias Nordqvist, Carl Berg and contributors")] [assembly: AssemblyCopyright("Copyright Spinit AB, Mattias Nordqvist, Carl Berg and contributors 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] /* File versions are set by CI build */ [assembly: AssemblyVersion("6.3.0")] [assembly: AssemblyFileVersion("6.3.0")] [assembly: AssemblyInformationalVersion("6.3.0")]
mit
C#
f41bfd14ca890730c71b646ccda47222213c85b3
Add some xmldocs
UselessToucan/osu,naoey/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,EVAST9919/osu,naoey/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu-new,DrabWeb/osu,smoogipooo/osu,ZLima12/osu,johnneijzen/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,2yangk23/osu,2yangk23/osu,ZLima12/osu,peppy/osu,DrabWeb/osu,ppy/osu,naoey/osu,UselessToucan/osu,ppy/osu,ppy/osu
osu.Game/Rulesets/UI/Scrolling/Visualisers/ISpeedChangeVisualiser.cs
osu.Game/Rulesets/UI/Scrolling/Visualisers/ISpeedChangeVisualiser.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.UI.Scrolling.Visualisers { public interface ISpeedChangeVisualiser { /// <summary> /// Given a point in time, computes the time at which the point enters the visible time range of this <see cref="ISpeedChangeVisualiser"/>. /// </summary> /// <remarks> /// E.g. For a constant visible time range of 5000ms, the time at which t=7000ms enters the visible time range is 2000ms. /// </remarks> /// <param name="time">The time value.</param> /// <returns>The time at which <paramref name="time"/> enters the visible time range of this <see cref="ISpeedChangeVisualiser"/>.</returns> double GetDisplayStartTime(double time); /// <summary> /// Computes the spatial length within a start and end time. /// </summary> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <returns>The absolute spatial length.</returns> float GetLength(double startTime, double endTime); /// <summary> /// Given the current time, computes the spatial position of a point in time. /// </summary> /// <param name="time">The time to compute the spatial position of.</param> /// <param name="currentTime">The current time.</param> /// <returns>The absolute spatial position.</returns> float PositionAt(double time, double currentTime); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Rulesets.UI.Scrolling.Visualisers { public interface ISpeedChangeVisualiser { double GetDisplayStartTime(double time); float GetLength(double startTime, double endTime); float PositionAt(double time, double currentTime); } }
mit
C#
eddae70823956172d88630f64452ceb46f19b610
add comments for public API
idseefeld/imagecropper4umbraco,idseefeld/imagecropper4umbraco,idseefeld/imagecropper4umbraco
idseefeld.de.imagecropper.pevc/ImageCropperExtendedPropertyEditorValueConverter.cs
idseefeld.de.imagecropper.pevc/ImageCropperExtendedPropertyEditorValueConverter.cs
using System; using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.PropertyEditors; using Umbraco.Web; using idseefeld.de.imagecropper.Model; using idseefeld.de.imagecropper.imagecropper; namespace idseefeld.de.imagecropper.PropertyEditorValueConverter { public class ImageCropperExtendedPropertyEditorValueConverter : IPropertyEditorValueConverter { /// <summary> /// PEVC for Image Cropper Extended /// </summary> /// <param name="propertyEditorId">Image Cropper Extended Guid</param> /// <param name="docTypeAlias">not used</param> /// <param name="propertyTypeAlias">not used</param> /// <returns></returns> public bool IsConverterFor(Guid propertyEditorId, string docTypeAlias, string propertyTypeAlias) { return ImageCropperBase.PropertyEditorId.Equals(propertyEditorId); } /// <summary> /// Converts the property value into strongly typed CropList (List&lt;CropModel&gt;). /// </summary> /// <param name="value">Property value</param> /// <returns>CropList</returns> public Attempt<object> ConvertPropertyValue(object value) { if (UmbracoContext.Current != null) { try { ImageCropperModel imageCropperExtendedContent = new ImageCropperModel(value.ToString()); CropList result = new CropList(imageCropperExtendedContent); return new Attempt<object>(true, result); } catch { } } return Attempt<object>.False; } } public class CropList : List<CropModel> { /// <summary> /// List of all crops as definded in the data type. /// </summary> /// <param name="model">ImageCropperModel (strongly typed model fro Image Cropper Extended data types aka property editor)</param> public CropList(ImageCropperModel model) { if (model == null) return; foreach (var crop in model.Crops) { this.Add(crop); } } /// <summary> /// Selects a crop by its name /// </summary> /// <param name="cropName">Name of crop as definde in the data type.</param> /// <returns>CropModel (strongly typed crop)</returns> public CropModel Find(string cropName) { return this.Find(c => c.Name.Equals(cropName)); } } }
using System; using System.Collections.Generic; using Umbraco.Core; using Umbraco.Core.PropertyEditors; using Umbraco.Web; using idseefeld.de.imagecropper.Model; using idseefeld.de.imagecropper.imagecropper; namespace idseefeld.de.imagecropper.PropertyEditorValueConverter { public class ImageCropperExtendedPropertyEditorValueConverter : IPropertyEditorValueConverter { string _propertyTypeAlias = string.Empty; string _docTypeAlias = string.Empty; public bool IsConverterFor(Guid propertyEditorId, string docTypeAlias, string propertyTypeAlias) { _propertyTypeAlias = propertyTypeAlias; _docTypeAlias = docTypeAlias; return ImageCropperBase.PropertyEditorId.Equals(propertyEditorId); } public Attempt<object> ConvertPropertyValue(object value) { if (UmbracoContext.Current != null) { try { ImageCropperModel imageCropperExtendedContent = new ImageCropperModel(value.ToString()); CropList result = new CropList(imageCropperExtendedContent); return new Attempt<object>(true, result); } catch { } } return Attempt<object>.False; } } public class CropList : List<CropModel> { public CropList(ImageCropperModel model) { if (model == null) return; foreach (var crop in model.Crops) { this.Add(crop); } } } }
mit
C#
0b7655e6ce54d2ff8d9e4b8042ab37b397aed4b6
Add serialization test for CookieContainer (#17673)
wtgodbe/corefx,elijah6/corefx,wtgodbe/corefx,cydhaselton/corefx,axelheer/corefx,ptoonen/corefx,JosephTremoulet/corefx,rjxby/corefx,YoupHulsebos/corefx,the-dwyer/corefx,rahku/corefx,twsouthwick/corefx,ptoonen/corefx,Petermarcu/corefx,shimingsg/corefx,elijah6/corefx,mazong1123/corefx,ViktorHofer/corefx,Jiayili1/corefx,krytarowski/corefx,JosephTremoulet/corefx,Petermarcu/corefx,mazong1123/corefx,seanshpark/corefx,the-dwyer/corefx,stone-li/corefx,alexperovich/corefx,MaggieTsang/corefx,elijah6/corefx,zhenlan/corefx,axelheer/corefx,Jiayili1/corefx,ravimeda/corefx,richlander/corefx,stephenmichaelf/corefx,rjxby/corefx,DnlHarvey/corefx,BrennanConroy/corefx,BrennanConroy/corefx,dhoehna/corefx,MaggieTsang/corefx,stephenmichaelf/corefx,zhenlan/corefx,nchikanov/corefx,gkhanna79/corefx,stone-li/corefx,krytarowski/corefx,tijoytom/corefx,richlander/corefx,axelheer/corefx,JosephTremoulet/corefx,zhenlan/corefx,rubo/corefx,parjong/corefx,jlin177/corefx,gkhanna79/corefx,DnlHarvey/corefx,yizhang82/corefx,rjxby/corefx,elijah6/corefx,tijoytom/corefx,alexperovich/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,krytarowski/corefx,stephenmichaelf/corefx,tijoytom/corefx,Ermiar/corefx,ericstj/corefx,Petermarcu/corefx,billwert/corefx,ptoonen/corefx,elijah6/corefx,wtgodbe/corefx,dotnet-bot/corefx,nbarbettini/corefx,dotnet-bot/corefx,ravimeda/corefx,richlander/corefx,Jiayili1/corefx,weltkante/corefx,elijah6/corefx,rahku/corefx,krk/corefx,fgreinacher/corefx,nchikanov/corefx,rubo/corefx,the-dwyer/corefx,zhenlan/corefx,mmitche/corefx,ViktorHofer/corefx,seanshpark/corefx,tijoytom/corefx,weltkante/corefx,MaggieTsang/corefx,Ermiar/corefx,ericstj/corefx,gkhanna79/corefx,dhoehna/corefx,fgreinacher/corefx,mazong1123/corefx,ptoonen/corefx,zhenlan/corefx,wtgodbe/corefx,rahku/corefx,YoupHulsebos/corefx,dotnet-bot/corefx,krytarowski/corefx,ericstj/corefx,axelheer/corefx,krytarowski/corefx,axelheer/corefx,dotnet-bot/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,shimingsg/corefx,YoupHulsebos/corefx,ericstj/corefx,yizhang82/corefx,twsouthwick/corefx,mmitche/corefx,JosephTremoulet/corefx,seanshpark/corefx,dhoehna/corefx,mmitche/corefx,Petermarcu/corefx,mmitche/corefx,billwert/corefx,krk/corefx,yizhang82/corefx,nchikanov/corefx,zhenlan/corefx,krk/corefx,billwert/corefx,ViktorHofer/corefx,stone-li/corefx,parjong/corefx,parjong/corefx,rahku/corefx,Jiayili1/corefx,Ermiar/corefx,Ermiar/corefx,YoupHulsebos/corefx,rubo/corefx,dotnet-bot/corefx,tijoytom/corefx,gkhanna79/corefx,rjxby/corefx,YoupHulsebos/corefx,axelheer/corefx,krk/corefx,nbarbettini/corefx,weltkante/corefx,yizhang82/corefx,nchikanov/corefx,jlin177/corefx,ravimeda/corefx,MaggieTsang/corefx,JosephTremoulet/corefx,billwert/corefx,mmitche/corefx,yizhang82/corefx,tijoytom/corefx,Petermarcu/corefx,dhoehna/corefx,seanshpark/corefx,cydhaselton/corefx,alexperovich/corefx,richlander/corefx,MaggieTsang/corefx,richlander/corefx,stone-li/corefx,richlander/corefx,stone-li/corefx,alexperovich/corefx,mazong1123/corefx,Ermiar/corefx,ptoonen/corefx,twsouthwick/corefx,nbarbettini/corefx,nbarbettini/corefx,mmitche/corefx,jlin177/corefx,zhenlan/corefx,MaggieTsang/corefx,nchikanov/corefx,twsouthwick/corefx,mmitche/corefx,rahku/corefx,Ermiar/corefx,Ermiar/corefx,nchikanov/corefx,shimingsg/corefx,cydhaselton/corefx,fgreinacher/corefx,DnlHarvey/corefx,weltkante/corefx,twsouthwick/corefx,alexperovich/corefx,stephenmichaelf/corefx,billwert/corefx,alexperovich/corefx,dotnet-bot/corefx,YoupHulsebos/corefx,the-dwyer/corefx,DnlHarvey/corefx,JosephTremoulet/corefx,krk/corefx,the-dwyer/corefx,rubo/corefx,jlin177/corefx,rahku/corefx,Petermarcu/corefx,jlin177/corefx,DnlHarvey/corefx,gkhanna79/corefx,Jiayili1/corefx,mazong1123/corefx,ravimeda/corefx,the-dwyer/corefx,cydhaselton/corefx,weltkante/corefx,wtgodbe/corefx,jlin177/corefx,yizhang82/corefx,ravimeda/corefx,stephenmichaelf/corefx,MaggieTsang/corefx,Jiayili1/corefx,dotnet-bot/corefx,dhoehna/corefx,gkhanna79/corefx,parjong/corefx,nbarbettini/corefx,wtgodbe/corefx,seanshpark/corefx,dhoehna/corefx,ericstj/corefx,weltkante/corefx,ericstj/corefx,dhoehna/corefx,JosephTremoulet/corefx,ViktorHofer/corefx,rahku/corefx,Petermarcu/corefx,shimingsg/corefx,nbarbettini/corefx,krytarowski/corefx,parjong/corefx,yizhang82/corefx,cydhaselton/corefx,gkhanna79/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx,DnlHarvey/corefx,ptoonen/corefx,krk/corefx,richlander/corefx,parjong/corefx,nbarbettini/corefx,stone-li/corefx,YoupHulsebos/corefx,BrennanConroy/corefx,rjxby/corefx,ravimeda/corefx,rjxby/corefx,cydhaselton/corefx,billwert/corefx,the-dwyer/corefx,billwert/corefx,parjong/corefx,nchikanov/corefx,fgreinacher/corefx,alexperovich/corefx,jlin177/corefx,stephenmichaelf/corefx,rubo/corefx,mazong1123/corefx,twsouthwick/corefx,elijah6/corefx,cydhaselton/corefx,krk/corefx,seanshpark/corefx,shimingsg/corefx,krytarowski/corefx,weltkante/corefx,twsouthwick/corefx,seanshpark/corefx,ViktorHofer/corefx,rjxby/corefx,ravimeda/corefx,mazong1123/corefx,tijoytom/corefx,stone-li/corefx,wtgodbe/corefx
src/System.Net.Primitives/tests/FunctionalTests/SerializationTest.cs
src/System.Net.Primitives/tests/FunctionalTests/SerializationTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Net.Primitives.Functional.Tests { public static class SerializationTest { public static IEnumerable<object[]> SerializeDeserialize_Roundtrip_MemberData() { yield return new object[] { IPAddress.Parse("127.0.0.1") }; yield return new object[] { new IPEndPoint(IPAddress.Loopback, 12345) }; yield return new object[] { new Cookie("somekey", "somevalue") }; yield return new object[] { new CookieCollection() { new Cookie("somekey", "somevalue") } }; } [Theory] [MemberData(nameof(SerializeDeserialize_Roundtrip_MemberData))] public static void SerializeDeserialize_Roundtrip_EqualObjects(object obj) { Assert.Equal(obj, BinaryFormatterHelpers.Clone(obj)); } [Fact] public static void SerializeDeserialize_CookieContainerRoundtrip_EqualValues() { CookieContainer cookies1 = new CookieContainer(); CookieContainer cookies2 = BinaryFormatterHelpers.Clone(cookies1); Assert.Equal(cookies1.Capacity, cookies2.Capacity); Assert.Equal(cookies1.Count, cookies2.Count); Assert.Equal(cookies1.MaxCookieSize, cookies2.MaxCookieSize); Assert.Equal(cookies1.PerDomainCapacity, cookies2.PerDomainCapacity); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Tests; using Xunit; namespace System.Net.Primitives.Functional.Tests { public static class SerializationTest { public static IEnumerable<object[]> SerializeDeserialize_Roundtrip_MemberData() { yield return new object[] { IPAddress.Parse("127.0.0.1") }; yield return new object[] { new IPEndPoint(IPAddress.Loopback, 12345) }; yield return new object[] { new Cookie("somekey", "somevalue") }; yield return new object[] { new CookieCollection() { new Cookie("somekey", "somevalue") } }; } [Theory] [MemberData(nameof(SerializeDeserialize_Roundtrip_MemberData))] public static void SerializeDeserialize_Roundtrip(object obj) { Assert.Equal(obj, BinaryFormatterHelpers.Clone(obj)); } } }
mit
C#
c463a8b15b364df3e5307733da71fab708462048
Refactor to make asynch callback functions exception safe
RoyalVeterinaryCollege/VetCompassClient
clr/VetCompassClient/RequestHelper.cs
clr/VetCompassClient/RequestHelper.cs
#if NET35 using System; using System.IO; using System.Net; using System.Threading.Tasks; namespace VetCompass.Client { /// <summary> /// This backports some methods on WebRequest available in .net 4.5 into .net 3.5 /// </summary> public static class RequestHelper { /// <summary> /// This back ports the asynch upload method from .net 4.5 to .net 3.5 /// </summary> /// <param name="request"></param> /// <returns></returns> public static Task<Stream> GetRequestStreamAsync(this WebRequest request) { //function taking an completed asynch callback to create an upload stream, and returns that stream Func<IAsyncResult, WebRequest> f = asynchResult => { var intialRequest = (WebRequest) asynchResult.AsyncState; return intialRequest; }; return Task.Factory .FromAsync(request.BeginGetRequestStream, f, request) .MapSuccess(initialRequest => initialRequest.GetRequestStream()); //do the request inside a task to prevent exceptions taking down the appdomain } /// <summary> /// This back ports the asynch response method from .net 4.5 to .net 3.5 /// </summary> /// <param name="request"></param> /// <returns></returns> public static Task<WebResponse> GetResponseAsync(this WebRequest request) { //function taking an completed asynch callback which represents a completed request and gets that request Func<IAsyncResult, WebRequest> f = asynchResult => { var intialRequest = (WebRequest)asynchResult.AsyncState; return intialRequest; }; return Task.Factory .FromAsync(request.BeginGetResponse, f, request) .MapSuccess(completedRequest => request.GetResponse()); //second task gets the response. It's done in a second task as GetResponse can actually throw an error, and we want this to happen inside a task (rather than in the callback which will take down the appdomain!) } } } #endif
#if NET35 using System; using System.IO; using System.Net; using System.Threading.Tasks; namespace VetCompass.Client { /// <summary> /// This backports some methods on WebRequest available in .net 4.5 into .net 3.5 /// </summary> public static class RequestHelper { /// <summary> /// This back ports the asynch upload method from .net 4.5 to .net 3.5 /// </summary> /// <param name="request"></param> /// <returns></returns> public static Task<Stream> GetRequestStreamAsync(this WebRequest request) { //function taking an completed asynch callback to create an upload stream, and returns that stream Func<IAsyncResult, Stream> f = asynchResult => { var intialRequest = (WebRequest) asynchResult.AsyncState; return intialRequest.GetRequestStream(); }; return Task.Factory.FromAsync(request.BeginGetRequestStream, f, request); } /// <summary> /// This back ports the asynch response method from .net 4.5 to .net 3.5 /// </summary> /// <param name="request"></param> /// <returns></returns> public static Task<WebResponse> GetResponseAsync(this WebRequest request) { //function taking an completed asynch callback to create an upload stream, and returns that stream Func<IAsyncResult, WebResponse> f = asynchResult => { var intialRequest = (WebRequest)asynchResult.AsyncState; return intialRequest.GetResponse(); }; return Task.Factory.FromAsync(request.BeginGetResponse, f, request); } } } #endif
mit
C#
382a4af4f1a1d057077c69eb37026545910b966e
Fix GlobalCleanupAttributeTest.GlobalCleanupMethodRunsTest (#894)
ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet
tests/BenchmarkDotNet.IntegrationTests/GlobalCleanupAttributeTest.cs
tests/BenchmarkDotNet.IntegrationTests/GlobalCleanupAttributeTest.cs
using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Tests.Loggers; using Xunit; using Xunit.Abstractions; namespace BenchmarkDotNet.IntegrationTests { public class GlobalCleanupAttributeTest : BenchmarkTestExecutor { private const string GlobalCleanupCalled = "// ### GlobalCleanup called ###"; private const string BenchmarkCalled = "// ### Benchmark called ###"; public GlobalCleanupAttributeTest(ITestOutputHelper output) : base(output) { } [Fact] public void GlobalCleanupMethodRunsTest() { var logger = new OutputLogger(Output); var config = CreateSimpleConfig(logger); CanExecute<GlobalCleanupAttributeBenchmarks>(config); string log = logger.GetLog(); Assert.Contains(BenchmarkCalled + System.Environment.NewLine, log); Assert.True( log.IndexOf(BenchmarkCalled + System.Environment.NewLine) < log.IndexOf(GlobalCleanupCalled + System.Environment.NewLine)); } public class GlobalCleanupAttributeBenchmarks { [Benchmark] public void Benchmark() { Console.WriteLine(BenchmarkCalled); } [GlobalCleanup] public void GlobalCleanup() { Console.WriteLine(GlobalCleanupCalled); } } } }
using System; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Tests.Loggers; using Xunit; using Xunit.Abstractions; namespace BenchmarkDotNet.IntegrationTests { public class GlobalCleanupAttributeTest : BenchmarkTestExecutor { private const string GlobalCleanupCalled = "// ### GlobalCleanup called ###"; private const string BenchmarkCalled = "// ### Benchmark called ###"; public GlobalCleanupAttributeTest(ITestOutputHelper output) : base(output) { } [Fact] public void GlobalCleanupMethodRunsTest() { var logger = new OutputLogger(Output); var config = CreateSimpleConfig(logger); CanExecute<GlobalCleanupAttributeBenchmarks>(config); string log = logger.GetLog(); Assert.Contains(GlobalCleanupCalled + System.Environment.NewLine, log); Assert.True( log.IndexOf(GlobalCleanupCalled + System.Environment.NewLine) > log.IndexOf(BenchmarkCalled + System.Environment.NewLine)); } public class GlobalCleanupAttributeBenchmarks { [Benchmark] public void Benchmark() { Console.WriteLine(BenchmarkCalled); } [GlobalCleanup] public void GlobalCleanup() { Console.WriteLine(GlobalCleanupCalled); } } } }
mit
C#
3f432bdf5e7896f8b73da63b0c89f183d6407ab8
add usage attribute to HeadOptions
Thilas/commandline,anthonylangsworth/commandline,Thilas/commandline,anthonylangsworth/commandline
demo/ReadText.Demo/Options.cs
demo/ReadText.Demo/Options.cs
using CommandLine; using CommandLine.Text; using System.Collections.Generic; namespace ReadText.Demo { interface IOptions { [Option('n', "lines", Default = 5U, SetName = "bylines", HelpText = "Lines to be printed from the beginning or end of the file.")] uint? Lines { get; set; } [Option('c', "bytes", SetName = "bybytes", HelpText = "Bytes to be printed from the beginning or end of the file.")] uint? Bytes { get; set; } [Option('q', "quiet", HelpText = "Supresses summary messages.")] bool Quiet { get; set; } [Value(0, MetaName = "input file", HelpText = "Input file to be processed.", Required = true)] string FileName { get; set; } } [Verb("head", HelpText = "Displays first lines of a file.")] class HeadOptions : IOptions { public uint? Lines { get; set; } public uint? Bytes { get; set; } public bool Quiet { get; set; } public string FileName { get; set; } [Usage(ApplicationAlias = "ReadText.Demo.exe")] public static IEnumerable<Example> Examples { get { yield return new Example("normal scenario", new HeadOptions { FileName = "file.bin"}); yield return new Example("specify bytes", new HeadOptions { FileName = "file.bin", Bytes=100 }); yield return new Example("supress summary", UnParserSettings.WithGroupSwitchesOnly(), new HeadOptions { FileName = "file.bin", Quiet = true }); yield return new Example("read more lines", new[] { UnParserSettings.WithGroupSwitchesOnly(), UnParserSettings.WithUseEqualTokenOnly() }, new HeadOptions { FileName = "file.bin", Lines = 10 }); } } } [Verb("tail", HelpText = "Displays last lines of a file.")] class TailOptions : IOptions { public uint? Lines { get; set; } public uint? Bytes { get; set; } public bool Quiet { get; set; } public string FileName { get; set; } } }
using CommandLine; namespace ReadText.Demo { interface IOptions { [Option('n', "lines", Default = 5U, SetName = "bylines", HelpText = "Lines to be printed from the beginning or end of the file.")] uint? Lines { get; set; } [Option('c', "bytes", SetName = "bybytes", HelpText = "Bytes to be printed from the beginning or end of the file.")] uint? Bytes { get; set; } [Option('q', "quiet", HelpText = "Supresses summary messages.")] bool Quiet { get; set; } [Value(0, MetaName = "input file", HelpText = "Input file to be processed.", Required = true)] string FileName { get; set; } } [Verb("head", HelpText = "Displays first lines of a file.")] class HeadOptions : IOptions { public uint? Lines { get; set; } public uint? Bytes { get; set; } public bool Quiet { get; set; } public string FileName { get; set; } } [Verb("tail", HelpText = "Displays last lines of a file.")] class TailOptions : IOptions { public uint? Lines { get; set; } public uint? Bytes { get; set; } public bool Quiet { get; set; } public string FileName { get; set; } } }
mit
C#
1b8d034f53363ff2cf392df4689e7f24426a8e49
Support list of hints per problem
Kakarot/CITS
CITS/Models/MathProblemModel.cs
CITS/Models/MathProblemModel.cs
using System; using System.Collections.Generic; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string problem, string solution, List<String> listOfHints):base(problem,solution, listOfHints){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } }
using System; namespace CITS.Models { public class MathProblemModel : ProblemModel { public MathProblemModel(string Problem, string Solution):base(Problem,Solution){} public override Boolean IsSolutionCorrect(String candidateSolution) { return Solution.Equals(candidateSolution.Trim()); } } }
mit
C#
6571477e436181cca7a54bbeeb33fc9b7a151e8b
Clean up Assembly Info
jcolag/CreditCardValidator
CreditCardRange/CreditCardRange/Properties/AssemblyInfo.cs
CreditCardRange/CreditCardRange/Properties/AssemblyInfo.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.cs" company="Colagioia Industries"> // Provided under the terms of the AGPL v3. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("CreditCardRange")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("john")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. // [assembly: AssemblyDelaySign(false)] // [assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("CreditCardRange")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("john")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
agpl-3.0
C#
a766f08c22ff6b4afaced2daa06d7c2edda4d4cc
Update sys version to v2.0-a4 #280
FanrayMedia/Fanray,FanrayMedia/Fanray,FanrayMedia/Fanray
src/Fan/Helpers/SysVersion.cs
src/Fan/Helpers/SysVersion.cs
namespace Fan.Helpers { public class SysVersion { public static string CurrentVersion = "v2.0-a4"; } }
namespace Fan.Helpers { public class SysVersion { public static string CurrentVersion = "v2.0-a3"; } }
apache-2.0
C#
799aa76f5c397b924e188b6a2fdc667a24785651
add field indexers to the Record
mvbalaw/EtlGate,mvbalaw/EtlGate,mvbalaw/EtlGate
src/EtlGate.Core/Record.cs
src/EtlGate.Core/Record.cs
using System; using System.Collections.Generic; using System.Linq; namespace EtlGate.Core { public class Record { public const string ErrorFieldIndexMustBeNonNegativeMessage = "field index must be >= 0."; public const string ErrorFieldNameIsNotAValidHeaderForThisRecordMessage = " is not a valid header for this record."; private readonly IList<string> _fields; private readonly IDictionary<string, int> _headings; public Record(params string[] fields) : this(fields, new Dictionary<string, int>()) { } public Record(IList<string> fields, IDictionary<string, int> headings) { _fields = fields; _headings = headings; } public int FieldCount { get { return _fields.Count; } } public IList<string> HeadingFieldNames { get { return _headings.Keys.ToList(); } } public string this[string name] { get { return GetField(name); } } public string this[int zeroBasedIndex] { get { return GetField(zeroBasedIndex); } } public string GetField(string name) { return GetField(GetFieldIndex(name)); } public string GetField(int zeroBasedIndex) { return HasField(zeroBasedIndex) ? _fields[zeroBasedIndex] : null; } private int GetFieldIndex(string name) { int zeroBasedIndex; if (!_headings.TryGetValue(name, out zeroBasedIndex)) { throw new ArgumentException(name + ErrorFieldNameIsNotAValidHeaderForThisRecordMessage, "name"); } return zeroBasedIndex; } public bool HasField(int zeroBasedIndex) { if (zeroBasedIndex < 0) { throw new ArgumentOutOfRangeException("zeroBasedIndex", ErrorFieldIndexMustBeNonNegativeMessage); } return zeroBasedIndex < _fields.Count; } public bool HasField(string name) { var zeroBasedIndex = GetFieldIndex(name); return HasField(zeroBasedIndex); } } }
using System; using System.Collections.Generic; using System.Linq; namespace EtlGate.Core { public class Record { public const string ErrorFieldIndexMustBeNonNegativeMessage = "field index must be >= 0."; public const string ErrorFieldNameIsNotAValidHeaderForThisRecordMessage = " is not a valid header for this record."; private readonly IList<string> _fields; private readonly IDictionary<string, int> _headings; public Record(params string[] fields) : this(fields, new Dictionary<string, int>()) { } public Record(IList<string> fields, IDictionary<string, int> headings) { _fields = fields; _headings = headings; } public int FieldCount { get { return _fields.Count; } } public IList<string> HeadingFieldNames { get { return _headings.Keys.ToList(); } } public string GetField(string name) { return GetField(GetFieldIndex(name)); } public string GetField(int zeroBasedIndex) { return HasField(zeroBasedIndex) ? _fields[zeroBasedIndex] : null; } private int GetFieldIndex(string name) { int zeroBasedIndex; if (!_headings.TryGetValue(name, out zeroBasedIndex)) { throw new ArgumentException(name + ErrorFieldNameIsNotAValidHeaderForThisRecordMessage, "name"); } return zeroBasedIndex; } public bool HasField(int zeroBasedIndex) { if (zeroBasedIndex < 0) { throw new ArgumentOutOfRangeException("zeroBasedIndex", ErrorFieldIndexMustBeNonNegativeMessage); } return zeroBasedIndex < _fields.Count; } public bool HasField(string name) { var zeroBasedIndex = GetFieldIndex(name); return HasField(zeroBasedIndex); } } }
mit
C#
c5e5c5328d5d048bc329c2e74d9325a7cd059a63
remove early Dispose() cleanup, to avoid a warning message from our cleanup system, see bug #6045
mono/maccore,jorik041/maccore,cwensley/maccore
src/Foundation/NSAction.cs
src/Foundation/NSAction.cs
// // Copyright 2009-2010, Novell, Inc. // Copyright 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public delegate void NSAction (); // Use this for synchronous operations [Register ("__MonoMac_NSActionDispatcher")] internal class NSActionDispatcher : NSObject { public static Selector Selector = new Selector ("apply"); NSAction action; public NSActionDispatcher (NSAction action) { this.action = action; } [Export ("apply")] [Preserve (Conditional = true)] public void Apply () { action (); } } // Use this for asynchronous operations [Register ("__MonoMac_NSAsyncActionDispatcher")] internal class NSAsyncActionDispatcher : NSObject { GCHandle gch; NSAction action; // This ctor is so that the runtime can create a new instance of this class // if ObjC wants to call release on an instance we've already called Dispose on. // Since we detach the handle from the managed instance when Dispose is called, // there is no way we can get the existing managed instance (which has possibly // been freed anyway) when ObjC calls release (which ends up in NSObject.NativeRelease). [Obsolete ("Do not use, this method is only used internally")] public NSAsyncActionDispatcher (IntPtr handle) : base (handle) { } public NSAsyncActionDispatcher (NSAction action) { this.action = action; gch = GCHandle.Alloc (this); } [Export ("apply")] [Preserve (Conditional = true)] public void Apply () { try { action (); } finally { action = null; // this is a one-shot dispatcher gch.Free (); // // Although I would like to call Dispose here, to // reduce the load on the GC, we have some useful diagnostic // code in our runtime that is useful to track down // problems, so we are removing the Dispose and letting // the GC and our pipeline do their job. // } } } }
// // Copyright 2009-2010, Novell, Inc. // Copyright 2012 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.InteropServices; using MonoMac.ObjCRuntime; namespace MonoMac.Foundation { public delegate void NSAction (); // Use this for synchronous operations [Register ("__MonoMac_NSActionDispatcher")] internal class NSActionDispatcher : NSObject { public static Selector Selector = new Selector ("apply"); NSAction action; public NSActionDispatcher (NSAction action) { this.action = action; } [Export ("apply")] [Preserve (Conditional = true)] public void Apply () { action (); } } // Use this for asynchronous operations [Register ("__MonoMac_NSAsyncActionDispatcher")] internal class NSAsyncActionDispatcher : NSObject { GCHandle gch; NSAction action; // This ctor is so that the runtime can create a new instance of this class // if ObjC wants to call release on an instance we've already called Dispose on. // Since we detach the handle from the managed instance when Dispose is called, // there is no way we can get the existing managed instance (which has possibly // been freed anyway) when ObjC calls release (which ends up in NSObject.NativeRelease). [Obsolete ("Do not use")] public NSAsyncActionDispatcher (IntPtr handle) : base (handle) { } public NSAsyncActionDispatcher (NSAction action) { this.action = action; gch = GCHandle.Alloc (this); } [Export ("apply")] [Preserve (Conditional = true)] public void Apply () { try { action (); } finally { action = null; // this is a one-shot dispatcher gch.Free (); Dispose (); } } } }
apache-2.0
C#
12db483273a721da2d7d3d4b71d04e2bd57a561f
Fix unit tests
basho/riak-dotnet-client,rob-somerville/riak-dotnet-client,rob-somerville/riak-dotnet-client,basho/riak-dotnet-client
src/RiakClient/Models/NVal.cs
src/RiakClient/Models/NVal.cs
// <copyright file="NVal.cs" company="Basho Technologies, Inc."> // Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka // Copyright (c) 2014 - Basho Technologies, Inc. // // This file is provided to you 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. // </copyright> namespace RiakClient.Models { using System; public class NVal : IEquatable<NVal> { private readonly uint nval = 0; public NVal(int nval) { if (nval <= 0) { throw new ArgumentOutOfRangeException("nval must be greater than zero"); } this.nval = (uint)nval; } internal NVal(uint nval) { this.nval = nval; } public static explicit operator NVal(int nval) { return new NVal(nval); } public static explicit operator int(NVal nval) { return (int)nval.nval; } [CLSCompliant(false)] public static implicit operator uint(NVal nval) { return nval.nval; } public override bool Equals(object obj) { return Equals(obj as NVal); } public bool Equals(NVal other) { if (object.ReferenceEquals(other, null)) { return false; } if (object.ReferenceEquals(other, this)) { return true; } return this.GetHashCode() == other.GetHashCode(); } public override int GetHashCode() { return nval.GetHashCode(); } } }
// <copyright file="NVal.cs" company="Basho Technologies, Inc."> // Copyright (c) 2011 - OJ Reeves & Jeremiah Peschka // Copyright (c) 2014 - Basho Technologies, Inc. // // This file is provided to you 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. // </copyright> namespace RiakClient.Models { using System; public class NVal : IEquatable<NVal> { private readonly uint nval = 0; public NVal(int nval) : this((uint)nval) { } internal NVal(uint nval) { if (nval <= 0) { throw new ArgumentOutOfRangeException("nval must be greater than zero"); } this.nval = (uint)nval; } public static explicit operator NVal(int nval) { return new NVal(nval); } public static explicit operator int(NVal nval) { return (int)nval.nval; } [CLSCompliant(false)] public static implicit operator uint(NVal nval) { return nval.nval; } public override bool Equals(object obj) { return Equals(obj as NVal); } public bool Equals(NVal other) { if (object.ReferenceEquals(other, null)) { return false; } if (object.ReferenceEquals(other, this)) { return true; } return this.GetHashCode() == other.GetHashCode(); } public override int GetHashCode() { return nval.GetHashCode(); } } }
apache-2.0
C#
e76a61e1378d8726c76fd72f4af1abd850ef8674
Update TypeCatalogParser for CoreConsoleHost removal
kmosher/PowerShell,bmanikm/PowerShell,KarolKaczmarek/PowerShell,bmanikm/PowerShell,jsoref/PowerShell,JamesWTruher/PowerShell-1,kmosher/PowerShell,JamesWTruher/PowerShell-1,PaulHigin/PowerShell,TravisEz13/PowerShell,TravisEz13/PowerShell,kmosher/PowerShell,bmanikm/PowerShell,KarolKaczmarek/PowerShell,PaulHigin/PowerShell,KarolKaczmarek/PowerShell,jsoref/PowerShell,TravisEz13/PowerShell,bmanikm/PowerShell,bingbing8/PowerShell,PaulHigin/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,daxian-dbw/PowerShell,jsoref/PowerShell,JamesWTruher/PowerShell-1,KarolKaczmarek/PowerShell,bingbing8/PowerShell,bingbing8/PowerShell,jsoref/PowerShell,daxian-dbw/PowerShell,daxian-dbw/PowerShell,daxian-dbw/PowerShell,kmosher/PowerShell,TravisEz13/PowerShell,bmanikm/PowerShell,jsoref/PowerShell,bingbing8/PowerShell,JamesWTruher/PowerShell-1,bingbing8/PowerShell,PaulHigin/PowerShell
src/TypeCatalogParser/Main.cs
src/TypeCatalogParser/Main.cs
using System; using System.IO; using System.Linq; using NuGet.Frameworks; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.Extensions.DependencyModel.Resolution; namespace TypeCatalogParser { public class Program { public static void Main(string[] args) { // The TypeCatalogGen project takes this as input var outputPath = "../TypeCatalogGen/powershell.inc"; // Get a context for our top level project var context = ProjectContext.Create("../powershell", NuGetFramework.Parse("netcoreapp1.0")); System.IO.File.WriteAllLines(outputPath, // Get the target for the current runtime from t in context.LockFile.Targets where t.RuntimeIdentifier == Constants.RuntimeIdentifier // Get the packages (not projects) from x in t.Libraries where x.Type == "package" // Get the real reference assemblies from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll") // Construct the path to the assemblies select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};"); Console.WriteLine($"List of reference assemblies written to {outputPath}"); } } }
using System; using System.IO; using System.Linq; using NuGet.Frameworks; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.Extensions.DependencyModel.Resolution; namespace ConsoleApplication { public class Program { public static void Main(string[] args) { // The TypeCatalogGen project takes this as input var outputPath = "../TypeCatalogGen/powershell.inc"; // Get a context for our top level project var context = ProjectContext.Create("../Microsoft.PowerShell.CoreConsoleHost", NuGetFramework.Parse("netcoreapp1.0")); System.IO.File.WriteAllLines(outputPath, // Get the target for the current runtime from t in context.LockFile.Targets where t.RuntimeIdentifier == Constants.RuntimeIdentifier // Get the packages (not projects) from x in t.Libraries where x.Type == "package" // Get the real reference assemblies from y in x.CompileTimeAssemblies where y.Path.EndsWith(".dll") // Construct the path to the assemblies select $"{context.PackagesDirectory}/{x.Name}/{x.Version}/{y.Path};"); Console.WriteLine($"List of reference assemblies written to {outputPath}"); } } }
mit
C#
09c154bbcd027a36ccc94998206a30101d8796c8
Solve build related issue
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> [Route("single-multiple-question")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [Route("single-multiple-question")] [HttpPost] /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
0c3967f172227b4d55edf70e7f45e76512ba2062
Make test independent from dll version
WaltChen/NDatabase,WaltChen/NDatabase
tests/NDatabase.UnitTests/Layer2/When_we_use_class_info.cs
tests/NDatabase.UnitTests/Layer2/When_we_use_class_info.cs
using NDatabase.Odb.Core.Layers.Layer2.Meta; using NDatabase.Tool.Wrappers; using NUnit.Framework; namespace NDatabase.UnitTests.Layer2 { internal class When_we_use_class_info { private class Country { private readonly string _name; public Country(string name, int population, string continent) { _name = name; Population = population; Continent = continent; } public string Name { get { return _name; } } public int Population { get; set; } public virtual string Continent { get; private set; } } [Test] public void It_should_have_set_proper_base_settings() { var classInfo = new ClassInfo(typeof (Country)); Assert.That(classInfo.ClassCategory, Is.EqualTo(ClassInfo.CategoryUserClass)); Assert.That(classInfo.UnderlyingType, Is.EqualTo(typeof(Country))); Assert.That(classInfo.FullClassName, Is.EqualTo(OdbClassUtil.GetFullName(typeof(Country)))); Assert.That(classInfo.Position, Is.EqualTo(-1)); Assert.That(classInfo.MaxAttributeId, Is.EqualTo(-1)); Assert.That(classInfo.ClassInfoId, Is.Null); } [Test] public void It_should_have_meaningful_default_string_representation() { var classInfo = new ClassInfo(typeof(Country)); Assert.That(classInfo.ToString(), Is.StringEnding( "- id= - previousClass= - nextClass= - attributes=(not yet defined) ]")); } } }
using NDatabase.Odb.Core.Layers.Layer2.Meta; using NDatabase.Tool.Wrappers; using NUnit.Framework; namespace NDatabase.UnitTests.Layer2 { internal class When_we_use_class_info { private class Country { private readonly string _name; public Country(string name, int population, string continent) { _name = name; Population = population; Continent = continent; } public string Name { get { return _name; } } public int Population { get; set; } public virtual string Continent { get; private set; } } [Test] public void It_should_have_set_proper_base_settings() { var classInfo = new ClassInfo(typeof (Country)); Assert.That(classInfo.ClassCategory, Is.EqualTo(ClassInfo.CategoryUserClass)); Assert.That(classInfo.UnderlyingType, Is.EqualTo(typeof(Country))); Assert.That(classInfo.FullClassName, Is.EqualTo(OdbClassUtil.GetFullName(typeof(Country)))); Assert.That(classInfo.Position, Is.EqualTo(-1)); Assert.That(classInfo.MaxAttributeId, Is.EqualTo(-1)); Assert.That(classInfo.ClassInfoId, Is.Null); } [Test] public void It_should_have_meaningful_default_string_representation() { var classInfo = new ClassInfo(typeof(Country)); Assert.That(classInfo.ToString(), Is.EqualTo( " [ NDatabase.UnitTests.Layer2.When_we_use_class_info+Country,NDatabase.UnitTests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0c7aa341ab3f9c12 - id= - previousClass= - nextClass= - attributes=(not yet defined) ]")); } } }
apache-2.0
C#
bce1a002465e67c1f00182b71ac3747d74b558a5
Update Occupation.cs (#947)
vknet/vk,vknet/vk
VkNet/Model/Occupation.cs
VkNet/Model/Occupation.cs
using System; using Newtonsoft.Json; using VkNet.Enums.SafetyEnums; using VkNet.Utils; using VkNet.Utils.JsonConverter; namespace VkNet.Model { /// <summary> /// Информация о текущем роде занятия пользователя. /// </summary> [Serializable] public class Occupation { /// <summary> /// Название школы, вуза или места работы /// </summary> public string Name { get; set; } /// <summary> /// Идентификатор школы, вуза, группы компании (в которой пользователь работает). /// </summary> public long? Id { get; set; } /// <summary> /// Информация о текущем роде занятия пользователя. /// </summary> [JsonConverter(typeof(SafetyEnumJsonConverter))] public OccupationType Type { get; set; } /// <summary> /// Разобрать из json. /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns> </returns> public static Occupation FromJson(VkResponse response) { var occupation = new Occupation { Id = response[key: "id"] , Name = response[key: "name"] , Type = response[key: "type"] }; return occupation; } } }
using System; using Newtonsoft.Json; using VkNet.Enums.SafetyEnums; using VkNet.Utils; using VkNet.Utils.JsonConverter; namespace VkNet.Model { /// <summary> /// Информация о текущем роде занятия пользователя. /// </summary> [Serializable] public class Occupation { /// <summary> /// Название школы, вуза или места работы /// </summary> public string Name { get; set; } /// <summary> /// Идентификатор школы, вуза, группы компании (в которой пользователь работает). /// </summary> public long Id { get; set; } /// <summary> /// Информация о текущем роде занятия пользователя. /// </summary> [JsonConverter(typeof(SafetyEnumJsonConverter))] public OccupationType Type { get; set; } /// <summary> /// Разобрать из json. /// </summary> /// <param name="response"> Ответ сервера. </param> /// <returns> </returns> public static Occupation FromJson(VkResponse response) { var occupation = new Occupation { Id = response[key: "id"] , Name = response[key: "name"] , Type = response[key: "type"] }; return occupation; } } }
mit
C#
4985332ee2298709b782025c221628f8b663288a
Disable the disable mouse script for now
mherbold/starflight,mherbold/starflight,mherbold/starflight
Assets/General/Scripts/DisableMouse.cs
Assets/General/Scripts/DisableMouse.cs
 using UnityEngine; using UnityEngine.EventSystems; class DisableMouse : MonoBehaviour { // private stuff we don't want the editor to see private GameObject m_lastSelectedGameObject; // this is called by unity before start void Awake() { m_lastSelectedGameObject = new GameObject(); } // this is called by unity every frame void Update() { // check if we have an active ui if ( false && ( EventSystem.current != null ) ) { // check if we have a currently selected game object if ( EventSystem.current.currentSelectedGameObject == null ) { // nope - the mouse may have stolen it - give it back to the last selected game object EventSystem.current.SetSelectedGameObject( m_lastSelectedGameObject ); } else if ( EventSystem.current.currentSelectedGameObject != m_lastSelectedGameObject ) { // we changed our selection - remember it m_lastSelectedGameObject = EventSystem.current.currentSelectedGameObject; } } } }
 using UnityEngine; using UnityEngine.EventSystems; class DisableMouse : MonoBehaviour { // private stuff we don't want the editor to see private GameObject m_lastSelectedGameObject; // this is called by unity before start void Awake() { m_lastSelectedGameObject = new GameObject(); } // this is called by unity every frame void Update() { // check if we have an active ui if ( EventSystem.current != null ) { // check if we have a currently selected game object if ( EventSystem.current.currentSelectedGameObject == null ) { // nope - the mouse may have stolen it - give it back to the last selected game object EventSystem.current.SetSelectedGameObject( m_lastSelectedGameObject ); } else if ( EventSystem.current.currentSelectedGameObject != m_lastSelectedGameObject ) { // we changed our selection - remember it m_lastSelectedGameObject = EventSystem.current.currentSelectedGameObject; } } } }
unlicense
C#
10114fb952c4ea5a486a04d839ffe50960f404e3
Update interface for return type
techphernalia/MyPersonalAccounts
MyPersonalAccountsModel/Controller/IInventoryController.cs
MyPersonalAccountsModel/Controller/IInventoryController.cs
using com.techphernalia.MyPersonalAccounts.Model.Inventory; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace com.techphernalia.MyPersonalAccounts.Model.Controller { public interface IInventoryController { #region Stock Unit List<StockUnit> GetAllStockUnits(); StockUnit GetStockUnitFromId(int unitId); int AddStockUnit(StockUnit stockUnit); void UpdateStockUnit(StockUnit stockUnit); void DeleteStockUnit(int unitId); #endregion #region Stock Group List<StockGroup> GetAllStockGroups(); List<StockGroup> GetStockGroupsForGroup(int stockGroupId); StockGroup GetStockGroupFromId(int stockGroupId); int AddStockGroup(StockItem stockItem); bool UpdateStockGroup(StockItem stockItem); bool DeleteStockGroup(int stockGroupId); #endregion #region Stock Item List<StockItem> GetAllStockItems(); List<StockItem> GetStockItemsForGroup(int stockGroupId); StockItem GetStockItemFromId(int stockItemId); int AddStockItem(StockGroup stockGroup); bool UpdateStockItem(StockGroup stockGroup); bool DeleteStockItemI(int stockItemId); #endregion } }
using com.techphernalia.MyPersonalAccounts.Model.Inventory; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace com.techphernalia.MyPersonalAccounts.Model.Controller { public interface IInventoryController { #region Stock Unit List<StockUnit> GetAllStockUnits(); StockUnit GetStockUnitFromId(int unitId); int AddStockUnit(StockUnit stockUnit); bool UpdateStockUnit(StockUnit stockUnit); bool DeleteStockUnit(int unitId); #endregion #region Stock Group List<StockGroup> GetAllStockGroups(); List<StockGroup> GetStockGroupsForGroup(int stockGroupId); StockGroup GetStockGroupFromId(int stockGroupId); int AddStockGroup(StockItem stockItem); bool UpdateStockGroup(StockItem stockItem); bool DeleteStockGroup(int stockGroupId); #endregion #region Stock Item List<StockItem> GetAllStockItems(); List<StockItem> GetStockItemsForGroup(int stockGroupId); StockItem GetStockItemFromId(int stockItemId); int AddStockItem(StockGroup stockGroup); bool UpdateStockItem(StockGroup stockGroup); bool DeleteStockItemI(int stockItemId); #endregion } }
mit
C#
277808a4edaeeaffccf9c9c97402e5edf3521235
add null check
fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Items/Others/RandomItemSpot.cs
UnityProject/Assets/Scripts/Items/Others/RandomItemSpot.cs
using System; using System.Collections.Generic; using Mirror; using UnityEngine; using Random = UnityEngine.Random; namespace Items { public class RandomItemSpot : NetworkBehaviour, IServerSpawn { [Tooltip("Amout of items we could get from this pool")] [SerializeField] private int lootCount = 1; [Tooltip("Should we spread the items in the tile once spawned?")][SerializeField] private bool fanOut = false; [Tooltip("List of possible pools of items to choose from")][SerializeField] private List<PoolData> poolList = null; private const int MaxAmountRolls = 5; public override void OnStartServer() { var registerTile = GetComponent<RegisterTile>(); registerTile.WaitForMatrixInit(RollRandomPool); } private void RollRandomPool(MatrixInfo matrixInfo) { for (int i = 0; i < lootCount; i++) { PoolData pool = null; // Roll attempt is a safe check in the case the mapper did tables with low % and we can't find // anything to spawn in 5 attempts int rollAttempt = 0; while (pool == null) { if (rollAttempt >= MaxAmountRolls) { break; } var tryPool = poolList.PickRandom(); if (DMMath.Prob(tryPool.Probability)) { pool = tryPool; } else { rollAttempt ++; } } if (pool == null) { return; } SpawnItems(pool); } Despawn.ServerSingle(gameObject); } private void SpawnItems(PoolData poolData) { var item = poolData.RandomItemPool.Pool.PickRandom(); var spread = fanOut ? Random.Range(-0.5f,0.5f) : (float?) null; if (!DMMath.Prob(item.Probability)) { return; } var maxAmt = Random.Range(1, item.MaxAmount+1); Spawn.ServerPrefab( item.Prefab, gameObject.RegisterTile().WorldPositionServer, count: maxAmt, scatterRadius: spread); } public void OnSpawnServer(SpawnInfo info) { if (info.SpawnType != SpawnType.Mapped) { OnStartServer(); } } } [Serializable] public class PoolData { [Tooltip("Probabilities of spawning from this pool when chosen")] [SerializeField][Range(0,100)] private int probability = 100; [Tooltip("The pool from which we will try to get items")] [SerializeField] private RandomItemPool randomItemPool = null; public int Probability => probability; public RandomItemPool RandomItemPool => randomItemPool; } }
using System; using System.Collections.Generic; using Mirror; using UnityEngine; using Random = UnityEngine.Random; namespace Items { public class RandomItemSpot : NetworkBehaviour, IServerSpawn { [Tooltip("Amout of items we could get from this pool")] [SerializeField] private int lootCount = 1; [Tooltip("Should we spread the items in the tile once spawned?")][SerializeField] private bool fanOut = false; [Tooltip("List of possible pools of items to choose from")][SerializeField] private List<PoolData> poolList = null; private const int MaxAmountRolls = 5; public override void OnStartServer() { var registerTile = GetComponent<RegisterTile>(); registerTile.WaitForMatrixInit(RollRandomPool); } private void RollRandomPool(MatrixInfo matrixInfo) { for (int i = 0; i < lootCount; i++) { PoolData pool = null; // Roll attempt is a safe check in the case the mapper did tables with low % and we can't find // anything to spawn in 5 attempts int rollAttempt = 0; while (pool == null) { if (rollAttempt >= MaxAmountRolls) { break; } var tryPool = poolList.PickRandom(); if (DMMath.Prob(tryPool.Probability)) { pool = tryPool; } else { rollAttempt ++; } } SpawnItems(pool); } Despawn.ServerSingle(gameObject); } private void SpawnItems(PoolData poolData) { var item = poolData.RandomItemPool.Pool.PickRandom(); var spread = fanOut ? Random.Range(-0.5f,0.5f) : (float?) null; if (!DMMath.Prob(item.Probability)) { return; } var maxAmt = Random.Range(1, item.MaxAmount+1); Spawn.ServerPrefab( item.Prefab, gameObject.RegisterTile().WorldPositionServer, count: maxAmt, scatterRadius: spread); } public void OnSpawnServer(SpawnInfo info) { if (info.SpawnType != SpawnType.Mapped) { OnStartServer(); } } } [Serializable] public class PoolData { [Tooltip("Probabilities of spawning from this pool when chosen")] [SerializeField][Range(0,100)] private int probability = 100; [Tooltip("The pool from which we will try to get items")] [SerializeField] private RandomItemPool randomItemPool = null; public int Probability => probability; public RandomItemPool RandomItemPool => randomItemPool; } }
agpl-3.0
C#
ba8fbeca63323e6e48cb3b6e1f1fa4987a1e26bb
Remove comment
tddbuddy/SpeedySqlLocalDb
source/TddBuddy.SpeedyLocalDb.EF.Example.Attachment/Context/AttachmentDbContext.cs
source/TddBuddy.SpeedyLocalDb.EF.Example.Attachment/Context/AttachmentDbContext.cs
using System.Data.Common; using System.Data.Entity; namespace TddBuddy.SpeedyLocalDb.EF.Example.Attachment.Context { public class AttachmentDbContext : DbContext { public AttachmentDbContext(DbConnection connection) : base(connection, false){ } public AttachmentDbContext() : base("AttachmentContext") { Database.SetInitializer<AttachmentDbContext>(null); } public IDbSet<Entities.Attachment> Attachments { get; set; } } }
using System.Data.Common; using System.Data.Entity; namespace TddBuddy.SpeedyLocalDb.EF.Example.Attachment.Context { public class AttachmentDbContext : DbContext { // NOTE: This would be a production contructor, here for illustration public AttachmentDbContext() : base("AttachmentContext") { Database.SetInitializer<AttachmentDbContext>(null); } public AttachmentDbContext(DbConnection connection) : base(connection, false){ } public IDbSet<Entities.Attachment> Attachments { get; set; } } }
mit
C#
80e69a347ef77c818337668ffe090275c9d9d2b4
修复了FormiumRequest的QueryString集合,当键值不存在时抛异常的问题。现在修改为当键值不存在时返回null。
NetDimension/NanUI,NetDimension/NanUI,NetDimension/NanUI
src/Library/shared/NetDimension.NanUI.SharedProject/ResourceHandler/QueryString.cs
src/Library/shared/NetDimension.NanUI.SharedProject/ResourceHandler/QueryString.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace NetDimension.NanUI.ResourceHandler { public class QueryString: IEnumerable<KeyValuePair<string,StringValueCollection>> { readonly IDictionary<string, string[]> RawQueries; public QueryString(IDictionary<string, string[]> value) { RawQueries = value; } public int Count => RawQueries.Count; public StringValueCollection this[string key] { get { if (!RawQueries.ContainsKey(key)) return null; return new StringValueCollection(RawQueries[key]); } } public IEnumerator<KeyValuePair<string, StringValueCollection>> GetEnumerator() { for (int i = 0; i < RawQueries.Keys.Count; i++) { var key = RawQueries.Keys.ElementAt(i); var value = RawQueries[key]; yield return new KeyValuePair<string, StringValueCollection>(key, new StringValueCollection(value)); } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace NetDimension.NanUI.ResourceHandler { public class QueryString: IEnumerable<KeyValuePair<string,StringValueCollection>> { readonly IDictionary<string, string[]> RawQueries; public QueryString(IDictionary<string, string[]> value) { RawQueries = value; } public int Count => RawQueries.Count; public StringValueCollection this[string key] => new StringValueCollection(RawQueries[key]); public IEnumerator<KeyValuePair<string, StringValueCollection>> GetEnumerator() { for (int i = 0; i < RawQueries.Keys.Count; i++) { var key = RawQueries.Keys.ElementAt(i); var value = RawQueries[key]; yield return new KeyValuePair<string, StringValueCollection>(key, new StringValueCollection(value)); } } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
mit
C#
d17a9b4d33b0fee1c29d971a3d939ef8f3732833
change object to nullable type
OlegKleyman/AlphaDev,OlegKleyman/AlphaDev,OlegKleyman/AlphaDev
core/AlphaDev.Core/PositiveInteger.cs
core/AlphaDev.Core/PositiveInteger.cs
using System; using JetBrains.Annotations; namespace AlphaDev.Core { public class PositiveInteger : IEquatable<PositiveInteger> { public static readonly PositiveInteger MinValue = new PositiveInteger(1); public static readonly PositiveInteger MaxValue = new PositiveInteger(int.MaxValue); public PositiveInteger(int value) => Value = value > 0 ? value : throw new ArgumentException("Must be positive.", nameof(value)); public int Value { get; } public bool Equals(PositiveInteger? other) => !(other is null) && Value == other.Value; public override bool Equals(object? obj) => obj is PositiveInteger p && Equals(p); public override int GetHashCode() => Value.GetHashCode(); public static int operator +([NotNull] PositiveInteger x, int y) => x.Value + y; public static int operator /([NotNull] PositiveInteger dividend, int divisor) => dividend.Value / divisor; public static int operator /(int dividend, [NotNull] PositiveInteger divisor) => dividend / divisor.Value; public static int operator /([NotNull] PositiveInteger dividend, [NotNull] PositiveInteger divisor) => dividend.Value / divisor.Value; } }
using System; using JetBrains.Annotations; namespace AlphaDev.Core { public class PositiveInteger : IEquatable<PositiveInteger> { public static readonly PositiveInteger MinValue = new PositiveInteger(1); public static readonly PositiveInteger MaxValue = new PositiveInteger(int.MaxValue); public PositiveInteger(int value) => Value = value > 0 ? value : throw new ArgumentException("Must be positive.", nameof(value)); public int Value { get; } public bool Equals(PositiveInteger? other) => !(other is null) && Value == other.Value; public override bool Equals([CanBeNull] object obj) => obj is PositiveInteger p && Equals(p); public override int GetHashCode() => Value.GetHashCode(); public static int operator +([NotNull] PositiveInteger x, int y) => x.Value + y; public static int operator /([NotNull] PositiveInteger dividend, int divisor) => dividend.Value / divisor; public static int operator /(int dividend, [NotNull] PositiveInteger divisor) => dividend / divisor.Value; public static int operator /([NotNull] PositiveInteger dividend, [NotNull] PositiveInteger divisor) => dividend.Value / divisor.Value; } }
unlicense
C#
9c737ccf4340d7523fdad65934776f67a5a026ba
Call converter changes to support stdcall on x86. The changes are mostly: 1) Enabling the FEATURE_INTERPRETER in the converter, which seemed to me to be already capable of stdcall conventions 2) Moving the CallingConvention enum to the Internal.Runtime.CallConverter namespace, to allow it to be used by the converter
shrah/corert,tijoytom/corert,botaberg/corert,sandreenko/corert,krytarowski/corert,krytarowski/corert,botaberg/corert,yizhang82/corert,sandreenko/corert,tijoytom/corert,shrah/corert,shrah/corert,sandreenko/corert,botaberg/corert,krytarowski/corert,tijoytom/corert,shrah/corert,sandreenko/corert,tijoytom/corert,yizhang82/corert,gregkalapos/corert,krytarowski/corert,yizhang82/corert,yizhang82/corert,gregkalapos/corert,gregkalapos/corert,botaberg/corert,gregkalapos/corert
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CallingConvention.cs
src/System.Private.CoreLib/src/System/Runtime/InteropServices/CallingConvention.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices { // Used for the CallingConvention named argument to the DllImport and NativeCallable attribute public enum CallingConvention { Winapi = 1, Cdecl = 2, StdCall = 3, ThisCall = 4, FastCall = 5, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// namespace System.Runtime.InteropServices { // Used for the CallingConvention named argument to the DllImport and NativeCallable attribute public enum CallingConvention { Winapi = 1, Cdecl = 2, StdCall = 3, ThisCall = 4, // FastCall = 5, } }
mit
C#
bb2ba8c894151b283d4bc7ed8b11065dcb70f837
fix mute problem.
azyobuzin/Mystique,fin-alice/Mystique
Inscribe/Common/FilterHelper.cs
Inscribe/Common/FilterHelper.cs
using System.Linq; using Dulcet.Twitter; using Inscribe.Configuration; using Inscribe.Storage; namespace Inscribe.Common { public static class FilterHelper { public static bool IsMuted(TwitterStatusBase status) { return (Setting.Instance.TimelineFilteringProperty.MuteFilterCluster != null && Setting.Instance.TimelineFilteringProperty.MuteFilterCluster.Filter(status) && !AccountStorage.Contains(status.User.ScreenName)) || IsMuted(status.User); } public static bool IsMuted(TwitterUser user) { return Setting.Instance.TimelineFilteringProperty.MuteBlockedUsers && AccountStorage.Accounts.Any(a => a.IsBlocking(user.NumericId) && !AccountStorage.Contains(user.ScreenName)); } } }
using System.Linq; using Dulcet.Twitter; using Inscribe.Configuration; using Inscribe.Storage; namespace Inscribe.Common { public static class FilterHelper { public static bool IsMuted(TwitterStatusBase status) { return (Setting.Instance.TimelineFilteringProperty.MuteFilterCluster != null && Setting.Instance.TimelineFilteringProperty.MuteFilterCluster.Filter(status)) || IsMuted(status.User); } public static bool IsMuted(TwitterUser user) { return Setting.Instance.TimelineFilteringProperty.MuteBlockedUsers && AccountStorage.Accounts.Any(a => a.IsBlocking(user.NumericId)); } } }
mit
C#
b8339c5baa842c3af86958fb922bedf6e9445275
fix aggregate provider issue
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/library/UtyMap.Unity/Maps/Providers/AggregateMapDataProvider.cs
unity/library/UtyMap.Unity/Maps/Providers/AggregateMapDataProvider.cs
using UtyDepend; using UtyDepend.Config; using UtyMap.Unity.Core.Tiling; using UtyMap.Unity.Infrastructure.Diagnostic; using UtyMap.Unity.Infrastructure.IO; using UtyMap.Unity.Infrastructure.Primitives; using UtyRx; namespace UtyMap.Unity.Maps.Providers { /// <summary> /// Aggregates different map data providers and decides which one to use for specific tiles. /// </summary> internal sealed class AggregateMapDataProvider : IMapDataProvider, IConfigurable { private readonly Range<int> OsmTileRange = new Range<int>(16, 16); private readonly OpenStreetMapDataProvider _osmMapDataProvider; private readonly MapzenMapDataProvider _mapzenMapDataProvider; [Dependency] public AggregateMapDataProvider(IFileSystemService fileSystemService, INetworkService networkService, ITrace trace) { _osmMapDataProvider = new OpenStreetMapDataProvider(fileSystemService, networkService, trace); _mapzenMapDataProvider = new MapzenMapDataProvider(fileSystemService, networkService, trace); } /// <inheritdoc /> public IObservable<string> Get(Tile tile) { if (OsmTileRange.Contains(tile.QuadKey.LevelOfDetail)) return _osmMapDataProvider.Get(tile); return _mapzenMapDataProvider.Get(tile); } /// <inheritdoc /> public void Configure(IConfigSection configSection) { _osmMapDataProvider.Configure(configSection); _mapzenMapDataProvider.Configure(configSection); } } }
using UtyDepend; using UtyDepend.Config; using UtyMap.Unity.Core.Tiling; using UtyMap.Unity.Infrastructure.Diagnostic; using UtyMap.Unity.Infrastructure.IO; using UtyMap.Unity.Infrastructure.Primitives; using UtyRx; namespace UtyMap.Unity.Maps.Providers { /// <summary> /// Aggregates different map data providers and decides which one to use for specific tiles. /// </summary> internal sealed class AggregateMapDataProvider : IMapDataProvider, IConfigurable { private readonly Range<int> OsmTileRange = new Range<int>(16, 16); private readonly OpenStreetMapDataProvider _osmMapDataProvider; private readonly MapzenMapDataProvider _mapzenMapDataProvider; [Dependency] public AggregateMapDataProvider(IFileSystemService fileSystemService, INetworkService networkService, ITrace trace) { _osmMapDataProvider = new OpenStreetMapDataProvider(fileSystemService, networkService, trace); _mapzenMapDataProvider = new MapzenMapDataProvider(fileSystemService, networkService, trace); } /// <inheritdoc /> public IObservable<string> Get(Tile tile) { if (OsmTileRange.Contains(tile.QuadKey.LevelOfDetail)) _osmMapDataProvider.Get(tile); return _mapzenMapDataProvider.Get(tile); } /// <inheritdoc /> public void Configure(IConfigSection configSection) { _osmMapDataProvider.Configure(configSection); _mapzenMapDataProvider.Configure(configSection); } } }
apache-2.0
C#
f49845be1ff67f9d3d25032611a2ffd2dd1fefd3
修正 Bug
wukaixian/Jumony,yonglehou/Jumony,wukaixian/Jumony,zpzgone/Jumony,zpzgone/Jumony,yonglehou/Jumony
Ivony.Web/VirtualPathBasedProviders.cs
Ivony.Web/VirtualPathBasedProviders.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Ivony.Web { /// <summary> /// 基于虚拟路径的提供程序列表 /// </summary> public static class VirtualPathBasedProviders { private static List<IVirtualPathBasedProvider> _providers = new List<IVirtualPathBasedProvider>(); private static object _sync = new object(); public static void RegisterProvider( IVirtualPathBasedProvider provider ) { lock ( _sync ) { _providers.Add( provider ); } } public static T GetService<T>( string virtualPath ) where T : class { lock ( _sync ) { foreach ( var p in _providers ) { var service = p.GetService( virtualPath, typeof( T ) ) as T; if ( service != null ) return service; } return null; } } public static T GetService<T>( string virtualPath, params IVirtualPathBasedProvider[] defaultProviders ) where T : class { var service = GetService<T>( virtualPath ); if ( service != null ) return service; foreach ( var p in defaultProviders ) { service = p.GetService<T>( virtualPath ); if ( service != null ) return service; } return null; } /// <summary> /// 获取指定类型的服务 /// </summary> /// <typeparam name="T">服务类型</typeparam> /// <param name="provider">服务提供程序</param> /// <param name="virtualPath">虚拟路径</param> /// <returns>服务对象</returns> public static T GetService<T>( this IVirtualPathBasedProvider provider, string virtualPath ) where T : class { return provider.GetService( virtualPath, typeof( T ) ) as T; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Ivony.Web { /// <summary> /// 基于虚拟路径的提供程序列表 /// </summary> public static class VirtualPathBasedProviders { private static List<IVirtualPathBasedProvider> _providers; private static object _sync; public static void RegisterProvider( IVirtualPathBasedProvider provider ) { lock ( _sync ) { _providers.Add( provider ); } } public static T GetService<T>( string virtualPath ) where T : class { lock ( _sync ) { foreach ( var p in _providers ) { var service = p.GetService( virtualPath, typeof( T ) ) as T; if ( service != null ) return service; } return null; } } public static T GetService<T>( string virtualPath, params IVirtualPathBasedProvider[] defaultProviders ) where T : class { var service = GetService<T>( virtualPath ); if ( service != null ) return service; foreach ( var p in defaultProviders ) { service = p.GetService<T>( virtualPath ); if ( service != null ) return service; } return null; } /// <summary> /// 获取指定类型的服务 /// </summary> /// <typeparam name="T">服务类型</typeparam> /// <param name="provider">服务提供程序</param> /// <param name="virtualPath">虚拟路径</param> /// <returns>服务对象</returns> public static T GetService<T>( this IVirtualPathBasedProvider provider, string virtualPath ) where T : class { return provider.GetService( virtualPath, typeof( T ) ) as T; } } }
apache-2.0
C#
450a5ff4fe7e143061f6fbddf846063716b3291f
Update AddLibraryReferenceToVbaProject.cs
asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET
Examples/CSharp/Articles/AddLibraryReferenceToVbaProject.cs
Examples/CSharp/Articles/AddLibraryReferenceToVbaProject.cs
using System; using Aspose.Cells.Vba; namespace Aspose.Cells.Examples.Articles { class AddLibraryReferenceToVbaProject { static void Main() { //ExStart:1 string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string outputPath = dataDir + "Output.out.xlsm"; Workbook workbook = new Workbook(); VbaProject vbaProj = workbook.VbaProject; vbaProj.References.AddRegisteredReference("stdole", "*\\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\\Windows\\system32\\stdole2.tlb#OLE Automation"); vbaProj.References.AddRegisteredReference("Office", "*\\G{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}#2.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE14\\MSO.DLL#Microsoft Office 14.0 Object Library"); workbook.Save(outputPath); //ExEnd:1 } } }
using System; using Aspose.Cells.Vba; namespace Aspose.Cells.Examples.Articles { class AddLibraryReferenceToVbaProject { static void Main() { string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string outputPath = dataDir + "Output.out.xlsm"; Workbook workbook = new Workbook(); VbaProject vbaProj = workbook.VbaProject; vbaProj.References.AddRegisteredReference("stdole", "*\\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\\Windows\\system32\\stdole2.tlb#OLE Automation"); vbaProj.References.AddRegisteredReference("Office", "*\\G{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}#2.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE14\\MSO.DLL#Microsoft Office 14.0 Object Library"); workbook.Save(outputPath); } } }
mit
C#
e079ff750e3761b00f922e31ed13be44700db8f2
Disable resource compiler verbosity by default
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
packages/C/bam/Scripts/Defaults/ICommonWinResourceCompilerSettings.cs
packages/C/bam/Scripts/Defaults/ICommonWinResourceCompilerSettings.cs
#region License // Copyright (c) 2010-2015, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace C.DefaultSettings { public static partial class DefaultSettingsExtensions { public static void Defaults( this C.ICommonWinResourceCompilerSettings settings, Bam.Core.Module module) { settings.Verbose = false; } } }
#region License // Copyright (c) 2010-2015, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace C.DefaultSettings { public static partial class DefaultSettingsExtensions { public static void Defaults( this C.ICommonWinResourceCompilerSettings settings, Bam.Core.Module module) { settings.Verbose = true; } } }
bsd-3-clause
C#
20460adcd150147cf9d3182232fb2e818673bfcb
bump verison to 1.0.0
PKRoma/Fody,ichengzi/Fody,shanselman/Fody,distantcam/Fody,shanselman/Fody,furesoft/Fody,huoxudong125/Fody,Fody/Fody,jasonholloway/Fody,ColinDabritzViewpoint/Fody,GeertvanHorrik/Fody,shanselman/Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("0.20.1.0")] [assembly: AssemblyFileVersion("0.20.1.0")]
mit
C#
c3b8fba1677e9a5fe9e6e51e8d173514c3c78fde
bump ref
Fody/EmptyConstructor
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("EmptyConstructor")] [assembly: AssemblyProduct("EmptyConstructor")] [assembly: AssemblyVersion("1.1.7")] [assembly: AssemblyFileVersion("1.1.7")]
using System.Reflection; [assembly: AssemblyTitle("EmptyConstructor")] [assembly: AssemblyProduct("EmptyConstructor")] [assembly: AssemblyVersion("1.1.6")] [assembly: AssemblyFileVersion("1.1.6")]
mit
C#
da63cf09391af800e86753d0f60be08cf8916580
Remove obsolete IActionGenerator
bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto
Source/Eto/Forms/GenerateActionArgs.cs
Source/Eto/Forms/GenerateActionArgs.cs
using System; using System.Collections; using System.Collections.Generic; namespace Eto.Forms { [Obsolete("Use separate collections for actions, menu and toolbar.")] public class GenerateActionArgs : EventArgs { #region Members readonly ActionCollection actions; readonly ActionItemCollection menu; readonly ActionItemCollection toolBar; readonly Dictionary<object, object> arguments = new Dictionary<object, object>(); #endregion #region Properties public Generator Generator { get { return actions.Generator; } } public ActionCollection Actions { get { return actions; } } public ActionItemCollection Menu { get { return menu; } } public ActionItemCollection ToolBar { get { return toolBar; } } public Dictionary<object, object> Arguments { get { return arguments; } } #endregion public GenerateActionArgs() : this((Generator)null) { } public GenerateActionArgs(Generator generator) : this(generator, null) { } public GenerateActionArgs(Control control) : this(control.Generator, control) { } public GenerateActionArgs(Generator g, Control control) { this.actions = new ActionCollection(g, control); this.menu = new ActionItemCollection(actions); this.toolBar = new ActionItemCollection(actions); } public GenerateActionArgs(ActionCollection actions, ActionItemCollection menu, ActionItemCollection toolBar) { this.actions = actions; this.menu = menu; this.toolBar = toolBar; } public void CopyArguments(GenerateActionArgs args) { foreach (var de in args.arguments) { arguments[de.Key] = de.Value; } } public void Merge(GenerateActionArgs args) { toolBar.Merge(args.toolBar); menu.Merge(args.Menu); } public object GetArgument(object key, object defaultValue) { return !arguments.ContainsKey(key) ? defaultValue : arguments[key]; } public void Clear() { actions.Clear(); menu.Clear(); toolBar.Clear(); } } }
using System; using System.Collections; using System.Collections.Generic; namespace Eto.Forms { public interface IActionGenerator { void Generate(GenerateActionArgs args); } [Obsolete("Use separate collections for actions, menu and toolbar.")] public class GenerateActionArgs : EventArgs { #region Members readonly ActionCollection actions; readonly ActionItemCollection menu; readonly ActionItemCollection toolBar; readonly Dictionary<object, object> arguments = new Dictionary<object, object>(); #endregion #region Properties public Generator Generator { get { return actions.Generator; } } public ActionCollection Actions { get { return actions; } } public ActionItemCollection Menu { get { return menu; } } public ActionItemCollection ToolBar { get { return toolBar; } } public Dictionary<object, object> Arguments { get { return arguments; } } #endregion public GenerateActionArgs() : this((Generator)null) { } public GenerateActionArgs(Generator generator) : this(generator, null) { } public GenerateActionArgs(Control control) : this(control.Generator, control) { } public GenerateActionArgs(Generator g, Control control) { this.actions = new ActionCollection(g, control); this.menu = new ActionItemCollection(actions); this.toolBar = new ActionItemCollection(actions); } public GenerateActionArgs(ActionCollection actions, ActionItemCollection menu, ActionItemCollection toolBar) { this.actions = actions; this.menu = menu; this.toolBar = toolBar; } public void CopyArguments(GenerateActionArgs args) { foreach (var de in args.arguments) { arguments[de.Key] = de.Value; } } public void Merge(GenerateActionArgs args) { toolBar.Merge(args.toolBar); menu.Merge(args.Menu); } public object GetArgument(object key, object defaultValue) { return !arguments.ContainsKey(key) ? defaultValue : arguments[key]; } public void Clear() { actions.Clear(); menu.Clear(); toolBar.Clear(); } } }
bsd-3-clause
C#
b3e28b7e18ab57d54a2a55aa23eafec1402fc063
fix ObserveProperty document summary
runceel/ReactiveProperty,runceel/ReactiveProperty,runceel/ReactiveProperty
Source/NET40/Extensions/INotifyPropertyChangedExtensions.cs
Source/NET40/Extensions/INotifyPropertyChangedExtensions.cs
using System; using System.ComponentModel; using System.Linq.Expressions; using System.Diagnostics.Contracts; #if WINDOWS_PHONE using Microsoft.Phone.Reactive; #else using System.Reactive; using System.Reactive.Linq; using System.Reactive.Concurrency; using System.Reactive.Disposables; #endif namespace Codeplex.Reactive.Extensions { public static class INotifyPropertyChangedExtensions { /// <summary>Converts PropertyChanged to an observable sequence.</summary> public static IObservable<PropertyChangedEventArgs> PropertyChangedAsObservable<T>(this T subject) where T : INotifyPropertyChanged { Contract.Requires<ArgumentNullException>(subject != null); Contract.Ensures(Contract.Result<IObservable<PropertyChangedEventArgs>>() != null); return ObservableEx.FromEvent<PropertyChangedEventHandler, PropertyChangedEventArgs>( h => (sender, e) => h(e), h => subject.PropertyChanged += h, h => subject.PropertyChanged -= h); } /// <summary> /// Converts NotificationObject's property changed to an observable sequence. /// </summary> /// <param name="propertySelector">Argument is self, Return is target property.</param> public static IObservable<TProperty> ObserveProperty<TSubject, TProperty>( this TSubject subject, Expression<Func<TSubject, TProperty>> propertySelector) where TSubject : INotifyPropertyChanged { Contract.Requires<ArgumentNullException>(subject != null); Contract.Requires<ArgumentNullException>(propertySelector != null); Contract.Ensures(Contract.Result<IObservable<TProperty>>() != null); string propertyName; var accessor = AccessorCache<TSubject>.Lookup(propertySelector, out propertyName); var result = subject.PropertyChangedAsObservable() .Where(e => e.PropertyName == propertyName) .Select(_ => ((Func<TSubject, TProperty>)accessor).Invoke(subject)); Contract.Assume(result != null); return result; } } }
using System; using System.ComponentModel; using System.Linq.Expressions; using System.Diagnostics.Contracts; #if WINDOWS_PHONE using Microsoft.Phone.Reactive; #else using System.Reactive; using System.Reactive.Linq; using System.Reactive.Concurrency; using System.Reactive.Disposables; #endif namespace Codeplex.Reactive.Extensions { public static class INotifyPropertyChangedExtensions { /// <summary>Converts PropertyChanged to an observable sequence.</summary> public static IObservable<PropertyChangedEventArgs> PropertyChangedAsObservable<T>(this T subject) where T : INotifyPropertyChanged { Contract.Requires<ArgumentNullException>(subject != null); Contract.Ensures(Contract.Result<IObservable<PropertyChangedEventArgs>>() != null); return ObservableEx.FromEvent<PropertyChangedEventHandler, PropertyChangedEventArgs>( h => (sender, e) => h(e), h => subject.PropertyChanged += h, h => subject.PropertyChanged -= h); } /// <summary> /// Converts NotificationObject's property to an observable sequence. /// </summary> /// <param name="propertySelector">Argument is self, Return is target property.</param> public static IObservable<TProperty> ObserveProperty<TSubject, TProperty>( this TSubject subject, Expression<Func<TSubject, TProperty>> propertySelector) where TSubject : INotifyPropertyChanged { Contract.Requires<ArgumentNullException>(subject != null); Contract.Requires<ArgumentNullException>(propertySelector != null); Contract.Ensures(Contract.Result<IObservable<TProperty>>() != null); string propertyName; var accessor = AccessorCache<TSubject>.Lookup(propertySelector, out propertyName); var result = subject.PropertyChangedAsObservable() .Where(e => e.PropertyName == propertyName) .Select(_ => ((Func<TSubject, TProperty>)accessor).Invoke(subject)); Contract.Assume(result != null); return result; } } }
mit
C#
7191f54a264e1bfd077cb8754e303a6ef0205dfe
Update IExchangeRateProvider.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/ForeignExchange/IExchangeRateProvider.cs
TIKSN.Core/Finance/ForeignExchange/IExchangeRateProvider.cs
using System; using System.Threading; using System.Threading.Tasks; namespace TIKSN.Finance.ForeignExchange { public interface IExchangeRateProvider { Task<ExchangeRate> GetExchangeRateAsync(CurrencyInfo baseCurrency, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken); } }
using System; using System.Threading; using System.Threading.Tasks; namespace TIKSN.Finance.ForeignExchange { public interface IExchangeRateProvider { Task<ExchangeRate> GetExchangeRateAsync(CurrencyInfo baseCurrency, CurrencyInfo counterCurrency, DateTimeOffset asOn, CancellationToken cancellationToken); } }
mit
C#
ce8c30fd845ad27adb795a797f07378787a5bf93
Add documentation for episode ids.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/Shows/Episodes/TraktEpisodeIds.cs
Source/Lib/TraktApiSharp/Objects/Get/Shows/Episodes/TraktEpisodeIds.cs
namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; /// <summary>A collection of ids for various web services, including the Trakt id, for a Trakt episode.</summary> public class TraktEpisodeIds : TraktIds { } }
namespace TraktApiSharp.Objects.Get.Shows.Episodes { using Basic; public class TraktEpisodeIds : TraktIds { } }
mit
C#
75fa5ea9f0a5ed71588e464d807803fa08ba261f
Update ServiceCollectionExtensions.cs
tiksn/TIKSN-Framework
TIKSN.Framework.UWP/DependencyInjection/ServiceCollectionExtensions.cs
TIKSN.Framework.UWP/DependencyInjection/ServiceCollectionExtensions.cs
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using TIKSN.Advertising; using TIKSN.FileSystem; using TIKSN.Network; using TIKSN.Settings; namespace TIKSN.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddFrameworkPlatform(this IServiceCollection services) { services.AddFrameworkCore(); services.TryAddSingleton<IAdUnitSelector, AdUnitSelector>(); services.TryAddSingleton<IKnownFolders, KnownFolders>(); services.TryAddSingleton<INetworkConnectivityService, NetworkConnectivityService>(); services.TryAddSingleton<ISettingsService, SettingsService>(); return services; } } }
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TIKSN.Advertising; using TIKSN.FileSystem; using TIKSN.Network; using TIKSN.Settings; namespace TIKSN.DependencyInjection { public static class ServiceCollectionExtensions { public static IServiceCollection AddFrameworkPlatform(this IServiceCollection services) { services.AddFrameworkCore(); services.TryAddSingleton<IAdUnitSelector, AdUnitSelector>(); services.TryAddSingleton<IKnownFolders, KnownFolders>(); services.TryAddSingleton<INetworkConnectivityService, NetworkConnectivityService>(); services.TryAddSingleton<ISettingsService, SettingsService>(); return services; } } }
mit
C#
3be0e26965c6d18f82a6339315157852a9c56d9f
fix xmldoc
poxet/Influx-Capacitor,poxet/influxdb-collector
Tharga.Influx-Capacitor.Collector/Interface/IPerformanceCounterInfo.cs
Tharga.Influx-Capacitor.Collector/Interface/IPerformanceCounterInfo.cs
using System.Collections.Generic; namespace Tharga.InfluxCapacitor.Collector.Interface { public interface IPerformanceCounterInfo { /// <summary> /// Gets the name of this informational counter. /// Can be <see cref="CounterName"/> or <see cref="InstanceName"/>, depending if <see cref="CounterName"/> value is "*". /// </summary> string Name { get; } /// <summary> /// Gets the system performance counter associated with this informations. /// <c>null</c> if the counter does not exists or is not available. /// </summary> /// <summary> /// Gets a value indicating if this informational counter has a real counter or not. /// </summary> bool HasPerformanceCounter { get; } /// <summary> /// Gets the category this performance counter is member of. /// </summary> string CategoryName { get; } /// <summary> /// Gets the performance counter name. /// </summary> string CounterName { get; } /// <summary> /// Gets the read instance name for this counter, based on system instance name (without filtering). /// </summary> string InstanceName { get; set; } /// <summary> /// Gets the name to use as a field for this counter. Can be the value of <see cref="CounterName"/> or <see cref="InstanceName"/> with an eventual filter applied. /// </summary> string FieldName { get; } /// <summary> /// Gets the machine name for this counter. /// </summary> string MachineName { get; } string Alias { get; } IEnumerable<ITag> Tags { get; } /// <summary> /// Gets the maximum value authorized for this counter. /// Useful if the counter is sometimes reporting more than a limit value. /// </summary> /// <seealso cref="ICounter.Max"/> /// <seealso href="https://support.microsoft.com/en-us/kb/310067"/> float? Max { get; } /// <summary> /// Obtains the next counter value and returns it. /// </summary> float NextValue(); } }
using System.Collections.Generic; namespace Tharga.InfluxCapacitor.Collector.Interface { public interface IPerformanceCounterInfo { /// <summary> /// Gets the name of this informational counter. /// Can be <see cref="CounterName"/> or <see cref="InstanceName"/>, depending if <see cref="CounterName"/> value is "*". /// </summary> string Name { get; } /// <summary> /// Gets the system performance counter associated with this informations. /// <c>null</c> if the counter does not exists or is not available. /// </summary> /// <summary> /// Gets a value indicating if this informational counter has a real counter or not. /// </summary> bool HasPerformanceCounter { get; } /// <summary> /// Gets the category this performance counter is member of. /// </summary> string CategoryName { get; } /// <summary> /// Gets the performance counter name. /// </summary> string CounterName { get; } /// <summary> /// Gets the read instance name for this counter, based on system instance name (without filtering). /// </summary> string InstanceName { get; set; } /// <summary> /// Gets the name to use as a field for this counter. Can be the value of <see cref="CounterName"/> or <see cref="InstanceName"/> with an eventual filter applied. /// </summary> string FieldName { get; } /// </summary> /// Gets the machine name for this counter. /// </summary> string MachineName { get; } string Alias { get; } IEnumerable<ITag> Tags { get; } /// <summary> /// Gets the maximum value authorized for this counter. /// Useful if the counter is sometimes reporting more than a limit value. /// </summary> /// <seealso cref="ICounter.Max"/> /// <seealso href="https://support.microsoft.com/en-us/kb/310067"/> float? Max { get; } /// <summary> /// Obtains the next counter value and returns it. /// </summary> float NextValue(); } }
mit
C#
60368346e6f1b6345b90acaf89887a2833789513
Fix DomainException LogError parameter order
geeklearningio/gl-dotnet-domain
src/GeekLearning.Domain.AspnetCore/DomainExceptionFilter.cs
src/GeekLearning.Domain.AspnetCore/DomainExceptionFilter.cs
namespace GeekLearning.Domain.AspnetCore { using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class DomainExceptionFilter : IActionFilter { private ILoggerFactory loggerFactory; private IOptions<DomainOptions> options; public DomainExceptionFilter(ILoggerFactory loggerFactory, IOptions<DomainOptions> domainOptions) { this.loggerFactory = loggerFactory; this.options = domainOptions; } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception != null) { var domainException = context.Exception as DomainException; var logger = this.loggerFactory.CreateLogger<DomainExceptionFilter>(); if (domainException == null) { logger.LogError(new EventId(1, "Unknown error"), context.Exception, context.Exception.Message); domainException = new Explanations.Unknown().AsException(context.Exception); } context.Result = new MaybeResult<object>(domainException.Explanation); context.ExceptionHandled = true; } } public void OnActionExecuting(ActionExecutingContext context) { } } }
namespace GeekLearning.Domain.AspnetCore { using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; public class DomainExceptionFilter : IActionFilter { private ILoggerFactory loggerFactory; private IOptions<DomainOptions> options; public DomainExceptionFilter(ILoggerFactory loggerFactory, IOptions<DomainOptions> domainOptions) { this.loggerFactory = loggerFactory; this.options = domainOptions; } public void OnActionExecuted(ActionExecutedContext context) { if (context.Exception != null) { var domainException = context.Exception as DomainException; var logger = this.loggerFactory.CreateLogger<DomainExceptionFilter>(); if (domainException == null) { logger.LogError(new EventId(1, "Unknown error"), context.Exception.Message, context.Exception); domainException = new Explanations.Unknown().AsException(context.Exception); } context.Result = new MaybeResult<object>(domainException.Explanation); context.ExceptionHandled = true; } } public void OnActionExecuting(ActionExecutingContext context) { } } }
mit
C#
b19b6faa5a37a42f5096172c582d56a537353d6b
升级版本到2.2.3
Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue,tangxuehua/equeue,Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue
src/EQueue/Properties/AssemblyInfo.cs
src/EQueue/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EQueue")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.3")] [assembly: AssemblyFileVersion("2.2.3")]
using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EQueue")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.2")] [assembly: AssemblyFileVersion("2.2.2")]
mit
C#
ca801365115c52253343f8002cff06e67c9a9c5e
Update div converter functionality
mysticmind/reversemarkdown-net
src/ReverseMarkdown/Converters/Div.cs
src/ReverseMarkdown/Converters/Div.cs
using System; using System.Collections.Generic; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class Div : ConverterBase { public Div(Converter converter) : base(converter) { Converter.Register("div", this); } public override string Convert(HtmlNode node) { var content = string.Empty; do { if (node.ChildNodes.Count == 1 && node.FirstChild.Name == "div") { node = node.FirstChild; continue; } content = TreatChildren(node); break; } while (true); var blockTags = new List<string> { "pre", "p", "ol", "oi", "table" }; // if there is a block child then ignore adding the newlines for div if ((node.ChildNodes.Count == 1 && blockTags.Contains(node.FirstChild.Name))) { return content; } return $"{(Td.FirstNodeWithinCell(node) ? "" : Environment.NewLine)}{content}{(Td.LastNodeWithinCell(node) ? "" : Environment.NewLine)}"; } } }
using System; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class Div : ConverterBase { public Div(Converter converter) : base(converter) { Converter.Register("div", this); } public override string Convert(HtmlNode node) { var content = TreatChildren(node); // if child is a pre tag then Trim in the above step removes the 4 spaces for code block if (node.ChildNodes.Count > 0 && node.FirstChild.Name == "pre") { return content; } return $"{(Td.FirstNodeWithinCell(node) ? "" : Environment.NewLine)}{content.Trim()}{(Td.LastNodeWithinCell(node) ? "" : Environment.NewLine)}"; } } }
mit
C#
d3eb24e70a2861cbfbe3f5d3759bf67f1cb23628
Fix score retrieval no longer working
UselessToucan/osu,2yangk23/osu,peppy/osu,ZLima12/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,naoey/osu,DrabWeb/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,smoogipooo/osu,NeoAdonis/osu,DrabWeb/osu,NeoAdonis/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,EVAST9919/osu,naoey/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu-new
osu.Game/Rulesets/Scoring/Score.cs
osu.Game/Rulesets/Scoring/Score.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Users; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Scoring { public class Score { public ScoreRank Rank { get; set; } public double TotalScore { get; set; } public double Accuracy { get; set; } public double Health { get; set; } = 1; public double? PP { get; set; } public int MaxCombo { get; set; } public int Combo { get; set; } public RulesetInfo Ruleset { get; set; } public Mod[] Mods { get; set; } = { }; public User User; [JsonIgnore] public Replay Replay; public BeatmapInfo Beatmap; public long OnlineScoreID; public DateTimeOffset Date; public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>(); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Mods; using osu.Game.Users; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Scoring { public class Score { public ScoreRank Rank { get; set; } public double TotalScore { get; set; } public double Accuracy { get; set; } public double Health { get; set; } = 1; public double? PP { get; set; } public int MaxCombo { get; set; } public int Combo { get; set; } public RulesetInfo Ruleset { get; set; } public Mod[] Mods { get; set; } = { }; public User User; public Replay Replay; public BeatmapInfo Beatmap; public long OnlineScoreID; public DateTimeOffset Date; public Dictionary<HitResult, object> Statistics = new Dictionary<HitResult, object>(); } }
mit
C#
c2d0467741b52e31840684ae6b298d8262d0fca2
increment pre-release version
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyInformationalVersion("0.1.0-pre01")] /* * Version 0.1.0-pre01 */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.0.1")] [assembly: AssemblyInformationalVersion("0.0.1-pre01")] /* */
mit
C#
60c4d132de98e1b8f2c708102f83249e399f7d13
increment minor version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.19.0")] [assembly: AssemblyInformationalVersion("0.19.0")] /* * Version 0.19.0 * * - [NEW] Declaration of test fixture factory using attribute * Introduces the new model to create test fixture. Using the * TestFixtureFactoryType attribute, a type of ITestFixtureFactory can be * defined and will be used to create a factory for test fixture. * * - [FIX] Renames the test attributes. (BREAKING CHANGE) * TheoremAttriute -> ExamAttribute * FirstClassTheoremAttriute -> FirstClassExamAttribute * * - [FIX] Splits the Experiment project to Experiment and Experiment.Xunit * projects. (BREAKING CHANGE) * * - [NEW] Rearrages nuget packages to reflect the splited projects. * (BREAKING CHANGE) * Publishes the new package 'Experiment.Xunit', and deletes the packages * 'Experiment.AutoFixtureWithExample' and 'Experiment'. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.18.2")] [assembly: AssemblyInformationalVersion("0.18.2")] /* * Version 0.19.0 * * - [NEW] Declaration of test fixture factory using attribute * Introduces the new model to create test fixture. Using the * TestFixtureFactoryType attribute, a type of ITestFixtureFactory can be * defined and will be used to create a factory for test fixture. * * - [FIX] Renames the test attributes. (BREAKING CHANGE) * TheoremAttriute -> ExamAttribute * FirstClassTheoremAttriute -> FirstClassExamAttribute * * - [FIX] Splits the Experiment project to Experiment and Experiment.Xunit * projects. (BREAKING CHANGE) * * - [FIX] Rearrages nuget packages to reflect the splited projects. * (BREAKING CHANGE) * Publishes the new package 'Experiment.Xunit', and deletes the packages * 'Experiment.AutoFixtureWithExample' and 'Experiment'. */
mit
C#
00eae8e75ac62d695fe4c7c6d939c2c2d23ba74d
Fix bug in OpenFileDialog
celeron533/marukotoolbox
mp4box/Extension/OpenFileDialogExt.cs
mp4box/Extension/OpenFileDialogExt.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static mp4box.Utility.DialogUtil; namespace System.Windows.Forms { public static class OpenFileDialogExt { public static OpenFileDialog Prepare(this OpenFileDialog dialog, string filter = "", string presetFileName = "") { if (!string.IsNullOrEmpty(presetFileName)) dialog.FileName = presetFileName; if (!string.IsNullOrEmpty(filter)) dialog.Filter = filter; return dialog; } public static OpenFileDialog Prepare(this OpenFileDialog dialog, DialogFilterTypes filterType, string presetFileName = "") { return dialog.Prepare(GetDialogFilter(filterType), presetFileName); } public static DialogResult ShowDialogExt(this OpenFileDialog dialog, ref string selectedFileName) { DialogResult result; if ((result = dialog.ShowDialog()) == DialogResult.OK) selectedFileName = dialog.FileName; return result; } public static DialogResult ShowDialogExt(this OpenFileDialog dialog, TextBoxBase selectedFileNameTextBoxBase) { DialogResult result; if ((result = dialog.ShowDialog()) == DialogResult.OK) selectedFileNameTextBoxBase.Text = dialog.FileName; return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static mp4box.Utility.DialogUtil; namespace System.Windows.Forms { public static class OpenFileDialogExt { public static OpenFileDialog Prepare(this OpenFileDialog dialog, string filter = "", string presetFileName = "") { if (!string.IsNullOrEmpty(presetFileName)) dialog.FileName = presetFileName; if (!string.IsNullOrEmpty(filter)) dialog.Filter = filter; return dialog; } public static OpenFileDialog Prepare(this OpenFileDialog dialog, DialogFilterTypes filterType, string presetFileName = "") { return dialog.Prepare(GetDialogFilter(filterType), presetFileName); } public static DialogResult ShowDialogExt(this OpenFileDialog dialog, out string selectedFileName) { DialogResult result; if ((result = dialog.ShowDialog()) == DialogResult.OK) selectedFileName = dialog.FileName; else selectedFileName = string.Empty; return result; } public static DialogResult ShowDialogExt(this OpenFileDialog dialog, TextBoxBase selectedFileNameTextBoxBase) { DialogResult result; if ((result = dialog.ShowDialog()) == DialogResult.OK) selectedFileNameTextBoxBase.Text = dialog.FileName; return result; } } }
apache-2.0
C#
c0cff16756fbaaa1ac2978a24cd526ee92c98a1b
add logic on queues for retrieval
azure-contrib/netmfazurestorage
netmfazurestorage/Tests/QueueTests.cs
netmfazurestorage/Tests/QueueTests.cs
using System; using Microsoft.SPOT; using netmfazurestorage.Queue; namespace netmfazurestorage.Tests { public class QueueTests { private QueueClient _queueClient; public QueueTests(string accountName, string accountKey) { _queueClient = new QueueClient(accountName, accountKey); } public void Run() { CreateQueue("netmfmessages"); CreateQueueMessage("netmfmessages", "Skynet is READY"); RetrieveQueueMessage("netmfmessages"); } private void RetrieveQueueMessage(string queueName) { var message = _queueClient.RetrieveQueueMessage(queueName); Debug.Print(message.Message); } private void CreateQueue(string queueName) { _queueClient.CreateQueue(queueName); } private void CreateQueueMessage(string queueName, string messageBody) { _queueClient.CreateQueueMessage(queueName, messageBody); } } }
using System; using Microsoft.SPOT; using netmfazurestorage.Queue; namespace netmfazurestorage.Tests { public class QueueTests { private QueueClient _queueClient; public QueueTests(string accountName, string accountKey) { _queueClient = new QueueClient(accountName, accountKey); } public void Run() { CreateQueue("netmfmessages"); CreateQueueMessage("netmfmessages", "Skynet => READY"); } private void CreateQueue(string queueName) { _queueClient.CreateQueue(queueName); } private void CreateQueueMessage(string queueName, string messageBody) { _queueClient.CreateQueueMessage(queueName, messageBody); } } }
apache-2.0
C#
6d62861a8d77b7e29cab1186b53bfb8d6ba88b1b
Make the Csv Parser could parse a single line
gydisme/Unity-DataManager
Assets/DataManager/Custom/TableParserCsv.cs
Assets/DataManager/Custom/TableParserCsv.cs
using System.IO; using System.Text; using System.Collections.Generic; using DataManagement; public class TableParserCsv : TableParser { public override object Parse( object input ) { try { using( StringReader readFile = new StringReader( (string)input ) ) { return _Parse( readFile ); } } catch { TableTools.Log( TableTools.LogLevel.ERROR, "read text asset have an exception:" + input ); } return new List<List<string>>(); } private List<List<string>> _Parse( TextReader readFile ) { List<List<string>> result = new List<List<string>>(); List<string> lines; string line = string.Empty; while( null != ( line = readFile.ReadLine() ) ) { lines = ParseLine( line ); result.Add( lines ); } return result; } public static List<string> ParseLine( string line ) { List<string> result = new List<string>(); string value = string.Empty; bool inQuato = false; bool addQuato = false; foreach( char c in line ) { if( addQuato && c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { addQuato = false; } else if( addQuato && !c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { addQuato = false; inQuato = false; } else if( inQuato && c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { addQuato = true; continue; } else if( c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { inQuato = true; continue; } if( !inQuato && c.Equals( EDataManager.COMMA_CHAR ) ) { result.Add( value ); value = string.Empty; continue; } value += c.ToString(); } result.Add( value ); return result; } }
using System.IO; using System.Text; using System.Collections.Generic; using DataManagement; public class TableParserCsv : TableParser { public override object Parse( object input ) { try { using( StringReader readFile = new StringReader( (string)input ) ) { return _Parse( readFile ); } } catch { TableTools.Log( TableTools.LogLevel.ERROR, "read text asset have an exception:" + input ); } return new List<List<string>>(); } private List<List<string>> _Parse( TextReader readFile ) { List<List<string>> result = new List<List<string>>(); List<string> lines; string line = string.Empty; bool inQuato = false; bool addQuato = false; string value = string.Empty; while( null != ( line = readFile.ReadLine() ) ) { lines = new List<string>(); value = string.Empty; foreach( char c in line ) { if( addQuato && c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { addQuato = false; } else if( addQuato && !c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { addQuato = false; inQuato = false; } else if( inQuato && c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { addQuato = true; continue; } else if( c.Equals( EDataManager.DOUBLE_QUOTATION_MARKS_CHAR ) ) { inQuato = true; continue; } if( !inQuato && c.Equals( EDataManager.COMMA_CHAR ) ) { lines.Add( value ); value = string.Empty; continue; } value += c.ToString(); } lines.Add( value ); result.Add( lines ); } return result; } }
mit
C#
116121a9bdb527823d8cc6e68350d400e6ee33de
Remove redundant line
ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
osu.Framework/Graphics/Video/StdIo.cs
osu.Framework/Graphics/Video/StdIo.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Graphics.Video { internal static class StdIo { internal const int SEEK_SET = 0; internal const int SEEK_CUR = 1; internal const int SEEK_END = 2; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Graphics.Video { internal static class StdIo { internal const int SEEK_SET = 0; internal const int SEEK_CUR = 1; internal const int SEEK_END = 2; } }
mit
C#
07c10c59a0315b7b83baad8b862d6ee0194a0ce4
Add conditional access
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
osu.Framework/Utils/OrderAttribute.cs
osu.Framework/Utils/OrderAttribute.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; namespace osu.Framework.Utils { public static class OrderAttributeUtils { /// <summary> /// Get values of an enum in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>() { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException("T must be an enum"); IEnumerable<T> items = (T[])Enum.GetValues(type); return GetValuesInOrder(items); } /// <summary> /// Get values of a collection of enum values in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>(IEnumerable<T> items) { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException("T must be an enum"); if (!(Attribute.GetCustomAttribute(type, typeof(HasOrderedElementsAttribute)) is HasOrderedElementsAttribute orderedAttr)) return items; return items.OrderBy(i => { if (type.GetField(i.ToString())?.GetCustomAttributes(typeof(OrderAttribute), false).FirstOrDefault() is OrderAttribute attr) return attr.Order; if (orderedAttr.AllowPartialOrdering) return (int)Enum.Parse(type, i.ToString()); throw new ArgumentException($"Not all values of {nameof(T)} have {nameof(OrderAttribute)} specified."); }); } } [AttributeUsage(AttributeTargets.Field)] public class OrderAttribute : Attribute { public readonly int Order; public OrderAttribute(int order) { Order = order; } } [AttributeUsage(AttributeTargets.Enum)] public class HasOrderedElementsAttribute : Attribute { /// <summary> /// Allow for partially ordering Enum members. /// Members without an Order Attribute will default to their value as ordering key. /// </summary> public bool AllowPartialOrdering { get; set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; namespace osu.Framework.Utils { public static class OrderAttributeUtils { /// <summary> /// Get values of an enum in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>() { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException("T must be an enum"); IEnumerable<T> items = (T[])Enum.GetValues(type); return GetValuesInOrder(items); } /// <summary> /// Get values of a collection of enum values in order. Supports custom ordering via <see cref="OrderAttribute"/>. /// </summary> public static IEnumerable<T> GetValuesInOrder<T>(IEnumerable<T> items) { var type = typeof(T); if (!type.IsEnum) throw new InvalidOperationException("T must be an enum"); if (!(Attribute.GetCustomAttribute(type, typeof(HasOrderedElementsAttribute)) is HasOrderedElementsAttribute orderedAttr)) return items; return items.OrderBy(i => { if (type.GetField(i.ToString()).GetCustomAttributes(typeof(OrderAttribute), false).FirstOrDefault() is OrderAttribute attr) return attr.Order; if (orderedAttr.AllowPartialOrdering) return (int)Enum.Parse(type, i.ToString()); throw new ArgumentException($"Not all values of {nameof(T)} have {nameof(OrderAttribute)} specified."); }); } } [AttributeUsage(AttributeTargets.Field)] public class OrderAttribute : Attribute { public readonly int Order; public OrderAttribute(int order) { Order = order; } } [AttributeUsage(AttributeTargets.Enum)] public class HasOrderedElementsAttribute : Attribute { /// <summary> /// Allow for partially ordering Enum members. /// Members without an Order Attribute will default to their value as ordering key. /// </summary> public bool AllowPartialOrdering { get; set; } } }
mit
C#
f89abf3140aae14952dc4c422441108c6436344a
Add comment.
dotnet/roslyn,mattscheffer/roslyn,orthoxerox/roslyn,bkoelman/roslyn,diryboy/roslyn,eriawan/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,davkean/roslyn,jcouv/roslyn,xasx/roslyn,VSadov/roslyn,pdelvo/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,mavasani/roslyn,jamesqo/roslyn,mattscheffer/roslyn,weltkante/roslyn,tmeschter/roslyn,dpoeschl/roslyn,xasx/roslyn,physhi/roslyn,reaction1989/roslyn,jmarolf/roslyn,paulvanbrenk/roslyn,yeaicc/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,srivatsn/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,jasonmalinowski/roslyn,genlu/roslyn,jasonmalinowski/roslyn,kelltrick/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,bkoelman/roslyn,jmarolf/roslyn,paulvanbrenk/roslyn,abock/roslyn,CaptainHayashi/roslyn,tvand7093/roslyn,dotnet/roslyn,paulvanbrenk/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,DustinCampbell/roslyn,stephentoub/roslyn,physhi/roslyn,wvdd007/roslyn,bkoelman/roslyn,sharwell/roslyn,bartdesmet/roslyn,gafter/roslyn,wvdd007/roslyn,jkotas/roslyn,heejaechang/roslyn,robinsedlaczek/roslyn,KirillOsenkov/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mavasani/roslyn,tmeschter/roslyn,aelij/roslyn,orthoxerox/roslyn,tmeschter/roslyn,robinsedlaczek/roslyn,xasx/roslyn,stephentoub/roslyn,reaction1989/roslyn,OmarTawfik/roslyn,jcouv/roslyn,khyperia/roslyn,genlu/roslyn,mattscheffer/roslyn,aelij/roslyn,jamesqo/roslyn,agocke/roslyn,AlekseyTs/roslyn,VSadov/roslyn,TyOverby/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,AnthonyDGreen/roslyn,brettfo/roslyn,MattWindsor91/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,cston/roslyn,CaptainHayashi/roslyn,DustinCampbell/roslyn,jamesqo/roslyn,cston/roslyn,nguerrera/roslyn,mavasani/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,wvdd007/roslyn,gafter/roslyn,VSadov/roslyn,OmarTawfik/roslyn,tmat/roslyn,Giftednewt/roslyn,yeaicc/roslyn,dpoeschl/roslyn,MattWindsor91/roslyn,orthoxerox/roslyn,robinsedlaczek/roslyn,jkotas/roslyn,mmitche/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,jkotas/roslyn,reaction1989/roslyn,brettfo/roslyn,nguerrera/roslyn,sharwell/roslyn,gafter/roslyn,khyperia/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,kelltrick/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,genlu/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,srivatsn/roslyn,Hosch250/roslyn,weltkante/roslyn,kelltrick/roslyn,yeaicc/roslyn,lorcanmooney/roslyn,TyOverby/roslyn,srivatsn/roslyn,CyrusNajmabadi/roslyn,pdelvo/roslyn,MichalStrehovsky/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,cston/roslyn,AlekseyTs/roslyn,lorcanmooney/roslyn,Giftednewt/roslyn,bartdesmet/roslyn,tvand7093/roslyn,eriawan/roslyn,pdelvo/roslyn,lorcanmooney/roslyn,agocke/roslyn,tannergooding/roslyn,agocke/roslyn,sharwell/roslyn,tmat/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,tmat/roslyn,abock/roslyn,MattWindsor91/roslyn,MattWindsor91/roslyn,khyperia/roslyn,eriawan/roslyn,tvand7093/roslyn,AnthonyDGreen/roslyn,jmarolf/roslyn,CaptainHayashi/roslyn,DustinCampbell/roslyn,KirillOsenkov/roslyn,abock/roslyn,Hosch250/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,AnthonyDGreen/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,mmitche/roslyn,nguerrera/roslyn,TyOverby/roslyn,MichalStrehovsky/roslyn,Hosch250/roslyn,davkean/roslyn,jcouv/roslyn,aelij/roslyn,Giftednewt/roslyn
src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs
src/Features/Core/Portable/AddImport/CodeActions/ProjectSymbolReferenceCodeAction.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportCodeFixProvider<TSimpleNameSyntax> { /// <summary> /// Code action for adding an import when we find a symbol in source in either our /// starting project, or some other unreferenced project in the solution. If we /// find a source symbol in a different project, we'll also add a p2p reference when /// we apply the code action. /// </summary> private class ProjectSymbolReferenceCodeAction : SymbolReferenceCodeAction { /// <summary> /// The optional id for a <see cref="Project"/> we'd like to add a reference to. /// </summary> private readonly ProjectId _projectReferenceToAdd; public ProjectSymbolReferenceCodeAction( Document originalDocument, ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId projectReferenceToAdd) : base(originalDocument, textChanges, title, tags, priority) { // We only want to add a project reference if the project the import references // is different from the project we started from. if (projectReferenceToAdd != originalDocument.Project.Id) { _projectReferenceToAdd = projectReferenceToAdd; } } internal override bool PerformFinalApplicabilityCheck => _projectReferenceToAdd != null; internal override bool IsApplicable(Workspace workspace) => _projectReferenceToAdd != null && workspace.CanAddProjectReference(OriginalDocument.Project.Id, _projectReferenceToAdd); protected override Project UpdateProject(Project project) { return _projectReferenceToAdd == null ? project : project.AddProjectReference(new ProjectReference(_projectReferenceToAdd)); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportCodeFixProvider<TSimpleNameSyntax> { private class ProjectSymbolReferenceCodeAction : SymbolReferenceCodeAction { /// <summary> /// The optional id for a <see cref="Project"/> we'd like to add a reference to. /// </summary> private readonly ProjectId _projectReferenceToAdd; public ProjectSymbolReferenceCodeAction( Document originalDocument, ImmutableArray<TextChange> textChanges, string title, ImmutableArray<string> tags, CodeActionPriority priority, ProjectId projectReferenceToAdd) : base(originalDocument, textChanges, title, tags, priority) { // We only want to add a project reference if the project the import references // is different from the project we started from. if (projectReferenceToAdd != originalDocument.Project.Id) { _projectReferenceToAdd = projectReferenceToAdd; } } internal override bool PerformFinalApplicabilityCheck => _projectReferenceToAdd != null; internal override bool IsApplicable(Workspace workspace) => _projectReferenceToAdd != null && workspace.CanAddProjectReference(OriginalDocument.Project.Id, _projectReferenceToAdd); protected override Project UpdateProject(Project project) { return _projectReferenceToAdd == null ? project : project.AddProjectReference(new ProjectReference(_projectReferenceToAdd)); } } } }
mit
C#
e70a14b83093d3c85e6b6d0c04fe9a78691f149d
Enable testing in emulated or actual device mode
crosswalk-project/crosswalk-extensions-twoinone,crosswalk-project/crosswalk-extensions-twoinone,crosswalk-project/crosswalk-extensions-twoinone
twoinone-windows-test/TwoinoneTest.cs
twoinone-windows-test/TwoinoneTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace xwalk { class TwoinoneTest { static void Main(string[] args) { if (args.Length > 0 && args[0] == "emulator") { runEmulator(); } else { run(); } } static void run() { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); Console.WriteLine("Tablet mode " + monitor.IsTablet); } } } static void runEmulator() { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); bool isTabletEmulated = monitor.IsTablet; // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); isTabletEmulated = !isTabletEmulated; emulator.IsTablet = isTabletEmulated; } } } private static void onTabletModeChanged(bool isTablet) { Console.WriteLine("onTabletModeChanged: " + isTablet); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace xwalk { class TwoinoneTest { static void Main(string[] args) { Emulator emulator = new Emulator(); TabletMonitor monitor = new TabletMonitor(emulator); monitor.TabletModeDelegate = onTabletModeChanged; monitor.start(); Console.WriteLine("Main: " + monitor.IsTablet); bool isTabletEmulated = monitor.IsTablet; // Fudge mainloop int tick = 0; while (true) { Thread.Sleep(500); Console.Write("."); tick++; if (tick % 10 == 0) { Console.WriteLine(""); isTabletEmulated = !isTabletEmulated; emulator.IsTablet = isTabletEmulated; } } } private static void onTabletModeChanged(bool isTablet) { Console.WriteLine("onTabletModeChanged: " + isTablet); } } }
bsd-3-clause
C#
aa795f05d7e242eaaa55b11b99f32e44abcdfcab
make SetValue work with JToken null
JSONAPIdotNET/JSONAPI.NET,SathishN/JSONAPI.NET,SphtKr/JSONAPI.NET,danshapir/JSONAPI.NET
JSONAPI/Core/EnumAttributeValueConverter.cs
JSONAPI/Core/EnumAttributeValueConverter.cs
using System; using System.Reflection; using Newtonsoft.Json.Linq; namespace JSONAPI.Core { /// <summary> /// Implementation of <see cref="IAttributeValueConverter" /> suitable for /// use converting between enum CLR properties and integer attributes. /// </summary> public class EnumAttributeValueConverter : IAttributeValueConverter { private readonly PropertyInfo _property; private readonly Type _enumType; private readonly bool _isNullable; /// <summary> /// Creates a new EnumAttributeValueConverter /// </summary> /// <param name="property"></param> /// <param name="enumType"></param> /// <param name="isNullable"></param> public EnumAttributeValueConverter(PropertyInfo property, Type enumType, bool isNullable) { _property = property; _enumType = enumType; _isNullable = isNullable; } public JToken GetValue(object resource) { var value = _property.GetValue(resource); if (value != null) return (int) value; if (_isNullable) return null; return 0; } public void SetValue(object resource, JToken value) { if (value == null || value.Type == JTokenType.Null) { if (_isNullable) _property.SetValue(resource, null); else { var enumValue = Enum.Parse(_enumType, "0"); _property.SetValue(resource, enumValue); } } else { var enumValue = Enum.Parse(_enumType, value.ToString()); _property.SetValue(resource, enumValue); } } } }
using System; using System.Reflection; using Newtonsoft.Json.Linq; namespace JSONAPI.Core { /// <summary> /// Implementation of <see cref="IAttributeValueConverter" /> suitable for /// use converting between enum CLR properties and integer attributes. /// </summary> public class EnumAttributeValueConverter : IAttributeValueConverter { private readonly PropertyInfo _property; private readonly Type _enumType; private readonly bool _isNullable; /// <summary> /// Creates a new EnumAttributeValueConverter /// </summary> /// <param name="property"></param> /// <param name="enumType"></param> /// <param name="isNullable"></param> public EnumAttributeValueConverter(PropertyInfo property, Type enumType, bool isNullable) { _property = property; _enumType = enumType; _isNullable = isNullable; } public JToken GetValue(object resource) { var value = _property.GetValue(resource); if (value != null) return (int) value; if (_isNullable) return null; return 0; } public void SetValue(object resource, JToken value) { if (value == null) { if (_isNullable) _property.SetValue(resource, null); else { var enumValue = Enum.Parse(_enumType, "0"); _property.SetValue(resource, enumValue); } } else { var enumValue = Enum.Parse(_enumType, value.ToString()); _property.SetValue(resource, enumValue); } } } }
mit
C#
52fa1e7cebd83c12fa557b1e8a649a6ba815ab78
Add interval-value comparer
skonves/Konves.Collections
Konves.Collections.ObjectModel/Comparers.cs
Konves.Collections.ObjectModel/Comparers.cs
using System; using System.Collections; using System.Collections.Generic; namespace Konves.Collections.ObjectModel { public class IntervalComparer<TBound> : IComparer<IInterval<TBound>> where TBound : IComparable<TBound> { public int Compare(IInterval<TBound> x, IInterval<TBound> y) { int lowerUpper = x.LowerBound.Value.CompareTo(y.UpperBound.Value); if (lowerUpper > 0 || (lowerUpper == 0 && (!x.LowerBound.IsInclusive || !y.UpperBound.IsInclusive))) return 1; int upperLower = x.UpperBound.Value.CompareTo(y.LowerBound.Value); if (upperLower < 0 || (upperLower == 0 && (!x.UpperBound.IsInclusive || !y.LowerBound.IsInclusive))) return -1; return 0; } } public class IntervalValueComparer<TBound> : IComparer where TBound : IComparable<TBound> { public int Compare(object x, object y) { IInterval<TBound> interval = x as IInterval<TBound>; TBound value; if (!ReferenceEquals(interval, null) && y is TBound) { value = (TBound) y; } else { interval = y as IInterval<TBound>; if (!ReferenceEquals(interval, null) && x is TBound) { value = (TBound) x; } else { throw new ArgumentException("'x' cannot be compared to 'y'"); } } int valueLower = value.CompareTo(interval.LowerBound.Value); if (valueLower < 0 || (valueLower == 0 && !interval.LowerBound.IsInclusive)) return -1; int valueUpper = value.CompareTo(interval.UpperBound.Value); if (valueUpper > 0 || (valueUpper == 0 && !interval.UpperBound.IsInclusive)) return 1; return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Konves.Collections.ObjectModel { public class IntervalComparer<TBound> : IComparer<IInterval<TBound>> where TBound : IComparable<TBound> { public int Compare(IInterval<TBound> x, IInterval<TBound> y) { int lowerUpper = x.LowerBound.Value.CompareTo(y.UpperBound.Value); if (lowerUpper > 0 || (lowerUpper == 0 && (!x.LowerBound.IsInclusive || !y.UpperBound.IsInclusive))) return 1; int upperLower = x.UpperBound.Value.CompareTo(y.LowerBound.Value); if (upperLower < 0 || (upperLower == 0 && (!x.UpperBound.IsInclusive || !y.LowerBound.IsInclusive))) return -1; return 0; } } }
apache-2.0
C#
cafd5d06b4d795234d155dd4148b8b460739eea5
Enable the user to choose PNG file as thumbnail.
allenlooplee/Lbookshelf
Lbookshelf/Utils/ChangeThumbnailBehavior.cs
Lbookshelf/Utils/ChangeThumbnailBehavior.cs
using Lbookshelf.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interactivity; namespace Lbookshelf.Utils { public class ChangeThumbnailBehavior : Behavior<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonUp += ShowChooseThumbnailDialog; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonUp -= ShowChooseThumbnailDialog; } private void ShowChooseThumbnailDialog(object sender, System.Windows.Input.MouseButtonEventArgs e) { DialogService.ShowOpenFileDialog( fileName => { // Note that when editing a book, we are actually // editing a clone of the original book. // The changes can be safely discarded if the user // cancel the edit. So feel free to change the // value of Thumbnail. The BookManager is responsible // for copying the new thumbnail. var book = (Book)AssociatedObject.DataContext; book.Thumbnail = fileName; }, "Image files|*.jpg;*.png", ".jpg"); } } }
using Lbookshelf.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interactivity; namespace Lbookshelf.Utils { public class ChangeThumbnailBehavior : Behavior<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonUp += ShowChooseThumbnailDialog; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonUp -= ShowChooseThumbnailDialog; } private void ShowChooseThumbnailDialog(object sender, System.Windows.Input.MouseButtonEventArgs e) { DialogService.ShowOpenFileDialog( fileName => { // Note that when editing a book, we are actually // editing a clone of the original book. // The changes can be safely discarded if the user // cancel the edit. So feel free to change the // value of Thumbnail. The BookManager is responsible // for copying the new thumbnail. var book = (Book)AssociatedObject.DataContext; book.Thumbnail = fileName; }, "Image files|*.jpg", ".jpg"); } } }
mit
C#
b3cd2d1b7dde5c377463577357f4400b3ccddc91
clean up code
maxlmo/outlook-matters,maxlmo/outlook-matters,makmu/outlook-matters,makmu/outlook-matters
OutlookMatters/Mattermost/RestMattermost.cs
OutlookMatters/Mattermost/RestMattermost.cs
using System; using Newtonsoft.Json; using OutlookMatters.Http; namespace OutlookMatters.Mattermost { public class RestMattermost: IMattermost { private readonly ISessionFactory _sessionFactory; private readonly IHttpClient _client; public RestMattermost(ISessionFactory sessionFactory, IHttpClient client) { _sessionFactory = sessionFactory; _client = client; } public ISession LoginByUsername(string url, string teamId, string username, string password) { var loginUrl = new Uri(new Uri(url), "api/v1/users/login"); var login = new Login { name = teamId, email = username, password = password }; var response = _client.Post(loginUrl) .WithContentType("text/json") .Send(JsonConvert.SerializeObject(login)); var token = response.GetHeaderValue("Token"); var payload = response.GetPayload(); var user = JsonConvert.DeserializeObject<User>(payload); return _sessionFactory.CreateSession(new Uri(url), token, user.id); } } }
using System; using Newtonsoft.Json; using OutlookMatters.Http; namespace OutlookMatters.Mattermost { public class RestMattermost: IMattermost { private readonly ISessionFactory _sessionFactory; private readonly IHttpClient _client; public RestMattermost(ISessionFactory sessionFactory, IHttpClient _client) { _sessionFactory = sessionFactory; this._client = _client; } public ISession LoginByUsername(string url, string teamId, string username, string password) { var loginUrl = new Uri(new Uri(url), "api/v1/users/login"); var login = new Login { name = teamId, email = username, password = password }; var response = _client.Post(loginUrl) .WithContentType("text/json") .Send(JsonConvert.SerializeObject(login)); var token = response.GetHeaderValue("Token"); var payload = response.GetPayload(); var user = JsonConvert.DeserializeObject<User>(payload); return _sessionFactory.CreateSession(new Uri(url), token, user.id); } } }
mit
C#
2d829dc3539b86d5ee1c7e2116bf45bdea3318ca
Fix compilation error in sample
VirusFree/SharpDX,fmarrabal/SharpDX,sharpdx/SharpDX,davidlee80/SharpDX-1,andrewst/SharpDX,mrvux/SharpDX,manu-silicon/SharpDX,davidlee80/SharpDX-1,shoelzer/SharpDX,PavelBrokhman/SharpDX,TigerKO/SharpDX,fmarrabal/SharpDX,weltkante/SharpDX,fmarrabal/SharpDX,VirusFree/SharpDX,RobyDX/SharpDX,shoelzer/SharpDX,PavelBrokhman/SharpDX,RobyDX/SharpDX,sharpdx/SharpDX,wyrover/SharpDX,fmarrabal/SharpDX,weltkante/SharpDX,waltdestler/SharpDX,weltkante/SharpDX,wyrover/SharpDX,manu-silicon/SharpDX,TigerKO/SharpDX,TechPriest/SharpDX,shoelzer/SharpDX,PavelBrokhman/SharpDX,TigerKO/SharpDX,manu-silicon/SharpDX,wyrover/SharpDX,davidlee80/SharpDX-1,waltdestler/SharpDX,TechPriest/SharpDX,RobyDX/SharpDX,shoelzer/SharpDX,Ixonos-USA/SharpDX,Ixonos-USA/SharpDX,jwollen/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX,TechPriest/SharpDX,jwollen/SharpDX,mrvux/SharpDX,sharpdx/SharpDX,andrewst/SharpDX,PavelBrokhman/SharpDX,dazerdude/SharpDX,weltkante/SharpDX,andrewst/SharpDX,VirusFree/SharpDX,davidlee80/SharpDX-1,mrvux/SharpDX,dazerdude/SharpDX,dazerdude/SharpDX,Ixonos-USA/SharpDX,manu-silicon/SharpDX,jwollen/SharpDX,VirusFree/SharpDX,dazerdude/SharpDX,TechPriest/SharpDX,waltdestler/SharpDX,Ixonos-USA/SharpDX,RobyDX/SharpDX,wyrover/SharpDX,jwollen/SharpDX,shoelzer/SharpDX
Samples/Toolkit/Desktop/MiniCube/Program.cs
Samples/Toolkit/Desktop/MiniCube/Program.cs
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // 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; namespace MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new MiniCubeGame()) program.Run(); } } }
// Copyright (c) 2010-2012 SharpDX - Alexandre Mutel // // 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; namespace MiniCube { /// <summary> /// Simple MiniCube application using SharpDX.Toolkit. /// </summary> class Program { /// <summary> /// Defines the entry point of the application. /// </summary> #if NETFX_CORE [MTAThread] #else [STAThread] #endif static void Main() { using (var program = new SphereGame()) program.Run(); } } }
mit
C#
de6931a9ebbcaea4254fa51197f37e7068d30f1e
Update release version
ninjanye/SearchExtensions
SearchExtensions/Properties/AssemblyInfo.cs
SearchExtensions/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("NinjaNye.SearchExtensions")] [assembly: AssemblyDescription("A collection of extension methods to IQueryable and IENumerable that enable easy searching and ranking")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("John Nye")] [assembly: AssemblyProduct("NinjaNye.SearchExtensions")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("0d7ebeb0-64e0-43e8-b10a-d63839cbd56c")] // 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.3.*")] [assembly: AssemblyFileVersion("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("NinjaNye.SearchExtensions")] [assembly: AssemblyDescription("A collection of extension methods to IQueryable that enable easy searching and ranking")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("John Nye")] [assembly: AssemblyProduct("NinjaNye.SearchExtensions")] [assembly: AssemblyCopyright("Copyright © 2013")] [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("0d7ebeb0-64e0-43e8-b10a-d63839cbd56c")] // 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.*")] [assembly: AssemblyFileVersion("0.2")]
mit
C#
0c0fb257e47839808da573d4217aa6332db98c07
Disable SSL checks for now
AlmirKadric/mage-sdk-unity,mage/mage-sdk-unity
Mage/Mage.cs
Mage/Mage.cs
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Net; using Newtonsoft.Json.Linq; public class MageSetupStatus { public bool done = false; public Exception error = null; } public class Mage : Singleton<Mage> { // public EventManager eventManager; public Session session; public RPCClient rpcClient; public MessageStream messageStream; public Archivist archivist; private ConsoleWriter _consoleWriter; private Logger _logger; // private Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>(); public Logger logger (string context = null) { if (string.IsNullOrEmpty(context)) { context = "Default"; } if (_loggers.ContainsKey(context)) { return _loggers[context]; } Logger newLogger = new Logger (context); _loggers.Add (context, new Logger(context)); return newLogger; } // public Mage() { eventManager = new EventManager(); session = new Session(); rpcClient = new RPCClient(); messageStream = new MessageStream(); archivist = new Archivist(); _consoleWriter = new ConsoleWriter (); _logger = logger("mage"); // TODO: properly check the damn certificate, for now ignore invalid ones (fix issue on Android/iOS) ServicePointManager.ServerCertificateValidationCallback += (o, cert, chain, errors) => true; } // public void setEndpoints (string baseUrl, string appName, string username = null, string password = null) { rpcClient.setEndpoint (baseUrl, appName, username, password); messageStream.setEndpoint (baseUrl, username, password); } // public void setup (List<string> moduleNames, Action<Exception> cb) { _logger.info ("Setting up modules"); Async.each<string> (moduleNames, (string moduleName, Action<Exception> callback) => { _logger.info("Setting up module: " + moduleName); // Use reflection to find module by name Assembly assembly = Assembly.GetExecutingAssembly(); Type[] assemblyTypes = assembly.GetTypes(); foreach(Type t in assemblyTypes) { if (moduleName == t.Name) { // Invoke the setup method on the module BindingFlags memberType = BindingFlags.InvokeMethod; object[] arguments = new object[]{callback}; t.InvokeMember("setupInstance", memberType, null, null, arguments); return; } } // If nothing found throw an error callback(new Exception("Can't find module " + moduleName)); }, (Exception error) => { if (error != null) { _logger.data(error).error("Setup failed!"); cb(error); return; } _logger.info("Setup complete"); cb(null); }); } public IEnumerator setupTask (List<string> moduleNames, Action<Exception> cb) { // Execute async setup function MageSetupStatus setupStatus = new MageSetupStatus (); setup(moduleNames, (Exception error) => { setupStatus.error = error; setupStatus.done = true; }); // Wait for setup to return while (!setupStatus.done) { yield return null; } // Call callback with error if there is one cb (setupStatus.error); } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Newtonsoft.Json.Linq; public class MageSetupStatus { public bool done = false; public Exception error = null; } public class Mage : Singleton<Mage> { // public EventManager eventManager; public Session session; public RPCClient rpcClient; public MessageStream messageStream; public Archivist archivist; private ConsoleWriter _consoleWriter; private Logger _logger; // private Dictionary<string, Logger> _loggers = new Dictionary<string, Logger>(); public Logger logger (string context = null) { if (string.IsNullOrEmpty(context)) { context = "Default"; } if (_loggers.ContainsKey(context)) { return _loggers[context]; } Logger newLogger = new Logger (context); _loggers.Add (context, new Logger(context)); return newLogger; } // public Mage() { eventManager = new EventManager(); session = new Session(); rpcClient = new RPCClient(); messageStream = new MessageStream(); archivist = new Archivist(); _consoleWriter = new ConsoleWriter (); _logger = logger("mage"); } // public void setEndpoints (string baseUrl, string appName, string username = null, string password = null) { rpcClient.setEndpoint (baseUrl, appName, username, password); messageStream.setEndpoint (baseUrl, username, password); } // public void setup (List<string> moduleNames, Action<Exception> cb) { _logger.info ("Setting up modules"); Async.each<string> (moduleNames, (string moduleName, Action<Exception> callback) => { _logger.info("Setting up module: " + moduleName); // Use reflection to find module by name Assembly assembly = Assembly.GetExecutingAssembly(); Type[] assemblyTypes = assembly.GetTypes(); foreach(Type t in assemblyTypes) { if (moduleName == t.Name) { // Invoke the setup method on the module BindingFlags memberType = BindingFlags.InvokeMethod; object[] arguments = new object[]{callback}; t.InvokeMember("setupInstance", memberType, null, null, arguments); return; } } // If nothing found throw an error callback(new Exception("Can't find module " + moduleName)); }, (Exception error) => { if (error != null) { _logger.data(error).error("Setup failed!"); cb(error); return; } _logger.info("Setup complete"); cb(null); }); } public IEnumerator setupTask (List<string> moduleNames, Action<Exception> cb) { // Execute async setup function MageSetupStatus setupStatus = new MageSetupStatus (); setup(moduleNames, (Exception error) => { setupStatus.error = error; setupStatus.done = true; }); // Wait for setup to return while (!setupStatus.done) { yield return null; } // Call callback with error if there is one cb (setupStatus.error); } }
mit
C#
fbdea1fc8a628c841e10981b020c2d44fd93c212
Update CastSpellParams.cs (#3894)
LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE
Source/ACE.Server/Entity/CastSpellParams.cs
Source/ACE.Server/Entity/CastSpellParams.cs
using ACE.Entity.Enum; using ACE.Server.WorldObjects; namespace ACE.Server.Entity { public class CastSpellParams { public Spell Spell { get; set; } //public bool IsWeaponSpell { get; set; } public WorldObject Caster { get; set; } public uint MagicSkill { get; set; } public uint ManaUsed { get; set; } public WorldObject Target { get; set; } public Player.CastingPreCheckStatus Status { get; set; } public bool HasWindupGestures => !Spell.Flags.HasFlag(SpellFlags.FastCast) && Caster == null && Spell.Formula.HasWindupGestures; public CastSpellParams(Spell spell, WorldObject caster, uint magicSkill, uint manaUsed, WorldObject target, Player.CastingPreCheckStatus status) { Spell = spell; //IsWeaponSpell = isWeaponSpell; Caster = caster; MagicSkill = magicSkill; ManaUsed = manaUsed; Target = target; Status = status; } public override string ToString() { var targetName = Target != null ? Target.Name : "null"; return $"{Spell.Name}, {Caster?.Name}, {MagicSkill}, {ManaUsed}, {targetName}, {Status}"; } } }
using ACE.Entity.Enum; using ACE.Server.WorldObjects; namespace ACE.Server.Entity { public class CastSpellParams { public Spell Spell { get; set; } //public bool IsWeaponSpell { get; set; } public WorldObject Caster { get; set; } public uint MagicSkill { get; set; } public uint ManaUsed { get; set; } public WorldObject Target { get; set; } public Player.CastingPreCheckStatus Status { get; set; } public bool HasWindupGestures => !Spell.Flags.HasFlag(SpellFlags.FastCast) && Caster != null && Spell.Formula.HasWindupGestures; public CastSpellParams(Spell spell, WorldObject caster, uint magicSkill, uint manaUsed, WorldObject target, Player.CastingPreCheckStatus status) { Spell = spell; //IsWeaponSpell = isWeaponSpell; Caster = caster; MagicSkill = magicSkill; ManaUsed = manaUsed; Target = target; Status = status; } public override string ToString() { var targetName = Target != null ? Target.Name : "null"; return $"{Spell.Name}, {Caster?.Name}, {MagicSkill}, {ManaUsed}, {targetName}, {Status}"; } } }
agpl-3.0
C#
05f9fa1ee753e2468b1d8bc9f6643f2eddf86cf7
Update ML info assertion (#5872) (#5875)
elastic/elasticsearch-net,elastic/elasticsearch-net
tests/Tests/XPack/MachineLearning/MachineLearningInfo/MachineLearningInfoApiTests.cs
tests/Tests/XPack/MachineLearning/MachineLearningInfo/MachineLearningInfoApiTests.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Transport; using FluentAssertions; using Nest; using Tests.Core.Client; using Tests.Core.Extensions; using Tests.Framework.EndpointTests.TestState; namespace Tests.XPack.MachineLearning.MachineLearningInfo { public class MachineLearningInfoApiTests : MachineLearningIntegrationTestBase<MachineLearningInfoResponse, IMachineLearningInfoRequest, MachineLearningInfoDescriptor, MachineLearningInfoRequest> { public MachineLearningInfoApiTests(MachineLearningCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override object ExpectJson => null; protected override int ExpectStatusCode => 200; protected override Func<MachineLearningInfoDescriptor, IMachineLearningInfoRequest> Fluent => f => f; protected override HttpMethod HttpMethod => HttpMethod.GET; protected override MachineLearningInfoRequest Initializer => new MachineLearningInfoRequest(); protected override string UrlPath => $"_ml/info"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.MachineLearning.Info(f), (client, f) => client.MachineLearning.InfoAsync(f), (client, r) => client.MachineLearning.Info(r), (client, r) => client.MachineLearning.InfoAsync(r) ); protected override MachineLearningInfoDescriptor NewDescriptor() => new MachineLearningInfoDescriptor(); protected override void ExpectResponse(MachineLearningInfoResponse response) { response.ShouldBeValid(); var anomalyDetectors = response.Defaults.AnomalyDetectors; anomalyDetectors.ModelMemoryLimit.Should().Be("1gb"); anomalyDetectors.CategorizationExamplesLimit.Should().Be(4); anomalyDetectors.ModelSnapshotRetentionDays.Should().Be(TestClient.Configuration.InRange(">=7.8.0") ? 10 : 1); if (TestClient.Configuration.InRange(">=7.8.0")) anomalyDetectors.DailyModelSnapshotRetentionAfterDays.Should().Be(1); response.Defaults.Datafeeds.ScrollSize.Should().Be(1000); if (Cluster.ClusterConfiguration.Version >= "7.6.0") { var analyzer = anomalyDetectors.CategorizationAnalyzer; analyzer.Should().NotBeNull(); analyzer.Tokenizer.Should().Be(TestClient.Configuration.InRange("<7.14.0") ? "ml_classic" : "ml_standard"); analyzer.Filter.Should().NotBeNullOrEmpty(); } if (TestClient.Configuration.InRange(">=7.8.0")) response.Limits.EffectiveMaxModelMemoryLimit.Should().NotBeNullOrEmpty(); } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Transport; using FluentAssertions; using Nest; using Tests.Core.Client; using Tests.Core.Extensions; using Tests.Framework.EndpointTests.TestState; namespace Tests.XPack.MachineLearning.MachineLearningInfo { public class MachineLearningInfoApiTests : MachineLearningIntegrationTestBase<MachineLearningInfoResponse, IMachineLearningInfoRequest, MachineLearningInfoDescriptor, MachineLearningInfoRequest> { public MachineLearningInfoApiTests(MachineLearningCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override bool ExpectIsValid => true; protected override object ExpectJson => null; protected override int ExpectStatusCode => 200; protected override Func<MachineLearningInfoDescriptor, IMachineLearningInfoRequest> Fluent => f => f; protected override HttpMethod HttpMethod => HttpMethod.GET; protected override MachineLearningInfoRequest Initializer => new MachineLearningInfoRequest(); protected override string UrlPath => $"_ml/info"; protected override LazyResponses ClientUsage() => Calls( (client, f) => client.MachineLearning.Info(f), (client, f) => client.MachineLearning.InfoAsync(f), (client, r) => client.MachineLearning.Info(r), (client, r) => client.MachineLearning.InfoAsync(r) ); protected override MachineLearningInfoDescriptor NewDescriptor() => new MachineLearningInfoDescriptor(); protected override void ExpectResponse(MachineLearningInfoResponse response) { response.ShouldBeValid(); var anomalyDetectors = response.Defaults.AnomalyDetectors; anomalyDetectors.ModelMemoryLimit.Should().Be("1gb"); anomalyDetectors.CategorizationExamplesLimit.Should().Be(4); anomalyDetectors.ModelSnapshotRetentionDays.Should().Be(TestClient.Configuration.InRange(">=7.8.0") ? 10 : 1); if (TestClient.Configuration.InRange(">=7.8.0")) anomalyDetectors.DailyModelSnapshotRetentionAfterDays.Should().Be(1); response.Defaults.Datafeeds.ScrollSize.Should().Be(1000); if (Cluster.ClusterConfiguration.Version >= "7.6.0") { var analyzer = anomalyDetectors.CategorizationAnalyzer; analyzer.Should().NotBeNull(); analyzer.Tokenizer.Should().Be("ml_classic"); analyzer.Filter.Should().NotBeNullOrEmpty(); } if (TestClient.Configuration.InRange(">=7.8.0")) response.Limits.EffectiveMaxModelMemoryLimit.Should().NotBeNullOrEmpty(); } } }
apache-2.0
C#
cf1a378390e23567907a0fc7ac5ecf262e6c7d1e
Update CurrencyFactory.cs
tiksn/TIKSN-Framework
TIKSN.Core/Globalization/CurrencyFactory.cs
TIKSN.Core/Globalization/CurrencyFactory.cs
using System; using System.Globalization; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using TIKSN.Data.Cache.Memory; using TIKSN.Finance; namespace TIKSN.Globalization { public class CurrencyFactory : MemoryCacheDecoratorBase<CurrencyInfo>, ICurrencyFactory { private readonly IOptions<CurrencyUnionRedirectionOptions> _currencyUnionRedirectionOptions; private readonly IOptions<RegionalCurrencyRedirectionOptions> _regionalCurrencyRedirectionOptions; private readonly IRegionFactory _regionFactory; public CurrencyFactory( IMemoryCache memoryCache, IRegionFactory regionFactory, IOptions<RegionalCurrencyRedirectionOptions> regionalCurrencyRedirectionOptions, IOptions<CurrencyUnionRedirectionOptions> currencyUnionRedirectionOptions, IOptions<MemoryCacheDecoratorOptions> genericOptions, IOptions<MemoryCacheDecoratorOptions<CurrencyInfo>> specificOptions) : base(memoryCache, genericOptions, specificOptions) { this._regionFactory = regionFactory; this._regionalCurrencyRedirectionOptions = regionalCurrencyRedirectionOptions; this._currencyUnionRedirectionOptions = currencyUnionRedirectionOptions; } public CurrencyInfo Create(string isoCurrencySymbol) { if (this._currencyUnionRedirectionOptions.Value.CurrencyUnionRedirections.TryGetValue(isoCurrencySymbol, out var redirectedRegion)) { return this.Create(this._regionFactory.Create(redirectedRegion)); } var cacheKey = Tuple.Create(entityType, isoCurrencySymbol.ToUpperInvariant()); return this.GetFromMemoryCache(cacheKey, () => new CurrencyInfo(isoCurrencySymbol)); } public CurrencyInfo Create(RegionInfo region) { if (this._regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections.ContainsKey(region.Name)) { region = this._regionFactory.Create( this._regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections[region.Name]); } else if (this._regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections.ContainsKey( region.TwoLetterISORegionName)) { region = this._regionFactory.Create( this._regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections[ region.TwoLetterISORegionName]); } var cacheKey = Tuple.Create(entityType, region.ISOCurrencySymbol); return this.GetFromMemoryCache(cacheKey, () => new CurrencyInfo(region)); } } }
using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Options; using System; using System.Globalization; using TIKSN.Data.Cache.Memory; using TIKSN.Finance; namespace TIKSN.Globalization { public class CurrencyFactory : MemoryCacheDecoratorBase<CurrencyInfo>, ICurrencyFactory { private readonly IRegionFactory _regionFactory; private readonly IOptions<RegionalCurrencyRedirectionOptions> _regionalCurrencyRedirectionOptions; private readonly IOptions<CurrencyUnionRedirectionOptions> _currencyUnionRedirectionOptions; public CurrencyFactory( IMemoryCache memoryCache, IRegionFactory regionFactory, IOptions<RegionalCurrencyRedirectionOptions> regionalCurrencyRedirectionOptions, IOptions<CurrencyUnionRedirectionOptions> currencyUnionRedirectionOptions, IOptions<MemoryCacheDecoratorOptions> genericOptions, IOptions<MemoryCacheDecoratorOptions<CurrencyInfo>> specificOptions) : base(memoryCache, genericOptions, specificOptions) { _regionFactory = regionFactory; _regionalCurrencyRedirectionOptions = regionalCurrencyRedirectionOptions; _currencyUnionRedirectionOptions = currencyUnionRedirectionOptions; } public CurrencyInfo Create(string isoCurrencySymbol) { if (_currencyUnionRedirectionOptions.Value.CurrencyUnionRedirections.TryGetValue(isoCurrencySymbol, out string redirectedRegion)) return Create(_regionFactory.Create(redirectedRegion)); var cacheKey = Tuple.Create(entityType, isoCurrencySymbol.ToUpperInvariant()); return GetFromMemoryCache(cacheKey, () => new CurrencyInfo(isoCurrencySymbol)); } public CurrencyInfo Create(RegionInfo region) { if (_regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections.ContainsKey(region.Name)) region = _regionFactory.Create(_regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections[region.Name]); else if (_regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections.ContainsKey(region.TwoLetterISORegionName)) region = _regionFactory.Create(_regionalCurrencyRedirectionOptions.Value.RegionalCurrencyRedirections[region.TwoLetterISORegionName]); var cacheKey = Tuple.Create(entityType, region.ISOCurrencySymbol); return GetFromMemoryCache(cacheKey, () => new CurrencyInfo(region)); } } }
mit
C#
3357df01ed45642b065550172ae715b2b05c1ebb
FIx HelenaX second hit effect
bunashibu/kikan
Assets/Scripts/Skill/Helena/HelenaX.cs
Assets/Scripts/Skill/Helena/HelenaX.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Bunashibu.Kikan { [RequireComponent(typeof(SkillSynchronizer))] public class HelenaX : Skill { void Awake() { _synchronizer = GetComponent<SkillSynchronizer>(); _hitRistrictor = new HitRistrictor(_hitInfo); MonoUtility.Instance.StoppableDelaySec(_existTime, "HelenaXFalse" + GetInstanceID().ToString(), () => { if (gameObject == null) return; gameObject.SetActive(false); // NOTE: Wait 5.0f in order to ensure value synchronization when hit at max range distance. MonoUtility.Instance.StoppableDelaySec(5.0f, "HelenaXDestroy" + GetInstanceID().ToString(), () => { if (gameObject == null) return; Destroy(gameObject); }); }); } void Start() { if (photonView.isMine) _moveDirection = transform.eulerAngles.y == 180 ? Vector2.right : Vector2.left; } void Update() { if (photonView.isMine) transform.Translate(_moveDirection * _spd * Time.deltaTime, Space.World); } void OnTriggerEnter2D(Collider2D collider) { if (PhotonNetwork.isMasterClient) { var target = collider.gameObject.GetComponent<IPhoton>(); if (target == null) return; if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj)) return; if (_hitRistrictor.ShouldRistrict(collider.gameObject)) return; DamageCalculator.Calculate(_skillUserObj, _attackInfo); if (_isSecond) _synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, (int)(DamageCalculator.Damage * _secondRatio), DamageCalculator.IsCritical, HitEffectType.Helena); else { _synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena); _isSecond = true; } } } void OnDestroy() { if (photonView.isMine && SkillReference.Instance != null) SkillReference.Instance.Remove(viewID); } [SerializeField] private AttackInfo _attackInfo; [SerializeField] private HitInfo _hitInfo; private Vector2 _moveDirection; private SkillSynchronizer _synchronizer; private HitRistrictor _hitRistrictor; private float _spd = 8.0f; private float _existTime = 0.37f; private bool _isSecond; private float _secondRatio = 0.5f; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Bunashibu.Kikan { [RequireComponent(typeof(SkillSynchronizer))] public class HelenaX : Skill { void Awake() { _synchronizer = GetComponent<SkillSynchronizer>(); _hitRistrictor = new HitRistrictor(_hitInfo); MonoUtility.Instance.StoppableDelaySec(_existTime, "HelenaXFalse" + GetInstanceID().ToString(), () => { if (gameObject == null) return; gameObject.SetActive(false); // NOTE: Wait 5.0f in order to ensure value synchronization when hit at max range distance. MonoUtility.Instance.StoppableDelaySec(5.0f, "HelenaXDestroy" + GetInstanceID().ToString(), () => { if (gameObject == null) return; Destroy(gameObject); }); }); } void Start() { if (photonView.isMine) _moveDirection = transform.eulerAngles.y == 180 ? Vector2.right : Vector2.left; } void Update() { if (photonView.isMine) transform.Translate(_moveDirection * _spd * Time.deltaTime, Space.World); } void OnTriggerEnter2D(Collider2D collider) { if (PhotonNetwork.isMasterClient) { var target = collider.gameObject.GetComponent<IPhoton>(); if (target == null) return; if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj)) return; if (_hitRistrictor.ShouldRistrict(collider.gameObject)) return; DamageCalculator.Calculate(_skillUserObj, _attackInfo); if (_isSecond) _synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, (int)(DamageCalculator.Damage * _secondRatio), DamageCalculator.IsCritical, HitEffectType.Nage); else { _synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena); _isSecond = true; } } } void OnDestroy() { if (photonView.isMine && SkillReference.Instance != null) SkillReference.Instance.Remove(viewID); } [SerializeField] private AttackInfo _attackInfo; [SerializeField] private HitInfo _hitInfo; private Vector2 _moveDirection; private SkillSynchronizer _synchronizer; private HitRistrictor _hitRistrictor; private float _spd = 8.0f; private float _existTime = 0.37f; private bool _isSecond; private float _secondRatio = 0.5f; } }
mit
C#
cf6aa18d13dfedb431a4019ee5610c2d9ffcf357
Rename of local variables
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade/Core/Addml/Definitions/FieldIndex.cs
src/Arkivverket.Arkade/Core/Addml/Definitions/FieldIndex.cs
using Arkivverket.Arkade.ExternalModels.Addml; using Arkivverket.Arkade.Util; namespace Arkivverket.Arkade.Core.Addml.Definitions { internal class FieldIndex { private readonly string _flatFileDefinitionName; private readonly string _recordDefinitionName; private readonly string _fieldDefinitionName; public FieldIndex(string flatFileDefinitionName, string recordDefinitionName, string fieldDefinitionName) { Assert.AssertNotNullOrEmpty("flatFileDefinitionName", flatFileDefinitionName); Assert.AssertNotNullOrEmpty("recordDefinitionName", recordDefinitionName); Assert.AssertNotNullOrEmpty("fieldDefinitionName", fieldDefinitionName); _flatFileDefinitionName = flatFileDefinitionName; _recordDefinitionName = recordDefinitionName; _fieldDefinitionName = fieldDefinitionName; } public FieldIndex(flatFileDefinition flatFileDefinition, recordDefinition recordDefinition, fieldDefinition fieldDefinition) : this(flatFileDefinition.name, recordDefinition.name, fieldDefinition.name) { } public FieldIndex(flatFileDefinitionReference flatFileDefinitionReference, recordDefinitionReference recordDefinitionReference, fieldDefinitionReference fieldDefinitionReference) : this(flatFileDefinitionReference.name, recordDefinitionReference.name, fieldDefinitionReference.name) { } protected bool Equals(FieldIndex other) { return string.Equals(_flatFileDefinitionName, other._flatFileDefinitionName) && string.Equals(_recordDefinitionName, other._recordDefinitionName) && string.Equals(_fieldDefinitionName, other._fieldDefinitionName); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((FieldIndex) obj); } public override int GetHashCode() { unchecked { int hashCode = _flatFileDefinitionName.GetHashCode(); hashCode = (hashCode*397) ^ _recordDefinitionName.GetHashCode(); hashCode = (hashCode*397) ^ _fieldDefinitionName.GetHashCode(); return hashCode; } } } }
using Arkivverket.Arkade.ExternalModels.Addml; using Arkivverket.Arkade.Util; namespace Arkivverket.Arkade.Core.Addml.Definitions { internal class FieldIndex { private readonly string _flatFileDefinitionReference; private readonly string _recordDefinitionReference; private readonly string _fieldDefinitionReference; public FieldIndex(string flatFileDefinitionReference, string recordDefinitionReference, string fieldDefinitionReference) { Assert.AssertNotNullOrEmpty("flatFileDefinitionReference", flatFileDefinitionReference); Assert.AssertNotNullOrEmpty("recordDefinitionReference", recordDefinitionReference); Assert.AssertNotNullOrEmpty("fieldDefinitionReference", fieldDefinitionReference); _flatFileDefinitionReference = flatFileDefinitionReference; _recordDefinitionReference = recordDefinitionReference; _fieldDefinitionReference = fieldDefinitionReference; } public FieldIndex(flatFileDefinition flatFileDefinition, recordDefinition recordDefinition, fieldDefinition fieldDefinition) : this(flatFileDefinition.name, recordDefinition.name, fieldDefinition.name) { } public FieldIndex(flatFileDefinitionReference flatFileDefinitionReference, recordDefinitionReference recordDefinitionReference, fieldDefinitionReference fieldDefinitionReference) : this(flatFileDefinitionReference.name, recordDefinitionReference.name, fieldDefinitionReference.name) { } protected bool Equals(FieldIndex other) { return string.Equals(_flatFileDefinitionReference, other._flatFileDefinitionReference) && string.Equals(_recordDefinitionReference, other._recordDefinitionReference) && string.Equals(_fieldDefinitionReference, other._fieldDefinitionReference); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((FieldIndex) obj); } public override int GetHashCode() { unchecked { int hashCode = _flatFileDefinitionReference.GetHashCode(); hashCode = (hashCode*397) ^ _recordDefinitionReference.GetHashCode(); hashCode = (hashCode*397) ^ _fieldDefinitionReference.GetHashCode(); return hashCode; } } } }
agpl-3.0
C#
70cd22ab740330b4ce4a3ff0b092864d717740b4
Fix AutoSuggestBox being focused when going back to Schedules page.
betrakiss/Tramline-5,betrakiss/Tramline-5
src/TramlineFive/TramlineFive/Views/Pages/Schedules.xaml.cs
src/TramlineFive/TramlineFive/Views/Pages/Schedules.xaml.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using TramlineFive.Common.Models; using TramlineFive.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using TramlineFive.Common.Managers; using TramlineFive.ViewModels.Wrappers; using TramlineFive.Views.Dialogs; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace TramlineFive.Views.Pages { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Schedules : Page { public AllLinesViewModel LineViewModel { get; private set; } public Schedules() { this.InitializeComponent(); this.Transitions = AnimationManager.GeneratePageTransitions(); this.LineViewModel = new AllLinesViewModel(); this.DataContext = LineViewModel; this.NavigationCacheMode = NavigationCacheMode.Enabled; this.Loaded += OnLoaded; } private async void OnLoaded(object sender, RoutedEventArgs e) { await LineViewModel.LoadAndGroupLinesAsync(); lvLines.Focus(FocusState.Programmatic); } private void OnSchedulesItemClick(object sender, ItemClickEventArgs e) { Frame.Navigate(typeof(Direction), e.ClickedItem); } private void OnSuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args) { Frame.Navigate(typeof(Direction), args.SelectedItem); } private void OnTextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) { sender.ItemsSource = LineViewModel.Lines.Where(l => l.NumberString.Contains(sender.Text)); } } private void OnBackClick(object sender, RoutedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame.CanGoBack) rootFrame.GoBack(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using TramlineFive.Common.Models; using TramlineFive.ViewModels; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using TramlineFive.Common.Managers; using TramlineFive.ViewModels.Wrappers; using TramlineFive.Views.Dialogs; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace TramlineFive.Views.Pages { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Schedules : Page { public AllLinesViewModel LineViewModel { get; private set; } public Schedules() { this.InitializeComponent(); this.Transitions = AnimationManager.GeneratePageTransitions(); this.LineViewModel = new AllLinesViewModel(); this.DataContext = LineViewModel; this.NavigationCacheMode = NavigationCacheMode.Enabled; this.Loaded += OnLoaded; } private async void OnLoaded(object sender, RoutedEventArgs e) { await LineViewModel.LoadAndGroupLinesAsync(); } private void OnSchedulesItemClick(object sender, ItemClickEventArgs e) { Frame.Navigate(typeof(Direction), e.ClickedItem); } private void OnSuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args) { Frame.Navigate(typeof(Direction), args.SelectedItem); } private void OnTextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args) { if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput) { sender.ItemsSource = LineViewModel.Lines.Where(l => l.NumberString.Contains(sender.Text)); } } private void OnBackClick(object sender, RoutedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; if (rootFrame.CanGoBack) rootFrame.GoBack(); } } }
apache-2.0
C#
cc0aa83eeccac1208efec7446d6003f4ace315ad
make odata response compatible with system.text.json
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/Universal/Bit.Universal.Http/Contracts/ODataResponse.cs
src/Universal/Bit.Universal.Http/Contracts/ODataResponse.cs
using Newtonsoft.Json; using System.Text.Json.Serialization; namespace Bit.Http.Contracts { public class ODataResponse<T> { [JsonProperty("value")] [JsonPropertyName("value")] public virtual T Value { get; set; } = default!; [JsonProperty("@odata.context")] [JsonPropertyName("@odata.context")] public virtual string? Context { get; set; } /// <summary> /// It can be requested by $count=true in query string of your request. /// </summary> [JsonProperty("@odata.count")] [JsonPropertyName("@odata.count")] public virtual long? TotalCount { get; set; } } }
using Newtonsoft.Json; namespace Bit.Http.Contracts { public class ODataResponse<T> { [JsonProperty("value")] public virtual T Value { get; set; } = default!; [JsonProperty("@odata.context")] public virtual string? Context { get; set; } /// <summary> /// It can be requested by $count=true in query string of your request. /// </summary> [JsonProperty("@odata.count")] public virtual long? TotalCount { get; set; } } }
mit
C#
352b0b4b3fb5d7e8b6a561dbf5a21921a3533be8
Use expression body
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/Controls/Dialog.xaml.cs
WalletWasabi.Fluent/Controls/Dialog.xaml.cs
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; namespace WalletWasabi.Fluent.Controls { /// <summary> /// A simple overlay Dialog control. /// </summary> public class Dialog : ContentControl { public static readonly StyledProperty<bool> IsDialogOpenProperty = AvaloniaProperty.Register<Dialog, bool>(nameof(IsDialogOpen)); public static readonly StyledProperty<double> MaxContentHeightProperty = AvaloniaProperty.Register<Dialog, double>(nameof(MaxContentHeight), double.PositiveInfinity); public static readonly StyledProperty<double> MaxContentWidthProperty = AvaloniaProperty.Register<Dialog, double>(nameof(MaxContentWidth), double.PositiveInfinity); public bool IsDialogOpen { get => GetValue(IsDialogOpenProperty); set => SetValue(IsDialogOpenProperty, value); } public double MaxContentHeight { get => GetValue(MaxContentHeightProperty); set => SetValue(MaxContentHeightProperty, value); } public double MaxContentWidth { get => GetValue(MaxContentWidthProperty); set => SetValue(MaxContentWidthProperty, value); } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == IsDialogOpenProperty) { PseudoClasses.Set(":open", change.NewValue.GetValueOrDefault<bool>()); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); var overlayButton = e.NameScope.Find<Panel>("PART_Overlay"); overlayButton.PointerPressed += (_, __) => IsDialogOpen = false; } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Primitives; namespace WalletWasabi.Fluent.Controls { /// <summary> /// A simple overlay Dialog control. /// </summary> public class Dialog : ContentControl { public static readonly StyledProperty<bool> IsDialogOpenProperty = AvaloniaProperty.Register<Dialog, bool>(nameof(IsDialogOpen)); public static readonly StyledProperty<double> MaxContentHeightProperty = AvaloniaProperty.Register<Dialog, double>(nameof(MaxContentHeight), double.PositiveInfinity); public static readonly StyledProperty<double> MaxContentWidthProperty = AvaloniaProperty.Register<Dialog, double>(nameof(MaxContentWidth), double.PositiveInfinity); public bool IsDialogOpen { get => GetValue(IsDialogOpenProperty); set => SetValue(IsDialogOpenProperty, value); } public double MaxContentHeight { get { return GetValue(MaxContentHeightProperty); } set { SetValue(MaxContentHeightProperty, value); } } public double MaxContentWidth { get { return GetValue(MaxContentWidthProperty); } set { SetValue(MaxContentWidthProperty, value); } } protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change) { base.OnPropertyChanged(change); if (change.Property == IsDialogOpenProperty) { PseudoClasses.Set(":open", change.NewValue.GetValueOrDefault<bool>()); } } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); var overlayButton = e.NameScope.Find<Panel>("PART_Overlay"); overlayButton.PointerPressed += (_, __) => IsDialogOpen = false; } } }
mit
C#
fda19b5a8f05b5aa1b37e4149450864501c49bad
Change 'Echos' to 'Echoes' (#964)
AntiTcb/Discord.Net,RogueException/Discord.Net
docs/guides/commands/samples/module.cs
docs/guides/commands/samples/module.cs
// Create a module with no prefix public class Info : ModuleBase<SocketCommandContext> { // ~say hello -> hello [Command("say")] [Summary("Echoes a message.")] public async Task SayAsync([Remainder] [Summary("The text to echo")] string echo) { // ReplyAsync is a method on ModuleBase await ReplyAsync(echo); } } // Create a module with the 'sample' prefix [Group("sample")] public class Sample : ModuleBase<SocketCommandContext> { // ~sample square 20 -> 400 [Command("square")] [Summary("Squares a number.")] public async Task SquareAsync([Summary("The number to square.")] int num) { // We can also access the channel from the Command Context. await Context.Channel.SendMessageAsync($"{num}^2 = {Math.Pow(num, 2)}"); } // ~sample userinfo --> foxbot#0282 // ~sample userinfo @Khionu --> Khionu#8708 // ~sample userinfo Khionu#8708 --> Khionu#8708 // ~sample userinfo Khionu --> Khionu#8708 // ~sample userinfo 96642168176807936 --> Khionu#8708 // ~sample whois 96642168176807936 --> Khionu#8708 [Command("userinfo")] [Summary("Returns info about the current user, or the user parameter, if one passed.")] [Alias("user", "whois")] public async Task UserInfoAsync([Summary("The (optional) user to get info for")] SocketUser user = null) { var userInfo = user ?? Context.Client.CurrentUser; await ReplyAsync($"{userInfo.Username}#{userInfo.Discriminator}"); } }
// Create a module with no prefix public class Info : ModuleBase<SocketCommandContext> { // ~say hello -> hello [Command("say")] [Summary("Echos a message.")] public async Task SayAsync([Remainder] [Summary("The text to echo")] string echo) { // ReplyAsync is a method on ModuleBase await ReplyAsync(echo); } } // Create a module with the 'sample' prefix [Group("sample")] public class Sample : ModuleBase<SocketCommandContext> { // ~sample square 20 -> 400 [Command("square")] [Summary("Squares a number.")] public async Task SquareAsync([Summary("The number to square.")] int num) { // We can also access the channel from the Command Context. await Context.Channel.SendMessageAsync($"{num}^2 = {Math.Pow(num, 2)}"); } // ~sample userinfo --> foxbot#0282 // ~sample userinfo @Khionu --> Khionu#8708 // ~sample userinfo Khionu#8708 --> Khionu#8708 // ~sample userinfo Khionu --> Khionu#8708 // ~sample userinfo 96642168176807936 --> Khionu#8708 // ~sample whois 96642168176807936 --> Khionu#8708 [Command("userinfo")] [Summary("Returns info about the current user, or the user parameter, if one passed.")] [Alias("user", "whois")] public async Task UserInfoAsync([Summary("The (optional) user to get info for")] SocketUser user = null) { var userInfo = user ?? Context.Client.CurrentUser; await ReplyAsync($"{userInfo.Username}#{userInfo.Discriminator}"); } }
mit
C#
8f1800568a9fd78f742e93c437a790babae65756
Add overloads
bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,mavasani/roslyn,mavasani/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,dotnet/roslyn
src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingSearchHelpers.cs
src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingSearchHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingSearchQuery { public readonly string FullyQualifiedTypeName; public readonly string? MethodName; public readonly int MethodArity; public readonly int MethodParameterCount; public UnitTestingSearchQuery(string fullyQualifiedTypeName) : this(fullyQualifiedTypeName, methodName: null, methodArity: 0, methodParameterCount: 0, unused: false) { } public UnitTestingSearchQuery(string fullyQualifiedTypeName, string methodName, int methodArity, int methodParameterCount) : this(fullyQualifiedTypeName, methodName, methodArity, methodParameterCount, unused: false) { } private UnitTestingSearchQuery(string fullyQualifiedTypeName, string methodName, int methodArity, int methodParameterCount, bool unused) { _ = unused; FullyQualifiedTypeName = fullyQualifiedTypeName; MethodName = methodName; MethodArity = methodArity; MethodParameterCount = methodParameterCount; } } internal readonly record struct UnitTestingNavigationOptions( bool PreferProvisionalTab = false, bool ActivateTab = true) { public UnitTestingNavigationOptions() : this(PreferProvisionalTab: false) { } } internal readonly struct UnitTestingDocumentSpan { private readonly DocumentSpan _documentSpan; internal UnitTestingDocumentSpan(DocumentSpan documentSpan, FileLinePositionSpan span) { _documentSpan = documentSpan; Span = span; } public FileLinePositionSpan Span { get; } public async Task NavigateToAsync(UnitTestingNavigationOptions options, CancellationToken cancellationToken) { var location = await _documentSpan.GetNavigableLocationAsync(cancellationToken).ConfigureAwait(false); if (location != null) await location.NavigateToAsync(new NavigationOptions(options.PreferProvisionalTab, options.ActivateTab), cancellationToken).ConfigureAwait(false); } internal static class UnitTestingSearchHelpers { public static async Task<ImmutableArray<UnitTestingDocumentSpan>> GetSourceLocations( Solution solution, UnitTestingSearchQuery query, CancellationToken cancellationToken) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingSearchQuery { public readonly string FullyQualifiedTypeName; public readonly string? MethodName; public readonly int MethodArity; public readonly int MethodParameterCount; public UnitTestingSearchQuery(string fullyQualifiedTypeName, string? methodName, int methodArity, int methodParameterCount) { FullyQualifiedTypeName = fullyQualifiedTypeName; MethodName = methodName; MethodArity = methodArity; MethodParameterCount = methodParameterCount; } } internal readonly record struct UnitTestingNavigationOptions( bool PreferProvisionalTab = false, bool ActivateTab = true) { public UnitTestingNavigationOptions() : this(PreferProvisionalTab: false) { } } internal readonly struct UnitTestingDocumentSpan { private readonly DocumentSpan _documentSpan; internal UnitTestingDocumentSpan(DocumentSpan documentSpan, FileLinePositionSpan span) { _documentSpan = documentSpan; Span = span; } public FileLinePositionSpan Span { get; } public async Task NavigateToAsync(UnitTestingNavigationOptions options, CancellationToken cancellationToken) { var location = await _documentSpan.GetNavigableLocationAsync(cancellationToken).ConfigureAwait(false); if (location != null) await location.NavigateToAsync(new NavigationOptions(options.PreferProvisionalTab, options.ActivateTab), cancellationToken).ConfigureAwait(false); } internal static class UnitTestingSearchHelpers { public static async Task<ImmutableArray<UnitTestingDocumentSpan>> GetSourceLocations( Solution solution, UnitTestingSearchQuery query, CancellationToken cancellationToken) { } } } }
mit
C#
4c52edd1e6532f0283cfe1bbc44792d1f7831043
Add method ToString to override default display and replace by Caption
Seddryck/NBi,Seddryck/NBi
NBi.Core/Analysis/Metadata/Property.cs
NBi.Core/Analysis/Metadata/Property.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Analysis.Metadata { public class Property : IField { public string UniqueName { get; private set; } public string Caption { get; set; } public Property(string uniqueName, string caption) { UniqueName = uniqueName; Caption = caption; } public Property Clone() { return new Property(UniqueName, Caption); } public override string ToString() { return Caption.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NBi.Core.Analysis.Metadata { public class Property : IField { public string UniqueName { get; private set; } public string Caption { get; set; } public Property(string uniqueName, string caption) { UniqueName = uniqueName; Caption = caption; } public Property Clone() { return new Property(UniqueName, Caption); } } }
apache-2.0
C#
f38b01793fc6cdf5bef041ce5cd443779eb6852d
add manual pipeline status
Xarlot/NGitLab
NGitLab/NGitLab/Models/PipelineData.cs
NGitLab/NGitLab/Models/PipelineData.cs
using System.Runtime.Serialization; namespace NGitLab.Models { public enum PipelineStatus { undefined, pending, success, created, failed, aborted, running, canceled, skipped, manual, } [DataContract] public class PipelineData { [DataMember(Name = "id")] public int Id { get; set; } [DataMember(Name = "status")] public PipelineStatus Status { get; set; } [DataMember(Name = "ref")] public string Ref { get; set; } [DataMember(Name = "sha")] public Sha1 Sha1 { get; set; } } }
using System.Runtime.Serialization; namespace NGitLab.Models { public enum PipelineStatus { undefined, pending, success, created, failed, aborted, running, canceled, skipped, } [DataContract] public class PipelineData { [DataMember(Name = "id")] public int Id { get; set; } [DataMember(Name = "status")] public PipelineStatus Status { get; set; } [DataMember(Name = "ref")] public string Ref { get; set; } [DataMember(Name = "sha")] public Sha1 Sha1 { get; set; } } }
mit
C#
ffb59513f48842b35f1bdcc85cfa31fa5e924e96
Build problem fixed
tanyta78/CSharpOOPGame
BACKTOBG/BackToBg.Business/Business/PlayerActions/Actions/PauseMenuAction.cs
BACKTOBG/BackToBg.Business/Business/PlayerActions/Actions/PauseMenuAction.cs
using BackToBg.Core.Business.Attributes; using BackToBg.Core.Business.Menu; using BackToBg.Core.Business.UtilityInterfaces; namespace BackToBg.Core.Business.PlayerActions.Actions { [PlayerAction("Escape")] public class PauseMenuAction : PlayerAction { [Inject] private IReader reader; [Inject] private IWriter writer; [Inject] private IEngine engine; public override void Execute() { var pauseMenu = new PauseMenu("Pause", this.reader, this.writer, this.engine); pauseMenu.StartMenu(); } } }
using BackToBg.Core.Business.Attributes; using BackToBg.Core.Business.Menu; using BackToBg.Core.Business.UtilityInterfaces; namespace BackToBg.Core.Business.PlayerActions.Actions { [PlayerAction("Escape")] public class PauseMenuAction : PlayerAction { [Inject] private IReader reader; [Inject] private IWriter writer; [Inject] private IEngine engine; [Inject] private IEngine engine; public override void Execute() { var pauseMenu = new PauseMenu("Pause", this.reader, this.writer, this.engine); pauseMenu.StartMenu(); } } }
mit
C#
e9ee1e030a2a949434b71e78dc4ada71e78e31a6
remove hard coded credentials
lderache/LeTruck,lderache/LeTruck,lderache/LeTruck
src/mvc5/TheTruck.Web/DataContexts/IdentityMigrations/Configuration.cs
src/mvc5/TheTruck.Web/DataContexts/IdentityMigrations/Configuration.cs
namespace TheTruck.Web.DataContexts.IdentityMigrations { using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Models; using System.Configuration; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<TheTruck.Web.DataContexts.IdentityDb> { public Configuration() { AutomaticMigrationsEnabled = false; MigrationsDirectory = @"DataContexts\IdentityMigrations"; } protected override void Seed(TheTruck.Web.DataContexts.IdentityDb context) { var adminEmail = ConfigurationManager.AppSettings["adminEmail"]; var adminPassword = ConfigurationManager.AppSettings["adminPassword"]; if (!context.Users.Any(u => u.UserName == adminEmail)) { // Roles var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var role = new IdentityRole { Name = "admin" }; roleManager.Create(role); // Admin user var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = new ApplicationUser { UserName = adminEmail, EmailConfirmed = true }; userManager.Create(user, adminPassword); // Add the role to admin user userManager.AddToRole(user.Id, role.Name); } } } }
namespace TheTruck.Web.DataContexts.IdentityMigrations { using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Models; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<TheTruck.Web.DataContexts.IdentityDb> { public Configuration() { AutomaticMigrationsEnabled = false; MigrationsDirectory = @"DataContexts\IdentityMigrations"; } protected override void Seed(TheTruck.Web.DataContexts.IdentityDb context) { if (!context.Users.Any(u => u.UserName == "laurent.derache@gmail.com")) { // Roles var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var role = new IdentityRole { Name = "admin" }; roleManager.Create(role); // Admin user var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); var user = new ApplicationUser { UserName = "laurent.derache@gmail.com" }; userManager.Create(user, "password"); // Add the role to admin user userManager.AddToRole(user.Id, role.Name); } } } }
mit
C#
a29b36b854655ee808e30f6f4ee7e7dd5d5cc277
throw error for invalid input
alexperovich/buildtools,weshaggard/buildtools,ericstj/buildtools,nguerrera/buildtools,crummel/dotnet_buildtools,alexperovich/buildtools,weshaggard/buildtools,mmitche/buildtools,mmitche/buildtools,mmitche/buildtools,stephentoub/buildtools,alexperovich/buildtools,weshaggard/buildtools,joperezr/buildtools,crummel/dotnet_buildtools,ericstj/buildtools,mmitche/buildtools,stephentoub/buildtools,joperezr/buildtools,nguerrera/buildtools,nguerrera/buildtools,stephentoub/buildtools,ericstj/buildtools,joperezr/buildtools,nguerrera/buildtools,MattGal/buildtools,MattGal/buildtools,weshaggard/buildtools,MattGal/buildtools,ericstj/buildtools,stephentoub/buildtools,MattGal/buildtools,joperezr/buildtools,MattGal/buildtools,alexperovich/buildtools,joperezr/buildtools,crummel/dotnet_buildtools,alexperovich/buildtools,mmitche/buildtools,crummel/dotnet_buildtools
src/xunit.netcore.extensions/Discoverers/ConditionalClassDiscoverer.cs
src/xunit.netcore.extensions/Discoverers/ConditionalClassDiscoverer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Xunit.Abstractions; using Xunit.Sdk; namespace Xunit.NetCore.Extensions { /// <summary> /// This class discovers all of the tests and test classes that have /// applied the ConditionalClass attribute /// </summary> public class ConditionalClassDiscoverer : ITraitDiscoverer { /// <summary> /// Gets the trait values from the Category attribute. /// </summary> /// <param name="traitAttribute">The trait attribute containing the trait values.</param> /// <returns>The trait values.</returns> public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute) { // If evaluated to false, skip the test class entirely. if (!EvaluateParameterHelper(traitAttribute)) { yield return new KeyValuePair<string, string>(XunitConstants.Category, XunitConstants.Failing); } } internal static bool EvaluateParameterHelper(IAttributeInfo traitAttribute) { // Parse the traitAttribute. We make sure it contains two parts: // 1. Type 2. nameof(conditionMemberName) object[] conditionArguments = traitAttribute.GetConstructorArguments().ToArray(); Debug.Assert(conditionArguments.Count() == 2); Type calleeType = null; string[] conditionMemberNames = null; if (ConditionalTestDiscoverer.CheckInputToSkipExecution(conditionArguments, ref calleeType, ref conditionMemberNames)) { return true; } foreach (string entry in conditionMemberNames) { // Null condition member names are silently tolerated. if (string.IsNullOrWhiteSpace(entry)) continue; MethodInfo conditionMethodInfo = ConditionalTestDiscoverer.LookupConditionalMethod(calleeType, entry); if (conditionMethodInfo == null) { throw new InvalidOperationException($"Unable to get MethodInfo, please check input for {entry}."); } // If one of the conditions is false, then return the category failing trait. if (!(bool)conditionMethodInfo.Invoke(null, null)) return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Xunit.Abstractions; using Xunit.Sdk; namespace Xunit.NetCore.Extensions { /// <summary> /// This class discovers all of the tests and test classes that have /// applied the ConditionalClass attribute /// </summary> public class ConditionalClassDiscoverer : ITraitDiscoverer { /// <summary> /// Gets the trait values from the Category attribute. /// </summary> /// <param name="traitAttribute">The trait attribute containing the trait values.</param> /// <returns>The trait values.</returns> public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute) { // If evaluated to false, skip the test class entirely. if (!EvaluateParameterHelper(traitAttribute)) { yield return new KeyValuePair<string, string>(XunitConstants.Category, XunitConstants.Failing); } } internal static bool EvaluateParameterHelper(IAttributeInfo traitAttribute) { // Parse the traitAttribute. We make sure it contains two parts: // 1. Type 2. nameof(conditionMemberName) object[] conditionArguments = traitAttribute.GetConstructorArguments().ToArray(); Debug.Assert(conditionArguments.Count() == 2); Type calleeType = null; string[] conditionMemberNames = null; if (ConditionalTestDiscoverer.CheckInputToSkipExecution(conditionArguments, ref calleeType, ref conditionMemberNames)) { return true; } foreach (string entry in conditionMemberNames) { // Null condition member names are silently tolerated. if (string.IsNullOrWhiteSpace(entry)) continue; MethodInfo conditionMethodInfo = ConditionalTestDiscoverer.LookupConditionalMethod(calleeType, entry); Debug.Assert(conditionMethodInfo != null, $"Unable to get MethodInfo, please check input for {entry}."); // If one of the conditions is false, then return the category failing trait. if (!(bool)conditionMethodInfo.Invoke(null, null)) return false; } return true; } } }
mit
C#
64e800187ddfd6e419a9bea5c298f5452a470943
disable namespace resharper autofix
RetireNet/dotnet-retire,RetireNet/dotnet-retire
RetireRuntimeMiddleware/RetireRunTimeMiddlewareExtensions.cs
RetireRuntimeMiddleware/RetireRunTimeMiddlewareExtensions.cs
using RetireRuntimeMiddleware.Middlewares; // ReSharper disable once CheckNamespace // On purpose to avoid cluttering hosts with new package namespace namespace Microsoft.AspNetCore.Builder { public static class RetireRunTimeMiddlewareExtensions { public static IApplicationBuilder UseRuntimeVulnerabilityReport(this IApplicationBuilder builder) { return builder.UseMiddleware<RetireRunTimeMiddleware>(); } } }
using RetireRuntimeMiddleware.Middlewares; namespace Microsoft.AspNetCore.Builder { public static class RetireRunTimeMiddlewareExtensions { public static IApplicationBuilder UseRuntimeVulnerabilityReport(this IApplicationBuilder builder) { return builder.UseMiddleware<RetireRunTimeMiddleware>(); } } }
mit
C#
45924abd66fefb31e55d79592271ce0c708288d8
Add test files to tree
smo-key/NXTLib,smo-key/NXTLib
tests/nxtlibtester/Program.cs
tests/nxtlibtester/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NXTLib; using System.IO; namespace nxtlibtester { class Program { static void Main(string[] args) { try { string filename = "../../version.ric"; //filename on disk (locally) string filenameonbrick = "version.ric"; //filename on remote NXT //Prepare Connection Console.WriteLine("File Upload Test\r\n"); Console.WriteLine("Connecting to brick..."); Brick brick = new Brick(Brick.LinkType.USB, null); //Brick = top layer of code, contains the sensors and motors if (!brick.Connect()) { throw new Exception(brick.LastError); } Protocol protocol = brick.ProtocolLink; //Protocol = underlying layer of code, contains NXT communications //Test Connection if (!brick.IsConnected) { throw new Exception("Not connected to NXT!"); } //Upload File Console.WriteLine("Uploading file..."); if (!brick.UploadFile(filename, filenameonbrick)) { throw new Exception(brick.LastError); } Console.WriteLine("Success!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NXTLib; using System.IO; namespace nxtlibtester { class Program { static void Main(string[] args) { try { string filename = "version.ric"; //filename on disk (locally) string filenameonbrick = "version.ric"; //filename on remote NXT //Prepare Connection Console.WriteLine("File Upload Test\r\n"); Console.WriteLine("Connecting to brick..."); Brick brick = new Brick(Brick.LinkType.USB, null); //Brick = top layer of code, contains the sensors and motors if (!brick.Connect()) { throw new Exception(brick.LastError); } Protocol protocol = brick.ProtocolLink; //Protocol = underlying layer of code, contains NXT communications //Test Connection if (!brick.IsConnected) { throw new Exception("Not connected to NXT!"); } //Upload File Console.WriteLine("Uploading file..."); if (!brick.UploadFile(filename, filenameonbrick)) { throw new Exception(brick.LastError); } Console.WriteLine("Success!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); Console.WriteLine("Press any key to continue..."); Console.ReadKey(true); return; } } } }
mit
C#
7c6ec990d2795d8618fd9a0f81f09b39c18b93d6
Fix issue building demo
proyecto26/RestClient
demo/Assets/MainScript.cs
demo/Assets/MainScript.cs
using UnityEngine; using UnityEditor; using Models; using Proyecto26; using System.Collections.Generic; public class MainScript : MonoBehaviour { private readonly string basePath = "https://jsonplaceholder.typicode.com"; public void Get(){ // We can add default request headers for all requests RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ..."; RequestHelper requestOptions = null; RestClient.GetArray<Post>(basePath + "/posts").Then(res => { EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok"); return RestClient.GetArray<Todo>(basePath + "/todos"); }).Then(res => { EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok"); return RestClient.GetArray<User>(basePath + "/users"); }).Then(res => { EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok"); // We can add specific options and override default headers for a request requestOptions = new RequestHelper { url = basePath + "/photos", headers = new Dictionary<string, string> { { "Authorization", "Other token..." } } }; return RestClient.GetArray<Photo>(requestOptions); }).Then(res => { EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok"); // And later we can clean the default headers for all requests RestClient.CleanDefaultHeaders(); }).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Post(){ RestClient.Post<Models.Post>(basePath + "/posts", new { title = "foo", body = "bar", userId = 1 }) .Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok")) .Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Put(){ RestClient.Put<Post>(basePath + "/posts/1", new { title = "foo", body = "bar", userId = 1 }, (err, res, body) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok"); } }); } public void Delete(){ RestClient.Delete(basePath + "/posts/1", (err, res) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok"); } }); } }
using UnityEngine; using UnityEditor; using Models; using Proyecto26; using System.Collections.Generic; public class MainScript : MonoBehaviour { private readonly string basePath = "https://jsonplaceholder.typicode.com"; public void Get(){ // We can add default request headers for all requests RestClient.DefaultRequestHeaders["Authorization"] = "Bearer ..."; RequestHelper requestOptions; RestClient.GetArray<Post>(basePath + "/posts").Then(res => { EditorUtility.DisplayDialog ("Posts", JsonHelper.ArrayToJsonString<Post>(res, true), "Ok"); return RestClient.GetArray<Todo>(basePath + "/todos"); }).Then(res => { EditorUtility.DisplayDialog ("Todos", JsonHelper.ArrayToJsonString<Todo>(res, true), "Ok"); return RestClient.GetArray<User>(basePath + "/users"); }).Then(res => { EditorUtility.DisplayDialog ("Users", JsonHelper.ArrayToJsonString<User>(res, true), "Ok"); // We can add specific options and override default headers for a request requestOptions = new RequestHelper { url = basePath + "/photos", headers = new Dictionary<string, string> { { "Authorization", "Other token..." } } }; return RestClient.GetArray<Photo>(requestOptions); }).Then(res => { EditorUtility.DisplayDialog("Header", requestOptions.GetHeader("Authorization"), "Ok"); // And later we can clean the default headers for all requests RestClient.CleanDefaultHeaders(); }).Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Post(){ RestClient.Post<Models.Post>(basePath + "/posts", new { title = "foo", body = "bar", userId = 1 }) .Then(res => EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(res, true), "Ok")) .Catch(err => EditorUtility.DisplayDialog ("Error", err.Message, "Ok")); } public void Put(){ RestClient.Put<Post>(basePath + "/posts/1", new { title = "foo", body = "bar", userId = 1 }, (err, res, body) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", JsonUtility.ToJson(body, true), "Ok"); } }); } public void Delete(){ RestClient.Delete(basePath + "/posts/1", (err, res) => { if(err != null){ EditorUtility.DisplayDialog ("Error", err.Message, "Ok"); } else{ EditorUtility.DisplayDialog ("Success", "Status: " + res.statusCode.ToString(), "Ok"); } }); } }
mit
C#
ce21eee1554d7e31afff4c09e699af05a5fad577
replace target-typed object creation
jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,grokys/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia
tests/Avalonia.Visuals.UnitTests/Rendering/SceneGraph/LineNodeTests.cs
tests/Avalonia.Visuals.UnitTests/Rendering/SceneGraph/LineNodeTests.cs
using System.Collections.Generic; using Avalonia.Media; using Avalonia.Rendering.SceneGraph; using Xunit; namespace Avalonia.Visuals.UnitTests.Rendering.SceneGraph { public class LineNodeTests { [Fact] public void HitTest_Should_Be_True() { var lineNode = new LineNode( Matrix.Identity, new Pen(Brushes.Black, 3), new Point(15, 15), new Point(150, 150)); var pointsInside = new List<Point>() { new Point(14, 14), new Point(15, 15), new Point(32.1, 30), new Point(30, 32.1), new Point(150, 150), new Point(151, 151), }; foreach (var point in pointsInside) { Assert.True(lineNode.HitTest(point)); } } [Fact] public void HitTest_Should_Be_False() { var lineNode = new LineNode( Matrix.Identity, new Pen(Brushes.Black, 3), new Point(15, 15), new Point(150, 150)); var pointsOutside= new List<Point>() { new Point(13.9, 13.9), new Point(30, 32.2), new Point(32.2, 30), new Point(151.1, 151.1), new Point(200, 200), }; foreach (var point in pointsOutside) { Assert.False(lineNode.HitTest(point)); } } } }
using System.Collections.Generic; using Avalonia.Media; using Avalonia.Rendering.SceneGraph; using Xunit; namespace Avalonia.Visuals.UnitTests.Rendering.SceneGraph { public class LineNodeTests { [Fact] public void HitTest_Should_Be_True() { var lineNode = new LineNode( Matrix.Identity, new Pen(Brushes.Black, 3), new Point(15, 15), new Point(150, 150)); List<Point> pointsInside = new() { new Point(14, 14), new Point(15, 15), new Point(32.1, 30), new Point(30, 32.1), new Point(150, 150), new Point(151, 151), }; foreach (var point in pointsInside) { Assert.True(lineNode.HitTest(point)); } } [Fact] public void HitTest_Should_Be_False() { var lineNode = new LineNode( Matrix.Identity, new Pen(Brushes.Black, 3), new Point(15, 15), new Point(150, 150)); List<Point> pointsOutside= new() { new Point(13.9, 13.9), new Point(30, 32.2), new Point(32.2, 30), new Point(151.1, 151.1), new Point(200, 200), }; foreach (var point in pointsOutside) { Assert.False(lineNode.HitTest(point)); } } } }
mit
C#
72526229f70863a8edc6f319169cbae19d9c620d
Update UnixTimeToDateTimeOffsetJsonConverter; fix #17
arthurrump/Zermelo.API
Zermelo.API/Helpers/UnixTimeToDateTimeOffsetJsonConverter.cs
Zermelo.API/Helpers/UnixTimeToDateTimeOffsetJsonConverter.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zermelo.API.Helpers { internal class UnixTimeToDateTimeOffsetJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { if (objectType == typeof(DateTimeOffset) || objectType == typeof(int) || objectType == typeof(long)) return true; return false; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object value = reader.Value; if (value == null) return null; long ticks = (long)value; DateTimeOffset d = UnixTimeHelpers.FromUnixTimeSeconds(ticks); return d; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { long ticks; if (value is DateTimeOffset d) { ticks = UnixTimeHelpers.ToUnixTimeSeconds(d.UtcDateTime); } else { throw new JsonSerializationException($"Expected {nameof(DateTimeOffset)} object value."); } writer.WriteValue(ticks); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zermelo.API.Helpers { internal class UnixTimeToDateTimeOffsetJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { if (objectType == typeof(DateTimeOffset) || objectType == typeof(int) || objectType == typeof(long)) return true; return false; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object value = reader.Value; if (value == null) return null; long ticks = (long)value; DateTimeOffset d = UnixTimeHelpers.FromUnixTimeSeconds(ticks); return d; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { long ticks; if (value is DateTimeOffset) { DateTimeOffset dateTimeOffset = (DateTimeOffset)value; DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime(); ticks = UnixTimeHelpers.ToUnixTimeSeconds(utcDateTimeOffset.UtcDateTime); } else { throw new JsonSerializationException($"Expected {nameof(DateTimeOffset)} object value."); } writer.WriteStartConstructor("Date"); writer.WriteValue(ticks); writer.WriteEndConstructor(); } } }
mit
C#
c105ae3ab08d95e2c94afd5b1126c8e4bcabed16
Fix name of changelog tests
amcoder/Curse.RestProxy
Curse.RestProxy.Tests/Controllers/AddOnFilesControllerChangelogTests.cs
Curse.RestProxy.Tests/Controllers/AddOnFilesControllerChangelogTests.cs
using System; using System.Threading.Tasks; using System.Web.Http.Results; using Curse.RestProxy.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Curse.RestProxy.Tests.Controllers { [TestClass] public class AddOnFilesControllerChangelogTests { [TestMethod] public void ChangelogReturnsOkWhenFileFound() { var changelog = "changes"; var addOnService = Mock.Of<AddOnService.IAddOnService>(s => s.v2GetChangeLogAsync(1, 2) == Task.FromResult(changelog) ); var controller = new AddOnFilesController(addOnService); var result = controller.Changelog(1, 2).Result; Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<string>), "Get should return Ok when the file is found"); } [TestMethod] public void ChangelogReturnsResultFromAddOnService() { var changelog = "changes"; var addOnService = Mock.Of<AddOnService.IAddOnService>(s => s.v2GetChangeLogAsync(1, 2) == Task.FromResult(changelog) ); var controller = new AddOnFilesController(addOnService); var result = controller.Changelog(1, 2).Result as OkNegotiatedContentResult<string>; Assert.AreEqual(changelog, result.Content, "Get should return result from the addon service"); } [TestMethod] public void ChangelogReturnsNotFoundWhenFileDoesNotExist() { var addOnService = Mock.Of<AddOnService.IAddOnService>(s => s.v2GetChangeLogAsync(1, 2) == Task.FromResult((string)null) ); var controller = new AddOnFilesController(addOnService); var result = controller.Changelog(1, 2).Result; Assert.IsInstanceOfType(result, typeof(NotFoundResult), "Get should return not found when file does not exist"); } } }
using System; using System.Threading.Tasks; using System.Web.Http.Results; using Curse.RestProxy.Controllers; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Curse.RestProxy.Tests.Controllers { [TestClass] public class AddOnFilesControllerChangelogTests { [TestMethod] public void GetReturnsOkWhenFileFound() { var changelog = "changes"; var addOnService = Mock.Of<AddOnService.IAddOnService>(s => s.v2GetChangeLogAsync(1, 2) == Task.FromResult(changelog) ); var controller = new AddOnFilesController(addOnService); var result = controller.Changelog(1, 2).Result; Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<string>), "Get should return Ok when the file is found"); } [TestMethod] public void GetReturnsResultFromAddOnService() { var changelog = "changes"; var addOnService = Mock.Of<AddOnService.IAddOnService>(s => s.v2GetChangeLogAsync(1, 2) == Task.FromResult(changelog) ); var controller = new AddOnFilesController(addOnService); var result = controller.Changelog(1, 2).Result as OkNegotiatedContentResult<string>; Assert.AreEqual(changelog, result.Content, "Get should return result from the addon service"); } [TestMethod] public void GetReturnsNotFoundWhenFileDoesNotExist() { var addOnService = Mock.Of<AddOnService.IAddOnService>(s => s.v2GetChangeLogAsync(1, 2) == Task.FromResult((string)null) ); var controller = new AddOnFilesController(addOnService); var result = controller.Changelog(1, 2).Result; Assert.IsInstanceOfType(result, typeof(NotFoundResult), "Get should return not found when file does not exist"); } } }
mit
C#
58185bfeb7201703defa1b1034d632e887ac4aba
Fix german three holy kings holiday name test
kappy/DateTimeExtensions
DateTimeExtensions.Tests/HolidaysTranslations/GermanHolidayNamesTest.cs
DateTimeExtensions.Tests/HolidaysTranslations/GermanHolidayNamesTest.cs
using DateTimeExtensions.WorkingDays; using DateTimeExtensions.WorkingDays.CultureStrategies; using NUnit.Framework; using System.Globalization; namespace DateTimeExtensions.Tests.HolidaysTranslations { [TestFixture] public class GermanHolidayNamesTest { [TestFixtureSetUp] public void Setup() { //setup a default culture System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } [Test] public void AssertGermanHolidaysAreTranslated() { //test holidays still on default culture (en-US) Assert.AreEqual(DE_DEHolidayStrategy.GermanUnityDay.Name, "German Unity Day"); System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE"); Assert.AreEqual("de-DE", System.Threading.Thread.CurrentThread.CurrentUICulture.Name); Assert.AreEqual(DE_DEHolidayStrategy.GermanUnityDay.Name, "Tag der Deutschen Einheit"); Assert.AreEqual(ChristianHolidays.Christmas.Name, "Weihnachten"); Assert.AreEqual(GlobalHolidays.NewYear.Name, "Neujahr"); Assert.AreEqual(ChristianHolidays.Epiphany.Name, "Heilige Drei Könige"); Assert.AreEqual(ChristianHolidays.Carnival.Name, "Fasching"); Assert.AreEqual(ChristianHolidays.AllSaints.Name, "Allerheiligen"); Assert.AreEqual(ChristianHolidays.CorpusChristi.Name, "Fronleichnam"); Assert.AreEqual(ChristianHolidays.Easter.Name, "Ostern"); Assert.AreEqual(ChristianHolidays.GoodFriday.Name, "Karfreitag"); Assert.AreEqual(ChristianHolidays.MaundyThursday.Name, "Gründonnerstag"); Assert.AreEqual(ChristianHolidays.Assumption.Name, "Maria Himmelfahrt"); Assert.AreEqual(ChristianHolidays.ImaculateConception.Name, "Maria Empfängnis"); Assert.AreEqual(ChristianHolidays.Pentecost.Name, "Pfingsten"); Assert.AreEqual(ChristianHolidays.PentecostMonday.Name, "Pfingstmontag"); Assert.AreEqual(GlobalHolidays.InternationalWorkersDay.Name, "Tag der Arbeit"); } } }
using DateTimeExtensions.WorkingDays; using DateTimeExtensions.WorkingDays.CultureStrategies; using NUnit.Framework; using System.Globalization; namespace DateTimeExtensions.Tests.HolidaysTranslations { [TestFixture] public class GermanHolidayNamesTest { [TestFixtureSetUp] public void Setup() { //setup a default culture System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US"); } [Test] public void AssertGermanHolidaysAreTranslated() { //test holidays still on default culture (en-US) Assert.AreEqual(DE_DEHolidayStrategy.GermanUnityDay.Name, "German Unity Day"); System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE"); Assert.AreEqual("de-DE", System.Threading.Thread.CurrentThread.CurrentUICulture.Name); Assert.AreEqual(DE_DEHolidayStrategy.GermanUnityDay.Name, "Tag der Deutschen Einheit"); Assert.AreEqual(ChristianHolidays.Christmas.Name, "Weihnachten"); Assert.AreEqual(GlobalHolidays.NewYear.Name, "Neujahr"); Assert.AreEqual(ChristianHolidays.Epiphany.Name, "Epifanía del Señor"); Assert.AreEqual(ChristianHolidays.Carnival.Name, "Fasching"); Assert.AreEqual(ChristianHolidays.AllSaints.Name, "Allerheiligen"); Assert.AreEqual(ChristianHolidays.CorpusChristi.Name, "Fronleichnam"); Assert.AreEqual(ChristianHolidays.Easter.Name, "Ostern"); Assert.AreEqual(ChristianHolidays.GoodFriday.Name, "Karfreitag"); Assert.AreEqual(ChristianHolidays.MaundyThursday.Name, "Gründonnerstag"); Assert.AreEqual(ChristianHolidays.Assumption.Name, "Maria Himmelfahrt"); Assert.AreEqual(ChristianHolidays.ImaculateConception.Name, "Maria Empfängnis"); Assert.AreEqual(ChristianHolidays.Pentecost.Name, "Pfingsten"); Assert.AreEqual(ChristianHolidays.PentecostMonday.Name, "Pfingstmontag"); Assert.AreEqual(GlobalHolidays.InternationalWorkersDay.Name, "Tag der Arbeit"); } } }
apache-2.0
C#
345ab279c3f02d0cb14f72e85edbfad26283d41b
update copyright strings in generated AssemblyInfo.cs in C# binding
OBIGOGIT/etch,OBIGOGIT/etch,OBIGOGIT/etch,OBIGOGIT/etch,OBIGOGIT/etch,OBIGOGIT/etch,OBIGOGIT/etch,OBIGOGIT/etch
binding-csharp/runtime/src/main/csharp/Properties/AssemblyInfo.cs
binding-csharp/runtime/src/main/csharp/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("Etch")] [assembly: AssemblyDescription("Apache Etch C# Binding Runtime DLL")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Apache Software Foundation")] [assembly: AssemblyProduct("Apache Etch (incubating)")] [assembly: AssemblyCopyright("Copyright Apache Software Foundation 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dfb6c903-751f-4473-8400-d50c1f0968f8")] // 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("1.1.0")] [assembly: AssemblyFileVersion("1.1.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("Etch")] [assembly: AssemblyDescription("Apache Etch Csharp Binding Runtime DLL")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Apache Software Foundation")] [assembly: AssemblyProduct("Apache Etch (incubating)")] [assembly: AssemblyCopyright("Copyright Apache Software Foundation 2009")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dfb6c903-751f-4473-8400-d50c1f0968f8")] // 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("1.1.0")] [assembly: AssemblyFileVersion("1.1.0-incubating")]
apache-2.0
C#
1083e8276249975e3b5b9b9b3f81872042ac4716
Fix not using OverridedValue.Reason
ryancyq/aspnetboilerplate,fengyeju/aspnetboilerplate,Nongzhsh/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,fengyeju/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,zclmoon/aspnetboilerplate,virtualcca/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,andmattia/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,beratcarsi/aspnetboilerplate,zclmoon/aspnetboilerplate,virtualcca/aspnetboilerplate,Nongzhsh/aspnetboilerplate,zclmoon/aspnetboilerplate,AlexGeller/aspnetboilerplate,carldai0106/aspnetboilerplate,AlexGeller/aspnetboilerplate,beratcarsi/aspnetboilerplate,ilyhacker/aspnetboilerplate,luchaoshuai/aspnetboilerplate,virtualcca/aspnetboilerplate,AlexGeller/aspnetboilerplate,carldai0106/aspnetboilerplate,verdentk/aspnetboilerplate,andmattia/aspnetboilerplate,Nongzhsh/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,andmattia/aspnetboilerplate,fengyeju/aspnetboilerplate,ilyhacker/aspnetboilerplate
src/Abp.AspNetCore/AspNetCore/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs
src/Abp.AspNetCore/AspNetCore/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs
using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; namespace Abp.AspNetCore.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason { get { if (OverridedValue != null) { return OverridedValue.Reason; } return HttpContextAccessor.HttpContext?.Request.GetDisplayUrl(); } } protected IHttpContextAccessor HttpContextAccessor { get; } public HttpRequestEntityChangeSetReasonProvider( IHttpContextAccessor httpContextAccessor, IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { HttpContextAccessor = httpContextAccessor; } } }
using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; namespace Abp.AspNetCore.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason => HttpContextAccessor.HttpContext?.Request.GetDisplayUrl(); protected IHttpContextAccessor HttpContextAccessor { get; } public HttpRequestEntityChangeSetReasonProvider( IHttpContextAccessor httpContextAccessor, IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { HttpContextAccessor = httpContextAccessor; } } }
mit
C#
782eda8def95ccc457fa292da6bbb8daa97c7239
Revert changes in CSharpOrderModifiersDiagnosticAnalyzer
shyamnamboodiripad/roslyn,KevinRansom/roslyn,sharwell/roslyn,sharwell/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,eriawan/roslyn,bartdesmet/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,weltkante/roslyn,eriawan/roslyn,KevinRansom/roslyn,physhi/roslyn,mavasani/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,physhi/roslyn,diryboy/roslyn,wvdd007/roslyn,weltkante/roslyn,dotnet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,wvdd007/roslyn,mavasani/roslyn,AmadeusW/roslyn,bartdesmet/roslyn
src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs
src/Analyzers/CSharp/Analyzers/OrderModifiers/CSharpOrderModifiersDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpOrderModifiersDiagnosticAnalyzer : AbstractOrderModifiersDiagnosticAnalyzer { public CSharpOrderModifiersDiagnosticAnalyzer() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance, LanguageNames.CSharp) { } protected override void Recurse( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode root) { foreach (var child in root.ChildNodesAndTokens()) { if (child.IsNode) { var node = child.AsNode(); if (node is MemberDeclarationSyntax memberDeclaration) { CheckModifiers(context, preferredOrder, severity, memberDeclaration); // Recurse and check children. Note: we only do this if we're on an actual // member declaration. Once we hit something that isn't, we don't need to // keep recursing. This prevents us from actually entering things like method // bodies. Recurse(context, preferredOrder, severity, node); } else if (node is AccessorListSyntax accessorList) { foreach (var accessor in accessorList.Accessors) { CheckModifiers(context, preferredOrder, severity, accessor); } } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.OrderModifiers; namespace Microsoft.CodeAnalysis.CSharp.OrderModifiers { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpOrderModifiersDiagnosticAnalyzer : AbstractOrderModifiersDiagnosticAnalyzer { public CSharpOrderModifiersDiagnosticAnalyzer() : base(CSharpSyntaxFacts.Instance, CSharpCodeStyleOptions.PreferredModifierOrder, CSharpOrderModifiersHelper.Instance, LanguageNames.CSharp) { } protected override void Recurse( SyntaxTreeAnalysisContext context, Dictionary<int, int> preferredOrder, ReportDiagnostic severity, SyntaxNode root) { foreach (var node in root.ChildNodes()) { if (node is MemberDeclarationSyntax || node.IsKind(SyntaxKind.LocalFunctionStatement)) { CheckModifiers(context, preferredOrder, severity, node); } else if (node is AccessorListSyntax accessorList) { foreach (var accessor in accessorList.Accessors) { CheckModifiers(context, preferredOrder, severity, accessor); } } // We don't stop at member declarations only because this prevents us from visiting local functions. Recurse(context, preferredOrder, severity, node); } } } }
mit
C#
a5784b5654984a98a84fd51f515ddc60a60adac9
clean up FormatXml
mattfrear/Swashbuckle.AspNetCore.Examples
src/Swashbuckle.AspNetCore.Filters/Extensions/ObjectExtensions.cs
src/Swashbuckle.AspNetCore.Filters/Extensions/ObjectExtensions.cs
using System; using System.IO; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using Microsoft.Net.Http.Headers; namespace Swashbuckle.AspNetCore.Filters.Extensions { public static class ObjectExtensions { public static string XmlSerialize<T>(this T value) { if (value == null) { return string.Empty; } var xmlSerializer = new XmlSerializer(value.GetType()); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter)) { xmlSerializer.Serialize(writer, value); return stringWriter .ToString() .FormatXml(); } } private static readonly MediaTypeHeaderValue ApplicationXml = MediaTypeHeaderValue.Parse("application/xml; charset=utf-8"); internal static string XmlSerialize<T>(this T value, MvcOutputFormatter mvcOutputFormatter) { if (mvcOutputFormatter == null) throw new ArgumentNullException(nameof(mvcOutputFormatter)); try { return mvcOutputFormatter .Serialize(value, ApplicationXml) .FormatXml(); } catch (MvcOutputFormatter.FormatterNotFound) { return value.XmlSerialize(); } } private static string FormatXml(this string unformattedXml) => XDocument.Parse(unformattedXml).ToString(); } }
using System; using System.IO; using System.Xml; using System.Xml.Linq; using System.Xml.Serialization; using Microsoft.Net.Http.Headers; namespace Swashbuckle.AspNetCore.Filters.Extensions { public static class ObjectExtensions { public static string XmlSerialize<T>(this T value) { if (value == null) { return string.Empty; } var xmlSerializer = new XmlSerializer(value.GetType()); var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter)) { xmlSerializer.Serialize(writer, value); return stringWriter .ToString() .FormatXml(); } } private static readonly MediaTypeHeaderValue ApplicationXml = MediaTypeHeaderValue.Parse("application/xml; charset=utf-8"); internal static string XmlSerialize<T>(this T value, MvcOutputFormatter mvcOutputFormatter) { if (mvcOutputFormatter == null) throw new ArgumentNullException(nameof(mvcOutputFormatter)); try { return mvcOutputFormatter .Serialize(value, ApplicationXml) .FormatXml(); } catch (MvcOutputFormatter.FormatterNotFound) { return value.XmlSerialize(); } } private static string FormatXml(this string unformattedXml) { var doc = XDocument.Parse(unformattedXml); return doc.ToString(); } } }
mit
C#
7b85e1fe63160ffa9da6cdb651b1a5300adc3190
Use WebUrl for OpenOnGitHub command
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio/Views/GitHubPane/PullRequestDetailView.xaml.cs
src/GitHub.VisualStudio/Views/GitHubPane/PullRequestDetailView.xaml.cs
using System; using System.ComponentModel.Composition; using System.Globalization; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; using GitHub.Exports; using GitHub.Extensions; using GitHub.Services; using GitHub.UI; using GitHub.UI.Helpers; using GitHub.ViewModels.GitHubPane; using GitHub.VisualStudio.UI.Helpers; using ReactiveUI; namespace GitHub.VisualStudio.Views.GitHubPane { public class GenericPullRequestDetailView : ViewBase<IPullRequestDetailViewModel, GenericPullRequestDetailView> { } [ExportViewFor(typeof(IPullRequestDetailViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class PullRequestDetailView : GenericPullRequestDetailView { public PullRequestDetailView() { InitializeComponent(); bodyMarkdown.PreviewMouseWheel += ScrollViewerUtilities.FixMouseWheelScroll; changesSection.PreviewMouseWheel += ScrollViewerUtilities.FixMouseWheelScroll; this.WhenActivated(d => { d(ViewModel.OpenOnGitHub.Subscribe(_ => DoOpenOnGitHub())); }); } [Import] IVisualStudioBrowser VisualStudioBrowser { get; set; } void DoOpenOnGitHub() { var browser = VisualStudioBrowser; browser.OpenUrl(ViewModel.WebUrl); } void OpenHyperlink(object sender, ExecutedRoutedEventArgs e) { Uri uri; if (Uri.TryCreate(e.Parameter?.ToString(), UriKind.Absolute, out uri)) { VisualStudioBrowser.OpenUrl(uri); } } } }
using System; using System.ComponentModel.Composition; using System.Globalization; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; using GitHub.Exports; using GitHub.Extensions; using GitHub.Services; using GitHub.UI; using GitHub.UI.Helpers; using GitHub.ViewModels.GitHubPane; using GitHub.VisualStudio.UI.Helpers; using ReactiveUI; namespace GitHub.VisualStudio.Views.GitHubPane { public class GenericPullRequestDetailView : ViewBase<IPullRequestDetailViewModel, GenericPullRequestDetailView> { } [ExportViewFor(typeof(IPullRequestDetailViewModel))] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class PullRequestDetailView : GenericPullRequestDetailView { public PullRequestDetailView() { InitializeComponent(); bodyMarkdown.PreviewMouseWheel += ScrollViewerUtilities.FixMouseWheelScroll; changesSection.PreviewMouseWheel += ScrollViewerUtilities.FixMouseWheelScroll; this.WhenActivated(d => { d(ViewModel.OpenOnGitHub.Subscribe(_ => DoOpenOnGitHub())); }); } [Import] IVisualStudioBrowser VisualStudioBrowser { get; set; } void DoOpenOnGitHub() { var browser = VisualStudioBrowser; var cloneUrl = ViewModel.LocalRepository.CloneUrl; var url = ToPullRequestUrl(cloneUrl.Host, ViewModel.RemoteRepositoryOwner, ViewModel.LocalRepository.Name, ViewModel.Model.Number); browser.OpenUrl(url); } static Uri ToPullRequestUrl(string host, string owner, string repositoryName, int number) { var url = string.Format(CultureInfo.InvariantCulture, "https://{0}/{1}/{2}/pull/{3}", host, owner, repositoryName, number); return new Uri(url); } void OpenHyperlink(object sender, ExecutedRoutedEventArgs e) { Uri uri; if (Uri.TryCreate(e.Parameter?.ToString(), UriKind.Absolute, out uri)) { VisualStudioBrowser.OpenUrl(uri); } } } }
mit
C#
f107cbe9afcde294785971dc269f8b5cf09df5ef
Convert to NFluent
blorgbeard/pickles,blorgbeard/pickles,irfanah/pickles,magicmonty/pickles,irfanah/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,picklesdoc/pickles,magicmonty/pickles,magicmonty/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,magicmonty/pickles,dirkrombauts/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,irfanah/pickles,blorgbeard/pickles,picklesdoc/pickles,dirkrombauts/pickles,blorgbeard/pickles,irfanah/pickles
src/Pickles/Pickles.Test/WhenGeneratingPathsFromFeaturesToDitaFiles.cs
src/Pickles/Pickles.Test/WhenGeneratingPathsFromFeaturesToDitaFiles.cs
using System; using Autofac; using NUnit.Framework; using PicklesDoc.Pickles.DirectoryCrawler; using PicklesDoc.Pickles.DocumentationBuilders.DITA; using PicklesDoc.Pickles.ObjectModel; using NFluent; namespace PicklesDoc.Pickles.Test { [TestFixture] public class WhenGeneratingPathsFromFeaturesToDitaFiles : BaseFixture { [Test] public void ThenCanGeneratePathToDeepLevelFeatureFileSuccessfully() { var configuration = Container.Resolve<Configuration>(); configuration.FeatureFolder = FileSystem.DirectoryInfo.FromDirectoryName(@"c:\features"); var featureNode = new FeatureNode(FileSystem.FileInfo.FromFileName(@"c:\features\path\to\the_feature.feature"), @"features\path\to\the_feature.feature", new Feature {Name = "The Feature"}); var ditaMapPathGenerator = Container.Resolve<DitaMapPathGenerator>(); Uri existingUri = ditaMapPathGenerator.GeneratePathToFeature(featureNode); Check.That(existingUri.OriginalString).IsEqualTo(@"path/to/the_feature.dita"); } [Test] public void ThenCanGeneratePathToTopLevelFeatureFileSuccessfully() { var configuration = Container.Resolve<Configuration>(); configuration.FeatureFolder = FileSystem.DirectoryInfo.FromDirectoryName(@"c:\features"); var featureNode = new FeatureNode(FileSystem.FileInfo.FromFileName(@"c:\features\the_feature.feature"), @"features\the_feature.feature", new Feature {Name = "The Feature"}); var ditaMapPathGenerator = Container.Resolve<DitaMapPathGenerator>(); Uri existingUri = ditaMapPathGenerator.GeneratePathToFeature(featureNode); Check.That(existingUri.OriginalString).IsEqualTo(@"the_feature.dita"); } } }
using System; using Autofac; using NUnit.Framework; using PicklesDoc.Pickles.DirectoryCrawler; using PicklesDoc.Pickles.DocumentationBuilders.DITA; using PicklesDoc.Pickles.ObjectModel; using PicklesDoc.Pickles.Parser; using Should; namespace PicklesDoc.Pickles.Test { [TestFixture] public class WhenGeneratingPathsFromFeaturesToDitaFiles : BaseFixture { [Test] public void ThenCanGeneratePathToDeepLevelFeatureFileSuccessfully() { var configuration = Container.Resolve<Configuration>(); configuration.FeatureFolder = FileSystem.DirectoryInfo.FromDirectoryName(@"c:\features"); var featureNode = new FeatureNode(FileSystem.FileInfo.FromFileName(@"c:\features\path\to\the_feature.feature"), @"features\path\to\the_feature.feature", new Feature {Name = "The Feature"}); var ditaMapPathGenerator = Container.Resolve<DitaMapPathGenerator>(); Uri existingUri = ditaMapPathGenerator.GeneratePathToFeature(featureNode); existingUri.OriginalString.ShouldEqual(@"path/to/the_feature.dita"); } [Test] public void ThenCanGeneratePathToTopLevelFeatureFileSuccessfully() { var configuration = Container.Resolve<Configuration>(); configuration.FeatureFolder = FileSystem.DirectoryInfo.FromDirectoryName(@"c:\features"); var featureNode = new FeatureNode(FileSystem.FileInfo.FromFileName(@"c:\features\the_feature.feature"), @"features\the_feature.feature", new Feature {Name = "The Feature"}); var ditaMapPathGenerator = Container.Resolve<DitaMapPathGenerator>(); Uri existingUri = ditaMapPathGenerator.GeneratePathToFeature(featureNode); existingUri.OriginalString.ShouldEqual(@"the_feature.dita"); } } }
apache-2.0
C#
8954e14ad293d410593611fcbe29c9dabd25c4a2
Revert "Dummy commit to test PR. No real changes"
pharring/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet,Microsoft/ApplicationInsights-dotnet,pharring/ApplicationInsights-dotnet
Test/CoreSDK.Test/Net40/Extensibility/Implementation/Platform/PlatformReferencesTests.cs
Test/CoreSDK.Test/Net40/Extensibility/Implementation/Platform/PlatformReferencesTests.cs
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Platform { using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; [TestClass] public class PlatformReferencesTests { [TestMethod] public void NoSystemWebReferences() { // Validate Platform assembly foreach (var assembly in typeof(DebugOutput).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } // Validate Core assembly foreach (var assembly in typeof(EventTelemetry).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } } } }
namespace Microsoft.ApplicationInsights.Extensibility.Implementation.Platform { using Microsoft.ApplicationInsights.DataContracts; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; [TestClass] public class PlatformReferencesTests { [TestMethod] public void NoSystemWebReferences() { // Validate Platform assembly. foreach (var assembly in typeof(DebugOutput).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } // Validate Core assembly foreach (var assembly in typeof(EventTelemetry).Assembly.GetReferencedAssemblies()) { Assert.True(!assembly.FullName.Contains("System.Web")); } } } }
mit
C#
234fffb719f21298e838a0433cc390aacaa26c98
Update version
mj1856/TimeZoneNames
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyCompany("Matt Johnson")] [assembly: AssemblyProduct("Time Zone Names")] [assembly: AssemblyCopyright("Copyright © 2014 Matt Johnson")] [assembly: AssemblyVersion("1.0.1.*")] [assembly: AssemblyInformationalVersion("1.0.1")]
using System.Reflection; [assembly: AssemblyCompany("Matt Johnson")] [assembly: AssemblyProduct("Time Zone Names")] [assembly: AssemblyCopyright("Copyright © 2014 Matt Johnson")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyInformationalVersion("1.0.0")]
mit
C#
f29642c13b16a7fcf2b5aae5b5cd52c8ec1dea9f
Add ApiException message when throwing DispatchException
appharbor/appharbor-cli
src/AppHarbor/CommandDispatcher.cs
src/AppHarbor/CommandDispatcher.cs
using System; using System.Linq; using Castle.MicroKernel; namespace AppHarbor { public class CommandDispatcher { private readonly IAliasMatcher _aliasMatcher; private readonly ITypeNameMatcher _typeNameMatcher; private readonly IKernel _kernel; public CommandDispatcher(IAliasMatcher aliasMatcher, ITypeNameMatcher typeNameMatcher, IKernel kernel) { _aliasMatcher = aliasMatcher; _typeNameMatcher = typeNameMatcher; _kernel = kernel; } public void Dispatch(string[] args) { var commandArgument = args.Any() ? string.Concat(args.Skip(1).FirstOrDefault(), args[0]) : "help"; Type matchingType = null; int argsToSkip = 0; if (_typeNameMatcher.IsSatisfiedBy(commandArgument)) { matchingType = _typeNameMatcher.GetMatchedType(commandArgument); argsToSkip = 2; } else if (_aliasMatcher.IsSatisfiedBy(args[0])) { matchingType = _aliasMatcher.GetMatchedType(args[0]); argsToSkip = 1; } else { throw new DispatchException(string.Format("The command \"{0}\" doesn't match a command name or alias", string.Join(" ", args))); } try { var command = (ICommand)_kernel.Resolve(matchingType); command.Execute(args.Skip(argsToSkip).ToArray()); } catch (ApiException exception) { throw new DispatchException(string.Format("An error occured while connecting to the API. {0}", exception.Message)); } catch (CommandException exception) { throw new DispatchException(exception.Message); } } } }
using System; using System.Linq; using Castle.MicroKernel; namespace AppHarbor { public class CommandDispatcher { private readonly IAliasMatcher _aliasMatcher; private readonly ITypeNameMatcher _typeNameMatcher; private readonly IKernel _kernel; public CommandDispatcher(IAliasMatcher aliasMatcher, ITypeNameMatcher typeNameMatcher, IKernel kernel) { _aliasMatcher = aliasMatcher; _typeNameMatcher = typeNameMatcher; _kernel = kernel; } public void Dispatch(string[] args) { var commandArgument = args.Any() ? string.Concat(args.Skip(1).FirstOrDefault(), args[0]) : "help"; Type matchingType = null; int argsToSkip = 0; if (_typeNameMatcher.IsSatisfiedBy(commandArgument)) { matchingType = _typeNameMatcher.GetMatchedType(commandArgument); argsToSkip = 2; } else if (_aliasMatcher.IsSatisfiedBy(args[0])) { matchingType = _aliasMatcher.GetMatchedType(args[0]); argsToSkip = 1; } else { throw new DispatchException(string.Format("The command \"{0}\" doesn't match a command name or alias", string.Join(" ", args))); } try { var command = (ICommand)_kernel.Resolve(matchingType); command.Execute(args.Skip(argsToSkip).ToArray()); } catch (ApiException) { throw new DispatchException("An error occured while connecting to the API."); } catch (CommandException exception) { throw new DispatchException(exception.Message); } } } }
mit
C#
8a856105f0522681b77d8f55592ea6bd7f90fa4e
Mark Activity and it's properties as Serializable
richlander/corefx,jlin177/corefx,yizhang82/corefx,ViktorHofer/corefx,axelheer/corefx,wtgodbe/corefx,the-dwyer/corefx,billwert/corefx,krytarowski/corefx,parjong/corefx,zhenlan/corefx,cydhaselton/corefx,alexperovich/corefx,MaggieTsang/corefx,the-dwyer/corefx,mmitche/corefx,ptoonen/corefx,fgreinacher/corefx,Ermiar/corefx,twsouthwick/corefx,jlin177/corefx,twsouthwick/corefx,parjong/corefx,DnlHarvey/corefx,tijoytom/corefx,MaggieTsang/corefx,alexperovich/corefx,DnlHarvey/corefx,ptoonen/corefx,billwert/corefx,seanshpark/corefx,shimingsg/corefx,tijoytom/corefx,twsouthwick/corefx,ptoonen/corefx,nchikanov/corefx,mmitche/corefx,rubo/corefx,krk/corefx,twsouthwick/corefx,ericstj/corefx,tijoytom/corefx,Jiayili1/corefx,fgreinacher/corefx,shimingsg/corefx,Jiayili1/corefx,zhenlan/corefx,stone-li/corefx,krk/corefx,gkhanna79/corefx,krytarowski/corefx,alexperovich/corefx,richlander/corefx,mmitche/corefx,axelheer/corefx,krk/corefx,shimingsg/corefx,ptoonen/corefx,stone-li/corefx,twsouthwick/corefx,mazong1123/corefx,rubo/corefx,the-dwyer/corefx,zhenlan/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,Ermiar/corefx,ravimeda/corefx,dotnet-bot/corefx,axelheer/corefx,nbarbettini/corefx,axelheer/corefx,nchikanov/corefx,ptoonen/corefx,stone-li/corefx,gkhanna79/corefx,dotnet-bot/corefx,yizhang82/corefx,stone-li/corefx,JosephTremoulet/corefx,jlin177/corefx,ViktorHofer/corefx,shimingsg/corefx,tijoytom/corefx,the-dwyer/corefx,zhenlan/corefx,Jiayili1/corefx,nchikanov/corefx,gkhanna79/corefx,stone-li/corefx,twsouthwick/corefx,dotnet-bot/corefx,parjong/corefx,JosephTremoulet/corefx,rubo/corefx,seanshpark/corefx,ravimeda/corefx,ViktorHofer/corefx,gkhanna79/corefx,richlander/corefx,seanshpark/corefx,richlander/corefx,nbarbettini/corefx,Jiayili1/corefx,shimingsg/corefx,MaggieTsang/corefx,the-dwyer/corefx,cydhaselton/corefx,seanshpark/corefx,stone-li/corefx,parjong/corefx,BrennanConroy/corefx,ravimeda/corefx,MaggieTsang/corefx,zhenlan/corefx,gkhanna79/corefx,mazong1123/corefx,billwert/corefx,JosephTremoulet/corefx,nbarbettini/corefx,richlander/corefx,nbarbettini/corefx,krytarowski/corefx,richlander/corefx,gkhanna79/corefx,Ermiar/corefx,mmitche/corefx,nchikanov/corefx,zhenlan/corefx,shimingsg/corefx,dotnet-bot/corefx,wtgodbe/corefx,Ermiar/corefx,DnlHarvey/corefx,ravimeda/corefx,ericstj/corefx,fgreinacher/corefx,nchikanov/corefx,mazong1123/corefx,jlin177/corefx,JosephTremoulet/corefx,yizhang82/corefx,zhenlan/corefx,yizhang82/corefx,DnlHarvey/corefx,seanshpark/corefx,ravimeda/corefx,nchikanov/corefx,billwert/corefx,alexperovich/corefx,jlin177/corefx,krk/corefx,mmitche/corefx,billwert/corefx,Ermiar/corefx,the-dwyer/corefx,ravimeda/corefx,krytarowski/corefx,seanshpark/corefx,tijoytom/corefx,MaggieTsang/corefx,parjong/corefx,MaggieTsang/corefx,nbarbettini/corefx,ericstj/corefx,billwert/corefx,krk/corefx,cydhaselton/corefx,ViktorHofer/corefx,ericstj/corefx,ravimeda/corefx,twsouthwick/corefx,mmitche/corefx,krytarowski/corefx,yizhang82/corefx,rubo/corefx,Ermiar/corefx,Ermiar/corefx,DnlHarvey/corefx,krytarowski/corefx,ericstj/corefx,fgreinacher/corefx,ptoonen/corefx,wtgodbe/corefx,tijoytom/corefx,DnlHarvey/corefx,seanshpark/corefx,Jiayili1/corefx,dotnet-bot/corefx,alexperovich/corefx,ericstj/corefx,rubo/corefx,DnlHarvey/corefx,wtgodbe/corefx,krk/corefx,nchikanov/corefx,ViktorHofer/corefx,parjong/corefx,alexperovich/corefx,Jiayili1/corefx,yizhang82/corefx,axelheer/corefx,tijoytom/corefx,jlin177/corefx,wtgodbe/corefx,cydhaselton/corefx,ViktorHofer/corefx,dotnet-bot/corefx,gkhanna79/corefx,BrennanConroy/corefx,parjong/corefx,mazong1123/corefx,MaggieTsang/corefx,wtgodbe/corefx,nbarbettini/corefx,alexperovich/corefx,stone-li/corefx,krk/corefx,krytarowski/corefx,mmitche/corefx,JosephTremoulet/corefx,wtgodbe/corefx,cydhaselton/corefx,mazong1123/corefx,mazong1123/corefx,Jiayili1/corefx,the-dwyer/corefx,nbarbettini/corefx,mazong1123/corefx,ptoonen/corefx,billwert/corefx,shimingsg/corefx,richlander/corefx,ericstj/corefx,axelheer/corefx,jlin177/corefx,cydhaselton/corefx,yizhang82/corefx,cydhaselton/corefx,BrennanConroy/corefx,ViktorHofer/corefx
src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs
src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { // this code is specific to .NET 4.5 and uses CallContext to store Activity.Current which requires Activity to be Serializable. [Serializable] // DO NOT remove public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private [Serializable] // DO NOT remove private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Remoting.Messaging; using System.Security; namespace System.Diagnostics { public partial class Activity { /// <summary> /// Returns the current operation (Activity) for the current thread. This flows /// across async calls. /// </summary> public static Activity Current { #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif get { return (Activity)CallContext.LogicalGetData(FieldKey); } #if ALLOW_PARTIALLY_TRUSTED_CALLERS [System.Security.SecuritySafeCriticalAttribute] #endif private set { CallContext.LogicalSetData(FieldKey, value); } } #region private private partial class KeyValueListNode { } private static readonly string FieldKey = $"{typeof(Activity).FullName}"; #endregion } }
mit
C#
11f780dfde514c0d8e2e7cb5b8c57b77bf643991
set hunger text when its in winter.
ZackAdams/squirrel-simulator,ZackAdams/squirrel-simulator
unity/Assets/HudDisplay.cs
unity/Assets/HudDisplay.cs
using UnityEngine; using System.Collections; public class HudDisplay : MonoBehaviour { public GUIText alertMessage; public GUIText nutsCollected; public GUIText hunger; public GUIText displayTimer; public CharacterStats player; public float fallTimelimit = 60; public float winterTimelimit = 60; public float currentTime; private float currentTimelimit; public Terrain terrain; public Material winterMaterial; public NutController nutController; private bool isWinter = false; private Vector3 spawnPosition; private Quaternion spawnRotation; public FamilyTree familyTree; // Use this for initialization void Start () { alertMessage.text = ""; nutSetText (0); hunger.text = ""; currentTimelimit = fallTimelimit; resetTimer (); } void resetTimer() { currentTime = currentTimelimit; } // Update is called once per frame void Update () { currentTimelimit -= Time.deltaTime; setTimerText (currentTimelimit); nutSetText ( player.nutCount ); if (currentTimelimit <= 0.0f) { Debug.Log("Time finished"); if (isWinter) { endGame(); } else { nutController.destroyNuts(); resetTimer(); player.reSpawn(); switchToWinter(); } } if (isWinter) { hungerSetText (); } } void setTimerText(float time) { displayTimer.text = "Time: " + time.ToString (); } void nutSetText(int nuts) { nutsCollected.text = "Nuts: " + nuts.ToString(); } void hungerSetText () { hunger.text = "Hunger: Very Hungry"; } void endGame() { //GAME OVER code goes here //bool an OnGUI function true to display a box with Game Over label, grays the screen out //show score //disable player movement //button to restart //button to quit } void switchToWinter() { isWinter = true; familyTree.isWinter = true; currentTimelimit = winterTimelimit; //Turn on snow //terrain.renderer.material = winterMaterial; terrain.materialTemplate = winterMaterial; //Hide grass terrain.detailObjectDistance = 0; //Turn off shadows, helps snow look better terrain.castShadows = false; } }
using UnityEngine; using System.Collections; public class HudDisplay : MonoBehaviour { public GUIText alertMessage; public GUIText nutsCollected; public GUIText hunger; public GUIText displayTimer; public CharacterStats player; public float fallTimelimit = 60; public float winterTimelimit = 60; public float currentTime; private float currentTimelimit; public Terrain terrain; public Material winterMaterial; public NutController nutController; private bool isWinter = false; private Vector3 spawnPosition; private Quaternion spawnRotation; public FamilyTree familyTree; // Use this for initialization void Start () { alertMessage.text = ""; nutSetText (0); if (true) { hunger.text = ""; } // Unity claims this to be unreachable // else // { // hungerSetText (); // } currentTimelimit = fallTimelimit; resetTimer (); } void resetTimer() { currentTime = currentTimelimit; } // Update is called once per frame void Update () { currentTimelimit -= Time.deltaTime; setTimerText (currentTimelimit); nutSetText ( player.nutCount ); if (currentTimelimit <= 0.0f) { Debug.Log("Time finished"); if (isWinter) { endGame(); } else { nutController.destroyNuts(); resetTimer(); player.reSpawn(); switchToWinter(); } } } void setTimerText(float time) { displayTimer.text = "Time: " + time.ToString (); } void nutSetText(int nuts) { nutsCollected.text = "Nuts: " + nuts.ToString(); } void hungerSetText () { hunger.text = "Hunger: Very Hungry"; } void endGame() { //GAME OVER code goes here //bool an OnGUI function true to display a box with Game Over label, grays the screen out //show score //disable player movement //button to restart //button to quit } void switchToWinter() { isWinter = true; familyTree.isWinter = true; currentTimelimit = winterTimelimit; //Turn on snow //terrain.renderer.material = winterMaterial; terrain.materialTemplate = winterMaterial; //Hide grass terrain.detailObjectDistance = 0; //Turn off shadows, helps snow look better terrain.castShadows = false; } }
mit
C#
a24209f1a6a97b82939d4cf324400f05409504f4
Add ExposureNotificationCallbackBroadcastReceiver (#920)
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
XPlat/ExposureNotification/source/Xamarin.ExposureNotification/CallbackService.android.cs
XPlat/ExposureNotification/source/Xamarin.ExposureNotification/CallbackService.android.cs
using System.Collections.Generic; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Gms.Nearby.ExposureNotification; using Android.Runtime; using AndroidX.Core.App; namespace Xamarin.ExposureNotifications { [BroadcastReceiver(Permission = permissionExposureCallback, Exported = true)] [IntentFilter(new[] { actionExposureStateUpdated, actionExposureNotFound })] [Preserve] class ExposureNotificationCallbackBroadcastReceiver : BroadcastReceiver { const string actionExposureStateUpdated = ExposureNotificationClient.ActionExposureStateUpdated; const string actionExposureNotFound = "com.google.android.gms.exposurenotification.ACTION_EXPOSURE_NOT_FOUND"; const string permissionExposureCallback = "com.google.android.gms.nearby.exposurenotification.EXPOSURE_CALLBACK"; public override void OnReceive(Context context, Intent intent) { // https://developers.google.com/android/exposure-notifications/exposure-notifications-api#broadcast-receivers var action = intent.Action; if (action == actionExposureStateUpdated) { global::Android.Util.Log.Debug("Xamarin.ExposureNotifications", "Exposure state updated."); ExposureNotificationCallbackService.EnqueueWork(context, intent); } else if (action == actionExposureNotFound) { global::Android.Util.Log.Debug("Xamarin.ExposureNotifications", "Exposure not found."); } } } [Service(Permission = "android.permission.BIND_JOB_SERVICE")] [Preserve] class ExposureNotificationCallbackService : JobIntentService { const int jobId = 0x02; public static void EnqueueWork(Context context, Intent work) => EnqueueWork(context, Java.Lang.Class.FromType(typeof(ExposureNotificationCallbackService)), jobId, work); protected override async void OnHandleWork(Intent workIntent) { var token = workIntent.GetStringExtra(ExposureNotificationClient.ExtraToken); var summary = await ExposureNotification.PlatformGetExposureSummaryAsync(token); Task<IEnumerable<ExposureInfo>> GetInfo() { return ExposureNotification.PlatformGetExposureInformationAsync(token); } // Invoke the custom implementation handler code with the summary info if (summary?.MatchedKeyCount > 0) { await ExposureNotification.Handler.ExposureDetectedAsync(summary, GetInfo); } } } }
using System.Collections.Generic; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Gms.Nearby.ExposureNotification; using Android.Runtime; using AndroidX.Core.App; namespace Xamarin.ExposureNotifications { [BroadcastReceiver( Permission = "com.google.android.gms.nearby.exposurenotification.EXPOSURE_CALLBACK", Exported = true)] [IntentFilter(new[] { ExposureNotificationClient.ActionExposureStateUpdated })] [Preserve] class ExposureNotificationCallbackBroadcastReceiver : BroadcastReceiver { public override void OnReceive(Context context, Intent intent) => ExposureNotificationCallbackService.EnqueueWork(context, intent); } [Service( Permission = "android.permission.BIND_JOB_SERVICE")] [Preserve] class ExposureNotificationCallbackService : JobIntentService { const int jobId = 0x02; public static void EnqueueWork(Context context, Intent work) => EnqueueWork(context, Java.Lang.Class.FromType(typeof(ExposureNotificationCallbackService)), jobId, work); protected override async void OnHandleWork(Intent workIntent) { var token = workIntent.GetStringExtra(ExposureNotificationClient.ExtraToken); var summary = await ExposureNotification.PlatformGetExposureSummaryAsync(token); Task<IEnumerable<ExposureInfo>> GetInfo() { return ExposureNotification.PlatformGetExposureInformationAsync(token); } // Invoke the custom implementation handler code with the summary info if (summary?.MatchedKeyCount > 0) { await ExposureNotification.Handler.ExposureDetectedAsync(summary, GetInfo); } } } }
mit
C#
036b41173208e824f50f489e53b35d541a3ff409
Update DateTimeExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/DateTimeExtensions.cs
src/DateTimeExtensions.cs
using System; using System.Globalization; public static class DateTimeExtensions { public static string ToISO8601String(this DateTime dt) { // ISO-8601 date format return dt.ToString(@"yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); } }
public static class DateTimeExtensions { public static string ToISO8601String (this DateTime dt) { // ISO-8601 date format return dt.ToString(@"yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); } }
apache-2.0
C#
182708c2fc754327938f1ee01fd78b31d2f57a54
update API URL
IdentityModel/IdentityModel.OidcClient.Samples,IdentityModel/IdentityModel.OidcClient.Samples
iOSClient/iOSClient/ViewController.cs
iOSClient/iOSClient/ViewController.cs
using System; using System.Text; using IdentityModel.OidcClient; using UIKit; using Foundation; using System.Net.Http; using Newtonsoft.Json.Linq; namespace iOSClient { public partial class ViewController : UIViewController { SafariServices.SFSafariViewController safari; OidcClient _client; AuthorizeState _state; HttpClient _apiClient; public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); CallApiButton.Enabled = false; LoginButton.TouchUpInside += LoginButton_TouchUpInside; CallApiButton.TouchUpInside += CallApiButton_TouchUpInside; } async void LoginButton_TouchUpInside (object sender, EventArgs e) { var options = new OidcClientOptions { Authority = "https://demo.identityserver.io", ClientId = "native.hybrid", Scope = "openid profile email api", RedirectUri = "io.identitymodel.native://callback", ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect }; _client = new OidcClient (options); _state = await _client.PrepareLoginAsync (); AppDelegate.CallbackHandler = HandleCallback; safari = new SafariServices.SFSafariViewController (new NSUrl (_state.StartUrl)); this.PresentViewController (safari, true, null); } async void CallApiButton_TouchUpInside (object sender, EventArgs e) { if (_apiClient == null) { return; } var result = await _apiClient.GetAsync ("test"); var content = await result.Content.ReadAsStringAsync (); if (!result.IsSuccessStatusCode) { OutputTextView.Text = result.ReasonPhrase + "\n\n" + content; return; } OutputTextView.Text = JArray.Parse (content).ToString (); } async void HandleCallback (string url) { await safari.DismissViewControllerAsync (true); var result = await _client.ProcessResponseAsync (url, _state); if (result.IsError) { OutputTextView.Text = result.Error; return; } var sb = new StringBuilder (128); foreach (var claim in result.User.Claims) { sb.AppendFormat ("{0}: {1}\n", claim.Type, claim.Value); } sb.AppendFormat ("\n{0}: {1}\n", "refresh token", result?.RefreshToken ?? "none"); sb.AppendFormat ("\n{0}: {1}\n", "access token", result.AccessToken); OutputTextView.Text = sb.ToString (); _apiClient = new HttpClient (); _apiClient.SetBearerToken (result.AccessToken); _apiClient.BaseAddress = new Uri ("https://demo.identityserver.io/api/"); CallApiButton.Enabled = true; } public override void DidReceiveMemoryWarning () { base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } }
using System; using System.Text; using IdentityModel.OidcClient; using UIKit; using Foundation; using System.Net.Http; using Newtonsoft.Json.Linq; namespace iOSClient { public partial class ViewController : UIViewController { SafariServices.SFSafariViewController safari; OidcClient _client; AuthorizeState _state; HttpClient _apiClient; public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); CallApiButton.Enabled = false; LoginButton.TouchUpInside += LoginButton_TouchUpInside; CallApiButton.TouchUpInside += CallApiButton_TouchUpInside; } async void LoginButton_TouchUpInside (object sender, EventArgs e) { var options = new OidcClientOptions { Authority = "https://demo.identityserver.io", ClientId = "native.hybrid", Scope = "openid profile email api", RedirectUri = "io.identitymodel.native://callback", ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect }; _client = new OidcClient (options); _state = await _client.PrepareLoginAsync (); AppDelegate.CallbackHandler = HandleCallback; safari = new SafariServices.SFSafariViewController (new NSUrl (_state.StartUrl)); this.PresentViewController (safari, true, null); } async void CallApiButton_TouchUpInside (object sender, EventArgs e) { if (_apiClient == null) { return; } var result = await _apiClient.GetAsync ("identity"); var content = await result.Content.ReadAsStringAsync (); if (!result.IsSuccessStatusCode) { OutputTextView.Text = result.ReasonPhrase + "\n\n" + content; return; } OutputTextView.Text = JArray.Parse (content).ToString (); } async void HandleCallback (string url) { await safari.DismissViewControllerAsync (true); var result = await _client.ProcessResponseAsync (url, _state); if (result.IsError) { OutputTextView.Text = result.Error; return; } var sb = new StringBuilder (128); foreach (var claim in result.User.Claims) { sb.AppendFormat ("{0}: {1}\n", claim.Type, claim.Value); } sb.AppendFormat ("\n{0}: {1}\n", "refresh token", result?.RefreshToken ?? "none"); sb.AppendFormat ("\n{0}: {1}\n", "access token", result.AccessToken); OutputTextView.Text = sb.ToString (); _apiClient = new HttpClient (); _apiClient.SetBearerToken (result.AccessToken); _apiClient.BaseAddress = new Uri ("https://api.identityserver.io"); CallApiButton.Enabled = true; } public override void DidReceiveMemoryWarning () { base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } }
apache-2.0
C#
6bcf32242cb5c527d284b1cec811956c55e9645f
fix urls
marihachi/MSharp2
src/MSharp.Core/Config.cs
src/MSharp.Core/Config.cs
using System; namespace MSharp.Core { public static class Config { public static string SessionKeyName { get; set; } = "hmsk"; public static Uri Url { get; set; } = new Uri("https://misskey.link"); public static Uri LoginUrl { get; set; } = new Uri("https://login.misskey.link"); public static Uri ApiUrl { get; set; } = new Uri("https://himasaku.misskey.link/ "); public static Uri NonLoginApiUrl { get; set; } = new Uri("https://api.misskey.link"); public static Uri StreamingApiUrl { get; set; } = new Uri("https://himasaku.misskey.link:3000"); } }
using System; namespace MSharp.Core { public static class Config { public static string SessionKeyName { get; set; } = "hmsk"; public static Uri Url { get; set; } = new Uri("https://misskey.xyz"); public static Uri LoginUrl { get; set; } = new Uri("https://login.misskey.xyz"); public static Uri ApiUrl { get; set; } = new Uri("https://himasaku.misskey.xyz"); public static Uri NonLoginApiUrl { get; set; } = new Uri("https://api.misskey.xyz"); public static Uri StreamingApiUrl { get; set; } = new Uri("https://himasaku.misskey.xyz:3000"); } }
mit
C#
64a25d4e06f57d7e2895ef3c9c85674d07108af5
Fix empty values for form item. (Thanks Eno!).
mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos
src/Manos/Manos.Http/HttpFormDataHandler.cs
src/Manos/Manos.Http/HttpFormDataHandler.cs
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // 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.Text; using Manos.Collections; namespace Manos.Http { public class HttpFormDataHandler : IHttpBodyHandler { private enum State { InKey, InValue, } private State state; private StringBuilder key_buffer = new StringBuilder (); private StringBuilder value_buffer = new StringBuilder (); public void HandleData (HttpEntity entity, ByteBuffer data, int pos, int len) { string str_data = entity.ContentEncoding.GetString (data.Bytes, pos, len); str_data = HttpUtility.HtmlDecode (str_data); pos = 0; len = str_data.Length; while (pos < len) { char c = str_data [pos++]; if (c == '&') { if (state == State.InKey) throw new InvalidOperationException ("& symbol can not be used in key data."); FinishPair (entity); state = State.InKey; continue; } if (c == '=') { if (state == State.InValue) throw new InvalidOperationException ("= symbol can not be used in value data."); state = State.InValue; continue; } switch (state) { case State.InKey: key_buffer.Append (c); break; case State.InValue: value_buffer.Append (c); break; } } } public void Finish (HttpEntity entity) { if (state == State.InKey) throw new HttpException ("Malformed POST data, key found without value."); FinishPair (entity); } private void FinishPair (HttpEntity entity) { if (key_buffer.Length == 0) throw new HttpException ("zero length key in www-form data."); Encoding e = entity.ContentEncoding; entity.PostData.Set (HttpUtility.UrlDecode (key_buffer.ToString (), e), HttpUtility.UrlDecode (value_buffer.ToString (), e)); key_buffer.Clear (); value_buffer.Clear (); } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // 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.Text; using Manos.Collections; namespace Manos.Http { public class HttpFormDataHandler : IHttpBodyHandler { private enum State { InKey, InValue, } private State state; private StringBuilder key_buffer = new StringBuilder (); private StringBuilder value_buffer = new StringBuilder (); public void HandleData (HttpEntity entity, ByteBuffer data, int pos, int len) { string str_data = entity.ContentEncoding.GetString (data.Bytes, pos, len); str_data = HttpUtility.HtmlDecode (str_data); pos = 0; len = str_data.Length; while (pos < len) { char c = str_data [pos++]; if (c == '&') { if (state == State.InKey) throw new InvalidOperationException ("& symbol can not be used in key data."); FinishPair (entity); state = State.InKey; continue; } if (c == '=') { if (state == State.InValue) throw new InvalidOperationException ("= symbol can not be used in value data."); state = State.InValue; continue; } switch (state) { case State.InKey: key_buffer.Append (c); break; case State.InValue: value_buffer.Append (c); break; } } } public void Finish (HttpEntity entity) { if (state == State.InKey) throw new HttpException ("Malformed POST data, key found without value."); FinishPair (entity); } private void FinishPair (HttpEntity entity) { if (value_buffer.Length == 0) return; if (key_buffer.Length == 0) throw new HttpException ("zero length key in www-form data."); Encoding e = entity.ContentEncoding; entity.PostData.Set (HttpUtility.UrlDecode (key_buffer.ToString (), e), HttpUtility.UrlDecode (value_buffer.ToString (), e)); key_buffer.Clear (); value_buffer.Clear (); } } }
mit
C#
2f927783ad6590452c65960111cb09919fe2c0e5
Add some tests for a bug.
KirillOsenkov/XmlParser
src/Microsoft.Language.Xml.Tests/TestApi.cs
src/Microsoft.Language.Xml.Tests/TestApi.cs
using System.Linq; using Xunit; namespace Microsoft.Language.Xml.Tests { public class TestApi { [Fact] public void TestAttributeValue() { var root = Parser.ParseText("<e a=\"\"/>"); var attributeValue = root.Attributes.First().Value; Assert.Equal("", attributeValue); } [Fact] public void TestContent() { var root = Parser.ParseText("<e>Content</e>"); var value = root.Value; Assert.Equal("Content", value); } [Fact] public void TestRootLevel() { var root = Parser.ParseText("<Root></Root>"); Assert.Equal("Root", root.Name); } [Fact(Skip = "https://github.com/KirillOsenkov/XmlParser/issues/8")] public void TestRootLevelTrivia() { var root = Parser.ParseText("<!-- C --><Root></Root>"); Assert.Equal("Root", root.Name); } [Fact] public void TestRootLevelTriviaWithDeclaration() { var root = Parser.ParseText("<?xml version=\"1.0\" encoding=\"utf-8\"?><!-- C --><Root></Root>"); Assert.Equal("Root", root.Name); } } }
using System.Linq; using Xunit; namespace Microsoft.Language.Xml.Tests { public class TestApi { [Fact] public void TestAttributeValue() { var root = Parser.ParseText("<e a=\"\"/>"); var attributeValue = root.Attributes.First().Value; Assert.Equal("", attributeValue); } [Fact] public void TestContent() { var root = Parser.ParseText("<e>Content</e>"); var value = root.Value; Assert.Equal("Content", value); } } }
apache-2.0
C#