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
3174400171a0a88275588bd451002454ad24b971
Update AssemblyInfo.cs
jamestao/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,pankajsn/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,atpham256/azure-sdk-for-net,hyonholee/azure-sdk-for-net,pankajsn/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,olydis/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,mihymel/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,nathannfan/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,begoldsm/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,samtoubia/azure-sdk-for-net,peshen/azure-sdk-for-net,shutchings/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,djyou/azure-sdk-for-net,smithab/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jamestao/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,peshen/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,shutchings/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,samtoubia/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pilor/azure-sdk-for-net,hyonholee/azure-sdk-for-net,mihymel/azure-sdk-for-net,shutchings/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,r22016/azure-sdk-for-net,begoldsm/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jamestao/azure-sdk-for-net,r22016/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,atpham256/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,smithab/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,btasdoven/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,olydis/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AzCiS/azure-sdk-for-net,atpham256/azure-sdk-for-net,hyonholee/azure-sdk-for-net,olydis/azure-sdk-for-net,pankajsn/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AzCiS/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,stankovski/azure-sdk-for-net,begoldsm/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pilor/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,jamestao/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,btasdoven/azure-sdk-for-net,pilor/azure-sdk-for-net,nathannfan/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,mihymel/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,smithab/azure-sdk-for-net,btasdoven/azure-sdk-for-net,r22016/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,markcowl/azure-sdk-for-net,djyou/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,nathannfan/azure-sdk-for-net,djyou/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,samtoubia/azure-sdk-for-net,AzCiS/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,samtoubia/azure-sdk-for-net,stankovski/azure-sdk-for-net,peshen/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,jackmagic313/azure-sdk-for-net
src/ResourceManagement/Compute/ComputeManagement/Properties/AssemblyInfo.cs
src/ResourceManagement/Compute/ComputeManagement/Properties/AssemblyInfo.cs
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Compute Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Compute Resources.")] [assembly: AssemblyVersion("10.0.0.0")] [assembly: AssemblyFileVersion("10.0.1.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Microsoft Azure Compute Management Library")] [assembly: AssemblyDescription("Provides management functionality for Microsoft Azure Compute Resources.")] [assembly: AssemblyVersion("10.0.0.0")] [assembly: AssemblyFileVersion("10.0.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Azure .NET SDK")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
593744ed21348b766ec240137adfa965690b31be
Add grep & egrep
garlab/Ext.NET
Ext.NET/EnumerableExtension.cs
Ext.NET/EnumerableExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Ext.NET { public static class EnumerableExtension { public static void Each<T>(this IEnumerable<T> enumerable, Action<T> action) { foreach (var item in enumerable) { action(item); } } public static IEnumerable<T> Grep<T>(this IEnumerable<T> enumerable, string pattern) { foreach (var item in enumerable) { if (item.ToString().Contains(pattern)) { yield return item; } } } public static IEnumerable<T> EGrep<T>(this IEnumerable<T> enumerable, string pattern, RegexOptions option = RegexOptions.None) { var regex = new Regex(pattern, option); foreach (var item in enumerable) { if (regex.IsMatch(item.ToString())) { yield return item; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ext.NET { public static class EnumerableExtension { public static void Each<T>(this IEnumerable<T> enumberable, Action<T> action) { foreach (var item in enumberable) { action(item); } } } }
mit
C#
cf58576bc40b33a581f028960ba4cc7ed5e01b80
Fix indentation for artifactRules
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/CI/TeamCity/Configuration/TeamCityArtifactDependency.cs
source/Nuke.Common/CI/TeamCity/Configuration/TeamCityArtifactDependency.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityArtifactDependency : TeamCityDependency { public TeamCityBuildType BuildType { get; set; } public string[] ArtifactRules { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock($"artifacts({BuildType.Id})")) { writer.WriteLine("artifactRules = \"\"\""); using (writer.Indent()) { foreach (var artifactRule in ArtifactRules) writer.WriteLine(artifactRule); } writer.WriteLine("\"\"\".trimIndent()"); } } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityArtifactDependency : TeamCityDependency { public TeamCityBuildType BuildType { get; set; } public string[] ArtifactRules { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock($"artifacts({BuildType.Id})")) { writer.WriteLine("artifactRules = \"\"\""); foreach (var artifactRule in ArtifactRules) writer.WriteLine(artifactRule); writer.WriteLine("\"\"\".trimIndent()"); } } } }
mit
C#
2b2622e0a4047c3810d3ceee0798f0f1d1600487
Update version number to 1.1
Haacked/SeeGit
SeeGitApp/Properties/AssemblyInfo.cs
SeeGitApp/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("SeeGit")] [assembly: AssemblyDescription("SeeGit makes it easy to visualize a Git repository in realtime as it grows.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SeeGit Visualizer")] [assembly: AssemblyCopyright("Copyright © 2012-2013 Phil Haack")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("SeeGit")] [assembly: AssemblyDescription("SeeGit makes it easy to visualize a Git repository in realtime as it grows.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SeeGit Visualizer")] [assembly: AssemblyCopyright("Copyright © 2012-2013 Phil Haack")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
5c838f3d30d483dcadb4181233a4437fb5e7f327
fix issue with dot3.5 BlockingCollection
somdoron/AsyncIO
Source/AsyncIO/BlockingCollection.cs
Source/AsyncIO/BlockingCollection.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using AsyncIO; namespace System.Collections.Concurrent { class BlockingCollection<T> { private Queue<T> m_queue; public BlockingCollection() { m_queue = new Queue<T>(); } public void Add(T item) { lock (m_queue) { m_queue.Enqueue(item); if (m_queue.Count == 1) { Monitor.PulseAll(m_queue); } } } public bool TryTake(out T item, int timeout) { Stopwatch stopwatch = Stopwatch.StartNew(); lock (m_queue) { while (m_queue.Count == 0) { long elapsed = stopwatch.ElapsedMilliseconds; int timeoutLeft = timeout == -1 ? -1 : (elapsed > timeout ? 0 : timeout - (int)elapsed); if (timeoutLeft == 0) { item = default(T); return false; } Monitor.Wait(m_queue, timeoutLeft); } item = m_queue.Dequeue(); return true; } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using AsyncIO; namespace System.Collections.Concurrent { class BlockingCollection<T> { private Queue<T> m_queue; public BlockingCollection() { m_queue = new Queue<T>(); } public void Add(T item) { lock (m_queue) { m_queue.Enqueue(item); if (m_queue.Count == 1) { Monitor.PulseAll(m_queue); } } } public bool TryTake(out T item, int timeout) { Stopwatch stopwatch = Stopwatch.StartNew(); int timeoutLeft = timeout == -1 ? -1 : (stopwatch.ElapsedMilliseconds > timeout ? 0 : timeout - (int)stopwatch.ElapsedMilliseconds); if (Monitor.TryEnter(m_queue, timeoutLeft)) { while (m_queue.Count == 0) { timeoutLeft = timeout == -1 ? -1 : (stopwatch.ElapsedMilliseconds > timeout ? 0 : timeout - (int)stopwatch.ElapsedMilliseconds); if (timeoutLeft == 0) { item = default(T); Monitor.Exit(m_queue); return false; } Monitor.Wait(m_queue, timeoutLeft); } item = m_queue.Dequeue(); Monitor.Exit(m_queue); return true; } else { item = default(T); return false; } } } }
mpl-2.0
C#
2a936d5479f32c5e4a824a28135ef30208047d1a
convert float to int health points
SamuelKnox/F.R.E.D.,Evorlor/F.R.E.D.
Fred/Components/HealthComponent.cs
Fred/Components/HealthComponent.cs
using Artemis; using Artemis.Interface; using Artemis.Attributes; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fred.Components { class HealthComponent : IComponent { public HealthComponent() : this(0) { } public HealthComponent(int points) { this.Points = this.MaximumHealth = points; } public int Points { get; set; } public bool IsAlive { get { return this.Points > 0; } } public int MaximumHealth { get; private set; } public void AddDamage(int damage) { this.Points -= damage; if (this.Points < 0) { this.Points = 0; } } } }
using Artemis; using Artemis.Interface; using Artemis.Attributes; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Fred.Components { class HealthComponent : IComponent { public HealthComponent() : this(0.0f) { } public HealthComponent(float points) { this.Points = this.MaximumHealth = points; } public float Points { get; set; } public double HealthPercentage { get { return Math.Round(this.Points / this.MaximumHealth * 100f); } } public bool IsAlive { get { return this.Points > 0; } } public float MaximumHealth { get; private set; } public void AddDamage(int damage) { this.Points -= damage; if (this.Points < 0) { this.Points = 0; } } } }
mit
C#
4d517cb8277aee797f0968c13bbddf18d8b6255e
Fix shortcode interface registration (#6937)
stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2
src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ServiceCollectionExtensions.cs
src/OrchardCore/OrchardCore.Shortcodes.Abstractions/ServiceCollectionExtensions.cs
using System; using Microsoft.Extensions.DependencyInjection; using Shortcodes; namespace OrchardCore.Shortcodes { public static class ServiceCollectionExtensions { public static IServiceCollection AddShortcode<T>(this IServiceCollection services, string name) where T : class, IShortcodeProvider => services.AddShortcode(name, null); public static IServiceCollection AddShortcode<T>(this IServiceCollection services, string name, Action<ShortcodeOption> describe) where T : class, IShortcodeProvider { services.Configure<ShortcodeOptions>(options => options.AddShortcode(name, describe)); services.AddScoped<IShortcodeProvider, T>(); return services; } public static IServiceCollection AddShortcode(this IServiceCollection services, string name, ShortcodeDelegate shortcode) => services.Configure<ShortcodeOptions>(options => options.AddShortcodeDelegate(name, shortcode, null)); public static IServiceCollection AddShortcode(this IServiceCollection services, string name, ShortcodeDelegate shortcode, Action<ShortcodeOption> describe) { services.Configure<ShortcodeOptions>(options => options.AddShortcodeDelegate(name, shortcode, describe)); return services; } } }
using System; using Microsoft.Extensions.DependencyInjection; using Shortcodes; namespace OrchardCore.Shortcodes { public static class ServiceCollectionExtensions { public static IServiceCollection AddShortcode<T>(this IServiceCollection services, string name) where T : class, IShortcodeProvider => services.AddShortcode(name, null); public static IServiceCollection AddShortcode<T>(this IServiceCollection services, string name, Action<ShortcodeOption> describe) where T : class, IShortcodeProvider { services.Configure<ShortcodeOptions>(options => options.AddShortcode(name, describe)); services.AddScoped<T>(); return services; } public static IServiceCollection AddShortcode(this IServiceCollection services, string name, ShortcodeDelegate shortcode) => services.Configure<ShortcodeOptions>(options => options.AddShortcodeDelegate(name, shortcode, null)); public static IServiceCollection AddShortcode(this IServiceCollection services, string name, ShortcodeDelegate shortcode, Action<ShortcodeOption> describe) { services.Configure<ShortcodeOptions>(options => options.AddShortcodeDelegate(name, shortcode, describe)); return services; } } }
bsd-3-clause
C#
9f94db6eeba981bd61e885bc9c4a74e0d096705f
Fix index creation attempt
dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu
src/Our.Umbraco.Nexu.Core/Migrations/Version_2_0_0/CreateRelationTableMigration.cs
src/Our.Umbraco.Nexu.Core/Migrations/Version_2_0_0/CreateRelationTableMigration.cs
namespace Our.Umbraco.Nexu.Core.Migrations.Version_2_0_0 { using global::Umbraco.Core.Migrations; using Our.Umbraco.Nexu.Common.Constants; /// <summary> /// Represents the create relation table migration. /// </summary> internal class CreateRelationTableMigration : MigrationBase { /// <summary> /// Initializes a new instance of the <see cref="CreateRelationTableMigration"/> class. /// </summary> /// <param name="context"> /// The context. /// </param> public CreateRelationTableMigration(IMigrationContext context) : base(context) { } /// <inheritdoc /> public override void Migrate() { this.Create.Table(DatabaseConstants.TableName) .WithColumn(DatabaseConstants.IdColumn).AsGuid().PrimaryKey(DatabaseConstants.PrimaryKey).NotNullable() .WithColumn(DatabaseConstants.ParentUdiColumn).AsString(100).NotNullable() .WithColumn(DatabaseConstants.ChildUdiColumn).AsString(100).NotNullable() .WithColumn(DatabaseConstants.RelationTypeColumn).AsGuid().NotNullable() .WithColumn(DatabaseConstants.PropertyAlias).AsString(100).NotNullable() .WithColumn(DatabaseConstants.CultureColumn).AsString(32).Nullable() .Do(); this.Create.Index(DatabaseConstants.ParentUdiIndex).OnTable(DatabaseConstants.TableName).WithOptions().NonClustered() .OnColumn(DatabaseConstants.ParentUdiColumn).Ascending().Do(); this.Create.Index(DatabaseConstants.ChildUdiIndex).OnTable(DatabaseConstants.TableName).WithOptions().NonClustered() .OnColumn(DatabaseConstants.ChildUdiColumn).Ascending().Do(); } } }
namespace Our.Umbraco.Nexu.Core.Migrations.Version_2_0_0 { using global::Umbraco.Core.Migrations; using Our.Umbraco.Nexu.Common.Constants; /// <summary> /// Represents the create relation table migration. /// </summary> internal class CreateRelationTableMigration : MigrationBase { /// <summary> /// Initializes a new instance of the <see cref="CreateRelationTableMigration"/> class. /// </summary> /// <param name="context"> /// The context. /// </param> public CreateRelationTableMigration(IMigrationContext context) : base(context) { } /// <inheritdoc /> public override void Migrate() { this.Create.Table(DatabaseConstants.TableName) .WithColumn(DatabaseConstants.IdColumn).AsGuid().PrimaryKey(DatabaseConstants.PrimaryKey).NotNullable() .WithColumn(DatabaseConstants.ParentUdiColumn).AsString(100).NotNullable().Indexed(DatabaseConstants.ParentUdiIndex) .WithColumn(DatabaseConstants.ChildUdiColumn).AsString(100).NotNullable().Indexed(DatabaseConstants.ChildUdiIndex) .WithColumn(DatabaseConstants.RelationTypeColumn).AsGuid().NotNullable() .WithColumn(DatabaseConstants.PropertyAlias).AsString(100).NotNullable() .WithColumn(DatabaseConstants.CultureColumn).AsString(32).Nullable() .Do(); } } }
mit
C#
e899f0616ec4c81ffdd1c7fd89c0c9029ae4aa72
Reformat version tests
rosolko/WebDriverManager.Net
IntegrationTests/VersionTests.cs
IntegrationTests/VersionTests.cs
using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using WebDriverManager.DriverConfigs; using WebDriverManager.DriverConfigs.Impl; using Xunit; namespace IntegrationTests { public class IndexOfData : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] {new ChromeConfig(), @"^\d+\.\d+$"}, new object[] {new EdgeConfig(), @"^\d+\.\d+$"}, new object[] {new FirefoxConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new IEConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new OperaConfig(), @"^\d+\.\d+\.\d+$"}, new object[] {new PhantomConfig(), @"^\d+\.\d+\.\d+$"} }; public IEnumerator<object[]> GetEnumerator() { return _data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } public class VersionTests { [Theory, ClassData(typeof(IndexOfData))] protected void VersionTest(IDriverConfig driverConfig, string pattern) { var version = driverConfig.GetLatestVersion(); var regex = new Regex(pattern); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } } }
using System.Text.RegularExpressions; using WebDriverManager.DriverConfigs.Impl; using Xunit; namespace IntegrationTests { public class VersionTests { [Fact] public void ChromeVersionResultNotEmptyAndMatch() { var chromeConfig = new ChromeConfig(); var version = chromeConfig.GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+$"); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } [Fact] public void EdgeVersionResultNotEmptyAndMatch() { var edgeConfig = new EdgeConfig(); var version = edgeConfig.GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+$"); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } [Fact] public void FirefoxVersionResultNotEmptyAndMatch() { var firefoxConfig = new FirefoxConfig(); var version = firefoxConfig.GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+\.\d+$"); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } [Fact] public void IEVersionResultNotEmptyAndMatch() { var ieConfig = new IEConfig(); var version = ieConfig.GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+\.\d+$"); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } [Fact] public void OperaVersionResultNotEmptyAndMatch() { var operaConfig = new OperaConfig(); var version = operaConfig.GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+\.\d+$"); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } [Fact] public void PhantomVersionResultNotEmptyAndMatch() { var phantomConfig = new PhantomConfig(); var version = phantomConfig.GetLatestVersion(); var regex = new Regex(@"^\d+\.\d+\.\d+$"); var match = regex.Match(version); Assert.NotEmpty(version); Assert.True(match.Success); } } }
mit
C#
8c249262ba55e534aaad3a13f2e8b2c85a3cd053
Add TODO note about potential improvement to dictionary
EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an
A-vs-An/WikipediaAvsAnTrieExtractor/RegexTextUtils.ExtractWordsAfterAOrAn.cs
A-vs-An/WikipediaAvsAnTrieExtractor/RegexTextUtils.ExtractWordsAfterAOrAn.cs
using System.Text.RegularExpressions; using System.Linq; using System; using System.Collections.Generic; namespace WikipediaAvsAnTrieExtractor { public partial class RegexTextUtils { //Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex //This code is bottlenecked by regexes, so this really matters, here. readonly Regex followingAn = new Regex(@"(^(?<article>An?)|[\s""()‘’“”](?<article>an?)) [""‘’“”$']*(?<word>[^\s""()‘’“”$-]+(?<!'))", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant); //general notes: //words consist of anything BUT spaces and delimiters "()‘’“”- //dash is a word delimiter in pronunciation, which is all we care about here //$ isn't a delimiter, but its an unpronounced prefix ($3 is "three dollars"), so //we exclude $ from words too. //Some tricky corner-cases: //watch out for dashes *before* "A" because of things like "Triple-A annotation" //Be careful of words like Chang'an - ' is not a separator here. //Prefer a few false negatives over false positives when it comes to article detection. //In particular, some symbolic math and logic expressions use the word "a" followed by things //like parentheses and that throws the statistics a little (but enough in rarely occuring //prefixes to matter). Therefore, don't detect a/an + word when separated by "(". public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) { //TODO: ignore uppercase "A" -it's just too hard to get right. return from Match m in followingAn.Matches(text) select new AvsAnSighting { Word = m.Groups["word"].Value, PrecededByAn = m.Groups["article"].Value.Length == 2 }; } } }
using System.Text.RegularExpressions; using System.Linq; using System; using System.Collections.Generic; namespace WikipediaAvsAnTrieExtractor { public partial class RegexTextUtils { //Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex //This code is bottlenecked by regexes, so this really matters, here. readonly Regex followingAn = new Regex(@"(^(?<article>An?)|[\s""()‘’“”](?<article>an?)) [""‘’“”$']*(?<word>[^\s""()‘’“”$-]+(?<!'))", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant); //general notes: //words consist of anything BUT spaces and delimiters "()‘’“”- //dash is a word delimiter in pronunciation, which is all we care about here //$ isn't a delimiter, but its an unpronounced prefix ($3 is "three dollars"), so //we exclude $ from words too. //Some tricky corner-cases: //watch out for dashes *before* "A" because of things like "Triple-A annotation" //Be careful of words like Chang'an - ' is not a separator here. //Prefer a few false negatives over false positives when it comes to article detection. //In particular, some symbolic math and logic expressions use the word "a" followed by things //like parentheses and that throws the statistics a little (but enough in rarely occuring //prefixes to matter). Therefore, don't detect a/an + word when separated by "(". public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) { return from Match m in followingAn.Matches(text) select new AvsAnSighting { Word = m.Groups["word"].Value, PrecededByAn = m.Groups["article"].Value.Length == 2 }; } } }
apache-2.0
C#
f830c8da35ecd30145d57e3232bee0d5ae6ec886
Implement TypeConverter CanConvertTo() and ConvertTo() methods for Uuid.
brendanjbaker/Bakery
src/Bakery/UuidTypeConverter.cs
src/Bakery/UuidTypeConverter.cs
namespace Bakery { using System; using System.ComponentModel; using System.Globalization; public class UuidTypeConverter : TypeConverter { public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(String); } public override Boolean CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return destinationType == typeof(String); } public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) { return new Uuid(Guid.Parse((String)value)); } public override Object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType) { if (value == null) return null; return value.ToString(); } } }
namespace Bakery { using System; using System.ComponentModel; using System.Globalization; public class UuidTypeConverter : TypeConverter { public override Boolean CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(String); } public override Object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value) { return new Uuid(Guid.Parse((String)value)); } } }
mit
C#
1c125eef121ebfda79bf7069765092433e242eff
Make `Users` an `IList` for more flexibility server-side
smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu-new,peppy/osu,peppy/osu
osu.Game/Online/Multiplayer/MultiplayerRoom.cs
osu.Game/Online/Multiplayer/MultiplayerRoom.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. #nullable enable using System; using System.Collections.Generic; using MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Multiplayer { /// <summary> /// A multiplayer room. /// </summary> [Serializable] [MessagePackObject] public class MultiplayerRoom { /// <summary> /// The ID of the room, used for database persistence. /// </summary> [Key(0)] public readonly long RoomID; /// <summary> /// The current state of the room (ie. whether it is in progress or otherwise). /// </summary> [Key(1)] public MultiplayerRoomState State { get; set; } /// <summary> /// All currently enforced game settings for this room. /// </summary> [Key(2)] public MultiplayerRoomSettings Settings { get; set; } = new MultiplayerRoomSettings(); /// <summary> /// All users currently in this room. /// </summary> [Key(3)] public IList<MultiplayerRoomUser> Users { get; set; } = new List<MultiplayerRoomUser>(); /// <summary> /// The host of this room, in control of changing room settings. /// </summary> [Key(4)] public MultiplayerRoomUser? Host { get; set; } [Key(5)] public MatchRulesetRoomState? MatchRulesetState { get; set; } [JsonConstructor] [SerializationConstructor] public MultiplayerRoom(long roomId) { RoomID = roomId; } public override string ToString() => $"RoomID:{RoomID} Host:{Host?.UserID} Users:{Users.Count} State:{State} Settings: [{Settings}]"; } }
// 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. #nullable enable using System; using System.Collections.Generic; using MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Multiplayer { /// <summary> /// A multiplayer room. /// </summary> [Serializable] [MessagePackObject] public class MultiplayerRoom { /// <summary> /// The ID of the room, used for database persistence. /// </summary> [Key(0)] public readonly long RoomID; /// <summary> /// The current state of the room (ie. whether it is in progress or otherwise). /// </summary> [Key(1)] public MultiplayerRoomState State { get; set; } /// <summary> /// All currently enforced game settings for this room. /// </summary> [Key(2)] public MultiplayerRoomSettings Settings { get; set; } = new MultiplayerRoomSettings(); /// <summary> /// All users currently in this room. /// </summary> [Key(3)] public List<MultiplayerRoomUser> Users { get; set; } = new List<MultiplayerRoomUser>(); /// <summary> /// The host of this room, in control of changing room settings. /// </summary> [Key(4)] public MultiplayerRoomUser? Host { get; set; } [Key(5)] public MatchRulesetRoomState? MatchRulesetState { get; set; } [JsonConstructor] [SerializationConstructor] public MultiplayerRoom(long roomId) { RoomID = roomId; } public override string ToString() => $"RoomID:{RoomID} Host:{Host?.UserID} Users:{Users.Count} State:{State} Settings: [{Settings}]"; } }
mit
C#
5328481da65830daa00737516423950966ac2338
Fix flakey tests (#475)
reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET,reactjs/React.NET
tests/React.Tests/Properties/AssemblyInfo.cs
tests/React.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using Xunit; [assembly: AssemblyTitle("React.Tests.Core")] [assembly: AssemblyDescription("Unit tests for ReactJS.NET")] [assembly: ComVisible(false)] [assembly: Guid("30a20b1c-18fd-4c3c-a18d-44875dba0c73")] [assembly: CollectionBehavior(DisableTestParallelization = true)]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("React.Tests.Core")] [assembly: AssemblyDescription("Unit tests for ReactJS.NET")] [assembly: ComVisible(false)] [assembly: Guid("30a20b1c-18fd-4c3c-a18d-44875dba0c73")]
mit
C#
af34debde72cb7e92a2dd254be2a56e57d2e4ba6
remove products for product configurations in basket
jontansey/.Net-Core-Ecommerce-Base,jontansey/.Net-Core-Ecommerce-Base
src/Shop.Core/Entites/Basket.cs
src/Shop.Core/Entites/Basket.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Shop.Core.BaseObjects; using Shop.Core.Enums; using Shop.Core.Interfaces; namespace Shop.Core.Entites { public class Basket : LifetimeBase, IReferenceable<Basket> { [Key] public int BasketId { get; set; } public string BasketReference { get; set; } public List<ProductConfiguration> ProductConfigurations { get; set; } public ShippingMethod ShippingMethod { get; set; } public DiscountCode DiscountCode { get; set; } public Basket() { BasketId = 0; BasketReference = string.Empty; ProductConfigurations = new List<ProductConfiguration>(); ShippingMethod = ShippingMethod.FirstClass; } public Basket CreateReference(IReferenceGenerator referenceGenerator) { BasketReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength); return this; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Shop.Core.BaseObjects; using Shop.Core.Enums; using Shop.Core.Interfaces; namespace Shop.Core.Entites { public class Basket : LifetimeBase, IReferenceable<Basket> { [Key] public int BasketId { get; set; } public string BasketReference { get; set; } public List<BasketProduct> Products { get; set; } public List<ProductConfiguration> ProductConfigurations { get; set; } public ShippingMethod ShippingMethod { get; set; } public DiscountCode DiscountCode { get; set; } public Basket() { BasketId = 0; BasketReference = string.Empty; Products = new List<BasketProduct>(); ProductConfigurations = new List<ProductConfiguration>(); ShippingMethod = ShippingMethod.FirstClass; DiscountCode = null; } public Basket CreateReference(IReferenceGenerator referenceGenerator) { BasketReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength); return this; } } }
mit
C#
1a4a4754f6067858fc74109fc861202ddd949f24
Add comment
panopticoncentral/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,genlu/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,AlekseyTs/roslyn,genlu/roslyn,jmarolf/roslyn,aelij/roslyn,swaroop-sridhar/roslyn,eriawan/roslyn,davkean/roslyn,jcouv/roslyn,brettfo/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,gafter/roslyn,tmat/roslyn,tannergooding/roslyn,reaction1989/roslyn,bartdesmet/roslyn,jcouv/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,nguerrera/roslyn,reaction1989/roslyn,agocke/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,eriawan/roslyn,davkean/roslyn,weltkante/roslyn,tmat/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,dotnet/roslyn,wvdd007/roslyn,sharwell/roslyn,mavasani/roslyn,heejaechang/roslyn,abock/roslyn,aelij/roslyn,heejaechang/roslyn,tmat/roslyn,dotnet/roslyn,heejaechang/roslyn,VSadov/roslyn,DustinCampbell/roslyn,nguerrera/roslyn,stephentoub/roslyn,mavasani/roslyn,jcouv/roslyn,abock/roslyn,abock/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,mavasani/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,jmarolf/roslyn,tannergooding/roslyn,reaction1989/roslyn,sharwell/roslyn,agocke/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,AlekseyTs/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,jmarolf/roslyn,eriawan/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,physhi/roslyn,aelij/roslyn,DustinCampbell/roslyn,davkean/roslyn,gafter/roslyn,DustinCampbell/roslyn,wvdd007/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,agocke/roslyn,panopticoncentral/roslyn,VSadov/roslyn,weltkante/roslyn,stephentoub/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,nguerrera/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,panopticoncentral/roslyn
src/EditorFeatures/Core/Implementation/SmartIndent/IBlankLineIndentationService.cs
src/EditorFeatures/Core/Implementation/SmartIndent/IBlankLineIndentationService.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.Threading; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.Editor { internal interface IBlankLineIndentationService { /// <summary> /// Determines indentation for a blank line (i.e. after hitting enter at the end of a line, /// or after moving to a blank line). The <paramref name="indentStyle"/> provided cannot be /// <see cref="FormattingOptions.IndentStyle.None"/>. /// /// Specifically, this function operates as if the line specified by <paramref name="lineNumber"/> /// is blank. The actual contents of the line do not matter. All indentation information is /// determined from the previous lines in the document. /// </summary> IndentationResult GetBlankLineIndentation( Document document, int lineNumber, FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken); } }
// 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.Threading; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.Editor { internal interface IBlankLineIndentationService { /// <summary> /// Determines indentation for a blank line (i.e. after hitting enter at the end of a line, /// or after moving to a blank line). This indent style cannot be <see cref="FormattingOptions.IndentStyle.None"/>; /// </summary> IndentationResult GetBlankLineIndentation( Document document, int lineNumber, FormattingOptions.IndentStyle indentStyle, CancellationToken cancellationToken); } }
mit
C#
c6a4e970755f9994720bb908dd7426c42e4de5d5
Add constructor from separate values.
mcneel/RhinoCycles
LinearWorkflow.cs
LinearWorkflow.cs
/** Copyright 2014-2015 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using System; using LwFlow = Rhino.Render.ChangeQueue.LinearWorkflow; namespace RhinoCycles { public class LinearWorkflow { public bool Active { get; set; } public float Gamma { get; set; } public float GammaReciprocal { get; set; } public LinearWorkflow(LwFlow lwf) { Active = lwf.Active; Gamma = lwf.Gamma; GammaReciprocal = lwf.GammaReciprocal; } public LinearWorkflow(bool active, float gamma) { Active = active; Gamma = gamma; GammaReciprocal = 1.0f/gamma; } public LinearWorkflow(LinearWorkflow old) { Active = old.Active; Gamma = old.Gamma; GammaReciprocal = old.GammaReciprocal; } public override bool Equals(object obj) { LinearWorkflow lwf = obj as LinearWorkflow; if (lwf == null) return false; return Active == lwf.Active && Math.Abs(Gamma-lwf.Gamma) < float.Epsilon && Math.Abs(GammaReciprocal - lwf.GammaReciprocal) < float.Epsilon; } } }
/** Copyright 2014-2015 Robert McNeel and Associates Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **/ using System; using LwFlow = Rhino.Render.ChangeQueue.LinearWorkflow; namespace RhinoCycles { public class LinearWorkflow { public bool Active { get; set; } public float Gamma { get; set; } public float GammaReciprocal { get; set; } public LinearWorkflow(LwFlow lwf) { Active = lwf.Active; Gamma = lwf.Gamma; GammaReciprocal = lwf.GammaReciprocal; } public LinearWorkflow(LinearWorkflow old) { Active = old.Active; Gamma = old.Gamma; GammaReciprocal = old.GammaReciprocal; } public override bool Equals(object obj) { LinearWorkflow lwf = obj as LinearWorkflow; if (lwf == null) return false; return Active == lwf.Active && Math.Abs(Gamma-lwf.Gamma) < float.Epsilon && Math.Abs(GammaReciprocal - lwf.GammaReciprocal) < float.Epsilon; } } }
apache-2.0
C#
8d9adaacd8da0dc946b5c40b902d9997dfd27572
Remove unused import
MHeasell/Mappy,MHeasell/Mappy
Mappy/IO/SectionLoader.cs
Mappy/IO/SectionLoader.cs
namespace Mappy.IO { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Mappy.Data; using TAUtil.Hpi; using TAUtil.Sct; public class SectionLoader : AbstractHpiLoader<Section> { private readonly SectionFactory factory; public SectionLoader() { this.factory = new SectionFactory(); } protected override void LoadFile(HpiReader h, string sect) { using (var s = new SctReader(h.ReadFile(sect))) { var section = new Section(h.FileName, sect); section.Name = HpiPath.GetFileNameWithoutExtension(sect); section.Minimap = this.factory.MinimapFromSct(s); section.DataWidth = s.DataWidth; section.DataHeight = s.DataHeight; string directoryString = HpiPath.GetDirectoryName(sect); Debug.Assert(directoryString != null, "Null directory for section in HPI."); string[] directories = directoryString.Split('\\'); section.World = directories[1]; section.Category = directories[2]; this.Records.Add(section); } } protected override IEnumerable<string> EnumerateFiles(HpiReader r) { return r.GetFilesRecursive("sections") .Select(x => x.Name) .Where(x => x.EndsWith(".sct", StringComparison.OrdinalIgnoreCase)); } } }
namespace Mappy.IO { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Mappy.Data; using TAUtil.Gdi.Palette; using TAUtil.Hpi; using TAUtil.Sct; public class SectionLoader : AbstractHpiLoader<Section> { private readonly SectionFactory factory; public SectionLoader() { this.factory = new SectionFactory(); } protected override void LoadFile(HpiReader h, string sect) { using (var s = new SctReader(h.ReadFile(sect))) { var section = new Section(h.FileName, sect); section.Name = HpiPath.GetFileNameWithoutExtension(sect); section.Minimap = this.factory.MinimapFromSct(s); section.DataWidth = s.DataWidth; section.DataHeight = s.DataHeight; string directoryString = HpiPath.GetDirectoryName(sect); Debug.Assert(directoryString != null, "Null directory for section in HPI."); string[] directories = directoryString.Split('\\'); section.World = directories[1]; section.Category = directories[2]; this.Records.Add(section); } } protected override IEnumerable<string> EnumerateFiles(HpiReader r) { return r.GetFilesRecursive("sections") .Select(x => x.Name) .Where(x => x.EndsWith(".sct", StringComparison.OrdinalIgnoreCase)); } } }
mit
C#
65bbc610bf212ac9b054fef1f7e760501869cf56
Fix start of week calculation
davidebbo/ForumScorer
Models/Helpers.cs
Models/Helpers.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForumModels { public static class Helpers { public static DateTimeOffset GetStartOfWeek(string date) { var dt = DateTimeOffset.Now; if (!String.IsNullOrEmpty(date)) { dt = DateTimeOffset.Parse(date); } dt = dt.ToLocalTime(); var dayOfWeekLocal = (int)dt.DayOfWeek; // Adjust it so the week starts Monday instead of Sunday dayOfWeekLocal = (dayOfWeekLocal + 6) % 7; // Go back to the start of the current week return dt.Date.AddDays(-dayOfWeekLocal); } public static string GetDataFileNameFromDate(DateTimeOffset startOfPeriod) { return startOfPeriod.ToString("yyyy-MM-dd") + ".json"; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ForumModels { public static class Helpers { public static DateTimeOffset GetStartOfWeek(string date) { var dt = DateTimeOffset.Now; if (!String.IsNullOrEmpty(date)) { dt = DateTimeOffset.Parse(date); } dt = dt.ToLocalTime(); var dayOfWeekLocal = (int)dt.DayOfWeek; // +1 because we want to start the week on Monday and not Sunday (local time) return dt.Date.AddDays(-dayOfWeekLocal + 1); } public static string GetDataFileNameFromDate(DateTimeOffset startOfPeriod) { return startOfPeriod.ToString("yyyy-MM-dd") + ".json"; } } }
apache-2.0
C#
b8ecfd744cb58338626e70185cb2c633b78c8e3a
Make use of asynchronous methods
Selz/PexelsNet
PexelsNet/PexelsClient.cs
PexelsNet/PexelsClient.cs
using System; using System.Net.Http; using Newtonsoft.Json; using System.Threading.Tasks; namespace PexelsNet { public class PexelsClient { private readonly string _apiKey; private const string BaseUrl = "http://api.pexels.com/v1/"; public PexelsClient(string apiKey) { _apiKey = apiKey; } private HttpClient InitHttpClient() { var client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _apiKey); return client; } public async Task<Page> SearchAsync(string query, int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = await client.GetAsync(BaseUrl + "search?query=" + Uri.EscapeDataString(query) + "&per_page=" + perPage + "&page=" + page); return await GetResultAsync(response); } public async Task<Page> PopularAsync(int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = await client.GetAsync(BaseUrl + "popular?per_page=" + perPage + "&page=" + page); return await GetResultAsync(response); } private static async Task<Page> GetResultAsync(HttpResponseMessage response) { var body = await response.Content.ReadAsStringAsync(); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<Page>(body); } throw new PexelsNetException(response.StatusCode, body); } } }
using System; using System.Net.Http; using Newtonsoft.Json; namespace PexelsNet { public class PexelsClient { private readonly string _apiKey; private const string BaseUrl = "http://api.pexels.com/v1/"; public PexelsClient(string apiKey) { _apiKey = apiKey; } private HttpClient InitHttpClient() { var client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", _apiKey); return client; } public Page Search(string query, int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = client.GetAsync(BaseUrl + "search?query=" + Uri.EscapeDataString(query) + "&per_page="+ perPage + "&page=" + page).Result; return GetResult(response); } public Page Popular(int page = 1, int perPage = 15) { var client = InitHttpClient(); HttpResponseMessage response = client.GetAsync(BaseUrl + "popular?per_page=" + perPage + "&page=" + page).Result; return GetResult(response); } private static Page GetResult(HttpResponseMessage response) { var body = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { return JsonConvert.DeserializeObject<Page>(body); } throw new PexelsNetException(response.StatusCode, body); } } }
mit
C#
efbfb3dbef4b9174a6148f98e759ff2e57828301
Implement Assembly.GetExecutingAssembly
shrah/corert,krytarowski/corert,botaberg/corert,yizhang82/corert,botaberg/corert,shrah/corert,gregkalapos/corert,yizhang82/corert,tijoytom/corert,gregkalapos/corert,tijoytom/corert,yizhang82/corert,tijoytom/corert,gregkalapos/corert,shrah/corert,botaberg/corert,yizhang82/corert,krytarowski/corert,tijoytom/corert,gregkalapos/corert,krytarowski/corert,botaberg/corert,krytarowski/corert,shrah/corert
src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/ReflectionHelpers.cs
src/System.Private.CoreLib/src/Internal/Runtime/CompilerHelpers/ReflectionHelpers.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.Reflection; using Internal.Runtime.Augments; namespace Internal.Runtime.CompilerHelpers { /// <summary> /// Set of helpers used to implement callsite-specific reflection intrinsics. /// </summary> internal static class ReflectionHelpers { // This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as // a default assembly name. public static Type GetType(string typeName, string callingAssemblyName, bool throwOnError, bool ignoreCase) { return ExtensibleGetType(typeName, callingAssemblyName, null, null, throwOnError: throwOnError, ignoreCase: ignoreCase); } // This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as // a default assembly name. public static Type ExtensibleGetType(string typeName, string callingAssemblyName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase) { return RuntimeAugments.Callbacks.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, callingAssemblyName); } // This supports Assembly.GetExecutingAssembly() intrinsic expansion in the compiler [System.Runtime.CompilerServices.DependencyReductionRoot] public static Assembly GetExecutingAssembly(RuntimeTypeHandle typeHandle) { return Type.GetTypeFromHandle(typeHandle).Assembly; } } }
// 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.Reflection; using Internal.Runtime.Augments; namespace Internal.Runtime.CompilerHelpers { /// <summary> /// Set of helpers used to implement callsite-specific reflection intrinsics. /// </summary> internal static class ReflectionHelpers { // This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as // a default assembly name. public static Type GetType(string typeName, string callingAssemblyName, bool throwOnError, bool ignoreCase) { return ExtensibleGetType(typeName, callingAssemblyName, null, null, throwOnError: throwOnError, ignoreCase: ignoreCase); } // This entry is used to implement Type.GetType()'s ability to detect the calling assembly and use it as // a default assembly name. public static Type ExtensibleGetType(string typeName, string callingAssemblyName, Func<AssemblyName, Assembly> assemblyResolver, Func<Assembly, string, bool, Type> typeResolver, bool throwOnError, bool ignoreCase) { return RuntimeAugments.Callbacks.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, callingAssemblyName); } } }
mit
C#
7c5b04e89d070487c75fe1958a76dee483a5311d
Switch to version 1.4.2
biarne-a/Zebus,Abc-Arbitrage/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.4.2")] [assembly: AssemblyFileVersion("1.4.2")] [assembly: AssemblyInformationalVersion("1.4.2")]
using System.Reflection; [assembly: AssemblyVersion("1.4.1")] [assembly: AssemblyFileVersion("1.4.1")] [assembly: AssemblyInformationalVersion("1.4.1")]
mit
C#
37e5f89921f38ffe82b9fab39485a8424bbe99b2
use one action for find symbols
jtbm37/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,jtbm37/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,sreal/omnisharp-roslyn,khellang/omnisharp-roslyn,fishg/omnisharp-roslyn,haled/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,hal-ler/omnisharp-roslyn,hitesh97/omnisharp-roslyn,nabychan/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,sreal/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,sriramgd/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,hach-que/omnisharp-roslyn,sriramgd/omnisharp-roslyn,hitesh97/omnisharp-roslyn,hach-que/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,fishg/omnisharp-roslyn,haled/omnisharp-roslyn,khellang/omnisharp-roslyn,nabychan/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,hal-ler/omnisharp-roslyn
src/OmniSharp/Api/Navigation/OmnisharpController.FindSymbols.cs
src/OmniSharp/Api/Navigation/OmnisharpController.FindSymbols.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using OmniSharp.Extensions; using OmniSharp.Models; namespace OmniSharp { public partial class OmnisharpController { [HttpPost("findsymbols")] public async Task<QuickFixResponse> FindSymbols(FindSymbolsRequest request = null) { Func<string, bool> isMatch = candidate => request != null ? candidate.IsValidCompletionFor(request.Filter) : true; return await FindSymbols(isMatch); } private async Task<QuickFixResponse> FindSymbols(Func<string, bool> predicate) { var symbols = await SymbolFinder.FindSourceDeclarationsAsync(_workspace.CurrentSolution, predicate); var quickFixes = (from symbol in symbols from location in symbol.Locations where symbol.CanBeReferencedByName && symbol.Kind != SymbolKind.Namespace select ConvertSymbol(symbol, location)).Distinct(); return new QuickFixResponse(quickFixes); } private QuickFix ConvertSymbol(ISymbol symbol, Location location) { var lineSpan = location.GetLineSpan(); var path = lineSpan.Path; var documents = _workspace.GetDocuments(path); return new QuickFix { Text = new SnippetGenerator().GenerateSnippet(symbol), FileName = path, Line = lineSpan.StartLinePosition.Line + 1, Column = lineSpan.StartLinePosition.Character + 1, EndLine = lineSpan.EndLinePosition.Line + 1, EndColumn = lineSpan.EndLinePosition.Character + 1, Projects = documents.Select(document => document.Project.Name).ToArray() }; } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using OmniSharp.Extensions; using OmniSharp.Models; namespace OmniSharp { public partial class OmnisharpController { [HttpPost("findsymbols")] public async Task<QuickFixResponse> FindSymbols() { Func<string, bool> isMatch = candidate => true; return await FindSymbols(isMatch); } [HttpPost("findsymbolswithfilter")] public async Task<QuickFixResponse> FindSymbols(FindSymbolsRequest request) { Func<string, bool> isMatch = candidate => candidate.IsValidCompletionFor(request.Filter); return await FindSymbols(isMatch); } private async Task<QuickFixResponse> FindSymbols(Func<string, bool> predicate) { var symbols = await SymbolFinder.FindSourceDeclarationsAsync(_workspace.CurrentSolution, predicate); var quickFixes = (from symbol in symbols from location in symbol.Locations where symbol.CanBeReferencedByName && symbol.Kind != SymbolKind.Namespace select ConvertSymbol(symbol, location)).Distinct(); return new QuickFixResponse(quickFixes); } private QuickFix ConvertSymbol(ISymbol symbol, Location location) { var lineSpan = location.GetLineSpan(); var path = lineSpan.Path; var documents = _workspace.GetDocuments(path); return new QuickFix { Text = new SnippetGenerator().GenerateSnippet(symbol), FileName = path, Line = lineSpan.StartLinePosition.Line + 1, Column = lineSpan.StartLinePosition.Character + 1, EndLine = lineSpan.EndLinePosition.Line + 1, EndColumn = lineSpan.EndLinePosition.Character + 1, Projects = documents.Select(document => document.Project.Name).ToArray() }; } } }
mit
C#
71402778d7589422b80fa1ab2a2dba2d58d53932
Fix GetHistory test
svedm/monodevelop-hg-addin
MonoDevelop.VersionControl.Mercurial/MonoDevelop.VersionControl.Tests/MercurialClientTests.cs
MonoDevelop.VersionControl.Mercurial/MonoDevelop.VersionControl.Tests/MercurialClientTests.cs
using NUnit.Framework; using System; using MonoDevelop.VersionControl.Mercurial; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; namespace MonoDevelop.VersionControl.Tests { [TestFixture] public class MercurialClientTests { private string _currentPath; private string _testRepoPath; private MercurialClient _mc; private string _testFilePath; private const string _testFileContent = "qweqwe"; [TestFixtureSetUp] public void Init() { Console.InputEncoding = new UTF8Encoding(false); _currentPath = Directory.GetCurrentDirectory(); _testRepoPath = Path.Combine(_currentPath, "testRepo"); if (Directory.Exists(_testRepoPath)) { Directory.Delete(_testRepoPath, true); } Directory.CreateDirectory(_testRepoPath); var os = Environment.OSVersion.VersionString.ToLower(); var hgPath = (os.Contains("win")) ? "hg" : (TestsUtils.IsRunningOnMac()) ? "/usr/local/bin/hg" : "/usr/bin/hg"; MercurialClient.Init(_testRepoPath, hgPath); _mc = new MercurialClient(_testRepoPath, hgPath); _testFilePath = Path.Combine(_testRepoPath, "qwe.txt"); File.AppendAllText(_testFilePath, _testFileContent); _mc.Add(new string[] { _testFilePath }); _mc.Commit("first commit"); } [Test] public void CatWithoutRevision() { var res = _mc.Cat(_testFilePath, null); Assert.AreEqual(_testFileContent, res); } [Test] public void GetHistory() { var res = _mc.Log(null, new List<string> { _testFilePath }); Assert.AreEqual(res[0].Message, "first commit"); } [TestFixtureTearDown] public void CleanUp() { Directory.Delete(_testRepoPath, true); } } }
using NUnit.Framework; using System; using MonoDevelop.VersionControl.Mercurial; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; namespace MonoDevelop.VersionControl.Tests { [TestFixture] public class MercurialClientTests { private string _currentPath; private string _testRepoPath; private MercurialClient _mc; private string _testFilePath; private const string _testFileContent = "qweqwe"; [TestFixtureSetUp] public void Init() { Console.InputEncoding = new UTF8Encoding(false); _currentPath = Directory.GetCurrentDirectory(); _testRepoPath = Path.Combine(_currentPath, "testRepo"); if (Directory.Exists(_testRepoPath)) { Directory.Delete(_testRepoPath, true); } Directory.CreateDirectory(_testRepoPath); var os = Environment.OSVersion.VersionString.ToLower(); var hgPath = (os.Contains("win")) ? "hg" : (TestsUtils.IsRunningOnMac()) ? "/usr/local/bin/hg" : "/usr/bin/hg"; MercurialClient.Init(_testRepoPath, hgPath); _mc = new MercurialClient(_testRepoPath, hgPath); _testFilePath = Path.Combine(_testRepoPath, "qwe.txt"); File.AppendAllText(_testFilePath, _testFileContent); _mc.Add(new string[] { _testFilePath }); _mc.Commit("first commit"); } [TestFixtureTearDown] public void CleanUp() { Directory.Delete(_testRepoPath, true); } [Test] public void CatWithoutRevision() { var res = _mc.Cat(_testFilePath, null); Assert.AreEqual(_testFileContent, res); } [Test] public void GetHistory() { var res = _mc.Log(null, new List<string> { _testFilePath }); } } }
mit
C#
cfea31c7043d036bb5d12f175a653212f4aa8a5c
Throw Exception if cert == null
yfann/AuthorizationServer,yfann/AuthorizationServer,IdentityModel/AuthorizationServer,IdentityModel/AuthorizationServer
source/Libraries/Thinktecture.AuthorizationServer.Core/Models/SigningKey.cs
source/Libraries/Thinktecture.AuthorizationServer.Core/Models/SigningKey.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IdentityModel.Tokens; using System.Linq; using System.Security.Cryptography.X509Certificates; using Thinktecture.IdentityModel; using Thinktecture.IdentityModel.Tokens; namespace Thinktecture.AuthorizationServer.Models { public abstract class SigningKey { public virtual int ID { get; set; } [Required] public virtual string Name { get; set; } public abstract SigningCredentials GetSigningCredentials(); public virtual ICollection<Application> Applications { get; set; } } public class X509CertificateReference : SigningKey { public virtual StoreLocation Location { get; set; } public virtual StoreName StoreName { get; set; } public virtual X509FindType FindType { get; set; } [Required] public virtual string FindValue { get; set; } public X509Certificate2 Certificate { get { return new X509CertificatesFinder( this.Location, this.StoreName, this.FindType) .Find(this.FindValue, false).SingleOrDefault(); } } public override SigningCredentials GetSigningCredentials() { var cert = this.Certificate; if (cert == null) throw new InvalidOperationException("A certificate is required to create SigningCredentials"); return new X509SigningCredentials(cert); } } public class SymmetricKey : SigningKey { [Required] public virtual byte[] Value { get; private set; } public void SetValue(byte[] value) { if (value == null || value.Length == 0) throw new ArgumentNullException("value"); this.Value = DataProtectection.Instance.Protect(value); } public byte[] GetValue() { if (this.Value == null) return null; return DataProtectection.Instance.Unprotect(this.Value); } public override SigningCredentials GetSigningCredentials() { var val = GetValue(); if (val == null) return null; return new HmacSigningCredentials(val); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IdentityModel.Tokens; using System.Linq; using System.Security.Cryptography.X509Certificates; using Thinktecture.IdentityModel; using Thinktecture.IdentityModel.Tokens; namespace Thinktecture.AuthorizationServer.Models { public abstract class SigningKey { public virtual int ID { get; set; } [Required] public virtual string Name { get; set; } public abstract SigningCredentials GetSigningCredentials(); public virtual ICollection<Application> Applications { get; set; } } public class X509CertificateReference : SigningKey { public virtual StoreLocation Location { get; set; } public virtual StoreName StoreName { get; set; } public virtual X509FindType FindType { get; set; } [Required] public virtual string FindValue { get; set; } public X509Certificate2 Certificate { get { return new X509CertificatesFinder( this.Location, this.StoreName, this.FindType) .Find(this.FindValue, false).SingleOrDefault(); } } public override SigningCredentials GetSigningCredentials() { var cert = this.Certificate; if (cert == null) return null; return new X509SigningCredentials(cert); } } public class SymmetricKey : SigningKey { [Required] public virtual byte[] Value { get; private set; } public void SetValue(byte[] value) { if (value == null || value.Length == 0) throw new ArgumentNullException("value"); this.Value = DataProtectection.Instance.Protect(value); } public byte[] GetValue() { if (this.Value == null) return null; return DataProtectection.Instance.Unprotect(this.Value); } public override SigningCredentials GetSigningCredentials() { var val = GetValue(); if (val == null) return null; return new HmacSigningCredentials(val); } } }
bsd-3-clause
C#
c5f653aee20efa5ae487deb403945b8935bd8160
Fix isssue with no defined path for console example application
stranne/Vasttrafik.NET,stranne/Vasttrafik.NET
src/Examples/Stranne.VasttrafikNET.Examples.DownloadParkingImage/Program.cs
src/Examples/Stranne.VasttrafikNET.Examples.DownloadParkingImage/Program.cs
using System; using System.IO; namespace Stranne.VasttrafikNET.Examples.DownloadParkingImage { class Program { private const string DeviceId = "Download Parking Image Example"; static void Main(string[] args) { if (args.Length < 4) { Console.WriteLine("Please enter which parking and camera id from where the image should be downloaded from."); Console.WriteLine("Usage: Parking id <number> Camera id <number> Västtrafik key <string> Västtrafik secret <string> Download directory <string|optional>"); return; } var id = int.Parse(args[0]); var cameraId = int.Parse(args[1]); var vtKey = args[2]; var vtSecret = args[3]; var imagePath = args.Length >= 5 ? args[4] : ".\\"; imagePath = imagePath.TrimEnd('\\'); if (!string.IsNullOrWhiteSpace(imagePath) && imagePath != ".") Directory.CreateDirectory(imagePath); var file = $@"{imagePath}\Vasttrafik_id-{id}_cameraId-{cameraId}_{DateTime.Now:yyyy-MM-dd_hh-mm}.gif"; DownloadCameraImage(file, id, cameraId, vtKey, vtSecret); Console.WriteLine($"Camera image saved at {file}"); } private static void DownloadCameraImage(string file, int id, int cameraId, string vtKey, string vtSecret) { using (var commuterParkingService = new CommuterParkingService(vtKey, vtSecret, DeviceId)) { var stream = commuterParkingService.GetParkingImage(id, cameraId); using (var fileStream = File.Create(file)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } } } } }
using System; using System.IO; namespace Stranne.VasttrafikNET.Examples.DownloadParkingImage { class Program { private const string DeviceId = "Download Parking Image Example"; static void Main(string[] args) { if (args.Length < 4) { Console.WriteLine("Please enter which parking and camera id from where the image should be downloaded from."); Console.WriteLine("Usage: Parking id <number> Camera id <number> Västtrafik key <string> Västtrafik secret <string> Download directory <string|optional>"); return; } var id = int.Parse(args[0]); var cameraId = int.Parse(args[1]); var vtKey = args[2]; var vtSecret = args[3]; var imagePath = args.Length >= 5 ? args[4] : ".\\"; imagePath = imagePath.TrimEnd('\\'); Directory.CreateDirectory(imagePath); var file = $@"{imagePath}\Västtrafik_id-{id}_cameraId-{cameraId}_{DateTime.Now:yyyy-MM-dd_hh-mm}.gif"; DownloadCameraImage(file, id, cameraId, vtKey, vtSecret); Console.WriteLine($"Camera image saved at {file}"); } private static void DownloadCameraImage(string file, int id, int cameraId, string vtKey, string vtSecret) { using (var commuterParkingService = new CommuterParkingService(vtKey, vtSecret, DeviceId)) { var stream = commuterParkingService.GetParkingImage(id, cameraId); using (var fileStream = File.Create(file)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(fileStream); } } } } }
mit
C#
a0df5b01473177f135aa26fb5dfa2bea74923d38
Add notification before deploying to Docker
Sitecore/Sitecore-Instance-Manager
src/SIM.Tool.Windows/MainWindowComponents/Buttons/InstallContainerButton.cs
src/SIM.Tool.Windows/MainWindowComponents/Buttons/InstallContainerButton.cs
namespace SIM.Tool.Windows.MainWindowComponents { using System.Linq; using System.Windows; using SIM.Instances; using SIM.Products; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; using SIM.Tool.Base.Profiles; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using SIM.Tool.Base.Pipelines; using SIM.Tool.Base.Wizards; [UsedImplicitly] public class InstallContainerButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public bool IsVisible(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { Assert.IsTrue(ProfileManager.IsValid, "Some of configuration settings are invalid - please fix them in Settings dialog and try again"); if (!ProductManager.ContainerProducts.Any()) { string message = $@"You don't have any container product package in your repository. If you already have them then you can either: * change the local repository folder (Ribbon -> Home -> Settings button) to the one that contains the files * download a package from 'https://github.com/Sitecore/container-deployment/releases', put the file into the current local repository folder: '{ProfileManager.Profile.LocalRepository}'"; MessageBox.Show(message, "", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (!ApplicationManager.IsDockerRunning) { string message = "The 'Docker Desktop' application is not running. Please start the app and re-run the deployment Sitecore to Docker."; MessageBox.Show(message, "", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (ApplicationManager.IsIisRunning) { string urlToWikiPage = "https://github.com/Sitecore/Sitecore-Instance-Manager/wiki/Troubleshooting"; string message = $@"The IIS is running now. It may prevent 'docker-compose' from spinning up Sitecore in Docker, due to the HTTPS(443) port usage conflict. Please visit the '{urlToWikiPage}' for details. Please stop the IIS and continue the installation. Do you want to proceed with the installation process?"; if (MessageBox.Show(message, "", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) { return; } } if (EnvironmentHelper.CheckSqlServer()) { WizardPipelineManager.Start("installContainer", mainWindow, null, null, (args) => { if (args == null) { return; } var install = (InstallWizardArgs)args; var product = install.Product; if (product == null) { return; } if (install.ShouldRefreshInstancesList) { MainWindowHelper.RefreshInstances(); } }, () => new InstallContainerWizardArgs()); } } #endregion } }
namespace SIM.Tool.Windows.MainWindowComponents { using System.Linq; using System.Windows; using SIM.Instances; using SIM.Products; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; using SIM.Tool.Base.Profiles; using Sitecore.Diagnostics.Base; using JetBrains.Annotations; using SIM.Tool.Base.Pipelines; using SIM.Tool.Base.Wizards; [UsedImplicitly] public class InstallContainerButton : IMainWindowButton { #region Public methods public bool IsEnabled(Window mainWindow, Instance instance) { return true; } public bool IsVisible(Window mainWindow, Instance instance) { return true; } public void OnClick(Window mainWindow, Instance instance) { Assert.IsTrue(ProfileManager.IsValid, "Some of configuration settings are invalid - please fix them in Settings dialog and try again"); if (!ProductManager.ContainerProducts.Any()) { string message = $@"You don't have any container product package in your repository. If you already have them then you can either: * change the local repository folder (Ribbon -> Home -> Settings button) to the one that contains the files * download a package from 'https://github.com/Sitecore/container-deployment/releases', put the file into the current local repository folder: '{ProfileManager.Profile.LocalRepository}'"; MessageBox.Show(message, "", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (!ApplicationManager.IsDockerRunning) { string message = "The 'Docker Desktop' application is not running. Please start the app and re-run the deployment Sitecore to Docker."; MessageBox.Show(message, "", MessageBoxButton.OK, MessageBoxImage.Information); return; } if (EnvironmentHelper.CheckSqlServer()) { WizardPipelineManager.Start("installContainer", mainWindow, null, null, (args) => { if (args == null) { return; } var install = (InstallWizardArgs)args; var product = install.Product; if (product == null) { return; } if (install.ShouldRefreshInstancesList) { MainWindowHelper.RefreshInstances(); } }, () => new InstallContainerWizardArgs()); } } #endregion } }
mit
C#
6f3e822774d786ccf66356d1c05bfec3b459e977
Increment build number
rajeshganesh/amqpnetlite,ChugR/amqpnetlite,mbroadst/amqpnetlite,CedarLogic/amqpnetlite,Azure/amqpnetlite,timhermann/amqpnetlite
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ 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("Amqp 1.0")] [assembly: AssemblyDescription("AMQP 1.0 .Net Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amqp")] [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("d1389a8f-5b67-4112-9415-8dd5b6bc72c8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("0.1.2.0")] [assembly: AssemblyFileVersion("0.1.2.0")]
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ 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("Amqp 1.0")] [assembly: AssemblyDescription("AMQP 1.0 .Net Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amqp")] [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("d1389a8f-5b67-4112-9415-8dd5b6bc72c8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")]
apache-2.0
C#
e87197c7fc80b9d40e85829b2120cfbbf8cca87d
Adjust text size
smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu
osu.Game/Overlays/Profile/Header/Components/ProfileHeaderStatisticsButton.cs
osu.Game/Overlays/Profile/Header/Components/ProfileHeaderStatisticsButton.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK; namespace osu.Game.Overlays.Profile.Header.Components { public abstract class ProfileHeaderStatisticsButton : ProfileHeaderButton { private readonly OsuSpriteText drawableText; protected ProfileHeaderStatisticsButton() { RelativeSizeAxes = Axes.Y; Child = new FillFlowContainer { AutoSizeAxes = Axes.X, RelativeSizeAxes = Axes.Y, Anchor = Anchor.Centre, Origin = Anchor.Centre, Direction = FillDirection.Horizontal, Children = new Drawable[] { new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = CreateIcon, FillMode = FillMode.Fit, Size = new Vector2(50, 14) }, drawableText = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Margin = new MarginPadding { Right = 10 }, Font = OsuFont.GetFont(size: 14, weight: FontWeight.Bold) } } }; } protected abstract IconUsage CreateIcon { get; } protected void SetValue(int value) => drawableText.Text = value.ToString("#,##0"); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK; namespace osu.Game.Overlays.Profile.Header.Components { public abstract class ProfileHeaderStatisticsButton : ProfileHeaderButton { private readonly OsuSpriteText drawableText; protected ProfileHeaderStatisticsButton() { RelativeSizeAxes = Axes.Y; Child = new FillFlowContainer { AutoSizeAxes = Axes.X, RelativeSizeAxes = Axes.Y, Anchor = Anchor.Centre, Origin = Anchor.Centre, Direction = FillDirection.Horizontal, Children = new Drawable[] { new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = CreateIcon, FillMode = FillMode.Fit, Size = new Vector2(50, 14) }, drawableText = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Margin = new MarginPadding { Right = 10 }, Font = OsuFont.GetFont(weight: FontWeight.Bold) } } }; } protected abstract IconUsage CreateIcon { get; } protected void SetValue(int value) => drawableText.Text = value.ToString("#,##0"); } }
mit
C#
764ef770f78b3755db2ab579cc073cdc31ff74f0
Update Menu.cs
nabrozidhs/unity_googleinapp_android,nabrozidhs/unity_googleinapp_android
unity/Assets/Scripts/Menu.cs
unity/Assets/Scripts/Menu.cs
using UnityEngine; using System.Collections; [RequireComponent(typeof(GoogleInAppPlugin))] public class Menu : MonoBehaviour { private static string INAPP_ITEM = "REPLACE_INADD_ITEM"; private static Vector2 BUTTON_SIZE = new Vector2(100, 50); private static Vector2 TEXT_SIZE = 2 * BUTTON_SIZE; private Rect buttonPosition; private Rect textPosition; private GoogleInAppPlugin inApp; private bool purchased; void Start() { buttonPosition = new Rect( (Screen.width - BUTTON_SIZE.x) / 2, (Screen.height - BUTTON_SIZE.y) / 2, BUTTON_SIZE.x, BUTTON_SIZE.y); textPosition = new Rect( (Screen.width - TEXT_SIZE.x) / 2, buttonPosition.y + 2 * BUTTON_SIZE.y, TEXT_SIZE.x, TEXT_SIZE.y); #if UNITY_ANDROID inApp = GetComponent<GoogleInAppPlugin>(); GoogleInAppPlugin.BindComplete += HandleBindComplete; inApp.Bind(); #endif } void OnGUI () { GUI.TextArea( textPosition, "Item " + INAPP_ITEM + (purchased ? " purchased." : " not purchased.")); if (GUI.Button(buttonPosition, "Purchase")) { #if UNITY_ANDROID inApp.PurchaseItem(INAPP_ITEM); #endif } } void OnApplicationFocus(bool focused) { if (focused) { #if UNITY_ANDROID purchased = inApp.IsItemPurchased(INAPP_ITEM); #endif } } /// <summary> /// Handles the bind complete event from GoogleInAppPlugin. /// </summary> public void HandleBindComplete() { #if UNITY_ANDROID purchased = inApp.IsItemPurchased(INAPP_ITEM); #endif } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(GoogleInAppPlugin))] public class Menu : MonoBehaviour { private static string INAPP_ITEM = "REPLACE_INADD_ITEM"; private static Vector2 BUTTON_SIZE = new Vector2(100, 50); private static Vector2 TEXT_SIZE = 2 * BUTTON_SIZE; private Rect buttonPosition; private Rect textPosition; private GoogleInAppPlugin inApp; private bool purchased; void Start() { buttonPosition = new Rect( (Screen.width - BUTTON_SIZE.x) / 2, (Screen.height - BUTTON_SIZE.y) / 2, BUTTON_SIZE.x, BUTTON_SIZE.y); textPosition = new Rect( (Screen.width - TEXT_SIZE.x) / 2, buttonPosition.y + 2 * BUTTON_SIZE.y, TEXT_SIZE.x, TEXT_SIZE.y); #if UNITY_ANDROID inApp = GetComponent<GoogleInAppPlugin>(); GoogleInAppPlugin.BindComplete += HandleBindComplete; inApp.Bind(); #endif } void OnGUI () { GUI.TextArea( textPosition, "Item " + INAPP_ITEM + (purchased ? " purchased." : " not purchased.")); if (GUI.Button(buttonPosition, "Purchase")) { #if UNITY_ANDROID inApp.PurchaseItem(INAPP_ITEM); #endif } } void OnApplicationFocus(bool focused) { if (focused) { purchased = inApp.IsItemPurchased(INAPP_ITEM); } } /// <summary> /// Handles the bind complete event from GoogleInAppPlugin. /// </summary> public void HandleBindComplete() { purchased = inApp.IsItemPurchased(INAPP_ITEM); } }
mit
C#
c3f1962d4b1244813bb5a9b798bf25fcb12dcbcc
Add overloads to register custom service types.
wasabii/Cogito.ServiceFabric
Cogito.ServiceFabric.AspNetCore.Kestrel.Autofac/KestrelContainerBuilderExtensions.cs
Cogito.ServiceFabric.AspNetCore.Kestrel.Autofac/KestrelContainerBuilderExtensions.cs
using Autofac; using Cogito.ServiceFabric.AspNetCore.Autofac; namespace Cogito.ServiceFabric.AspNetCore.Kestrel.Autofac { public static class KestrelContainerBuilderExtensions { /// <summary> /// Registers the given <typeparamref name="TStartup"/> class to start in Kestrel stateful service. /// </summary> /// <typeparam name="TStartup"></typeparam> /// <param name="builder"></param> /// <param name="serviceTypeName"></param> /// <param name="endpointName"></param> public static void RegisterStatefulKestrelWebService<TService, TStartup>(this ContainerBuilder builder, string serviceTypeName, string endpointName = null) where TService : StatefulKestrelWebService<TStartup> where TStartup : class { builder.RegisterStatefulWebService<TService>(serviceTypeName, endpointName); } /// <summary> /// Registers the given <typeparamref name="TStartup"/> class to start in a Kestrel stateless service. /// </summary> /// <typeparam name="TStartup"></typeparam> /// <param name="builder"></param> /// <param name="serviceTypeName"></param> /// <param name="endpointName"></param> public static void RegisterStatelessKestrelWebService<TService, TStartup>(this ContainerBuilder builder, string serviceTypeName, string endpointName = null) where TService : StatelessKestrelWebService<TStartup> where TStartup : class { builder.RegisterStatelessWebService<TService>(serviceTypeName, endpointName); } /// <summary> /// Registers the given <typeparamref name="TStartup"/> class to start in Kestrel stateful service. /// </summary> /// <typeparam name="TStartup"></typeparam> /// <param name="builder"></param> /// <param name="serviceTypeName"></param> /// <param name="endpointName"></param> public static void RegisterStatefulKestrelWebService<TStartup>(this ContainerBuilder builder, string serviceTypeName, string endpointName = null) where TStartup : class { RegisterStatefulKestrelWebService<StatefulKestrelWebService<TStartup>>(builder, serviceTypeName, endpointName); } /// <summary> /// Registers the given <typeparamref name="TStartup"/> class to start in a Kestrel stateless service. /// </summary> /// <typeparam name="TStartup"></typeparam> /// <param name="builder"></param> /// <param name="serviceTypeName"></param> /// <param name="endpointName"></param> public static void RegisterStatelessKestrelWebService<TStartup>(this ContainerBuilder builder, string serviceTypeName, string endpointName = null) where TStartup : class { RegisterStatelessKestrelWebService<StatelessKestrelWebService<TStartup>>(builder, serviceTypeName, endpointName); } } }
using Autofac; using Cogito.ServiceFabric.AspNetCore.Autofac; namespace Cogito.ServiceFabric.AspNetCore.Kestrel.Autofac { public static class KestrelContainerBuilderExtensions { /// <summary> /// Registers the given <typeparamref name="TStartup"/> class to start in Kestrel stateful service. /// </summary> /// <typeparam name="TStartup"></typeparam> /// <param name="builder"></param> /// <param name="serviceTypeName"></param> /// <param name="endpointName"></param> public static void RegisterStatefulKestrelWebService<TStartup>(this ContainerBuilder builder, string serviceTypeName, string endpointName = null) where TStartup : class { builder.RegisterStatefulWebService<StatefulKestrelWebService<TStartup>>(serviceTypeName, endpointName); } /// <summary> /// Registers the given <typeparamref name="TStartup"/> class to start in a Kestrel stateless service. /// </summary> /// <typeparam name="TStartup"></typeparam> /// <param name="builder"></param> /// <param name="serviceTypeName"></param> /// <param name="endpointName"></param> public static void RegisterStatelessKestrelWebService<TStartup>(this ContainerBuilder builder, string serviceTypeName, string endpointName = null) where TStartup : class { builder.RegisterStatelessWebService<StatelessKestrelWebService<TStartup>>(serviceTypeName, endpointName); } } }
mit
C#
6e580afe0e0cf234b58fd43abc0c8199644904a6
Rename requiredTimeSlots to availableTimeSlots
victoria92/university-program-generator,victoria92/university-program-generator
UniProgramGen/Data/Requirements.cs
UniProgramGen/Data/Requirements.cs
using System.Collections.Generic; namespace UniProgramGen.Data { public class Requirements { public readonly double weight; public readonly List<TimeSlot> availableTimeSlots; public readonly List<Room> requiredRooms; public Requirements(double weight, List<TimeSlot> availableTimeSlots, List<Room> requiredRooms) { this.weight = weight; this.availableTimeSlots = availableTimeSlots; this.requiredRooms = requiredRooms; } } }
using System.Collections.Generic; namespace UniProgramGen.Data { public class Requirements { public readonly double weight; public readonly List<TimeSlot> requiredTimeSlots; public readonly List<Room> requiredRooms; public Requirements(double weight, List<TimeSlot> requiredTimeSlots, List<Room> requiredRooms) { this.weight = weight; this.requiredTimeSlots = requiredTimeSlots; this.requiredRooms = requiredRooms; } } }
bsd-2-clause
C#
177e8408dfe6293ae644ecbbdbba71ed7148b35f
Apply new css class for displaying long email addresses and other data in panel
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Views/EmployerTeam/V2/SingleProvider.cshtml
src/SFA.DAS.EmployerAccounts.Web/Views/EmployerTeam/V2/SingleProvider.cshtml
 @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <h3 class="das-panel__heading">@Model.AccountViewModel.Providers.First().Name</h3> <dl class="das-definition-list das-definition-list--inline das-definition-list--muted govuk-!-font-size-16"> <dt class="das-definition-list__title">UK Provider Reference Number</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Ukprn</dd> </dl> <p> @if (@Model.AccountViewModel.Providers.First().Street != null) { @(Model.AccountViewModel.Providers.First().Street)@:, <br> } @(Model.AccountViewModel.Providers.First().Town)<text>, </text>@(Model.AccountViewModel.Providers.First().Postcode) </p> <dl class="das-definition-list das-definition-list--table-narrow"> <dt class="das-definition-list__title">Tel</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Phone</dd> <dt class="das-definition-list__title">Email</dt> <dd class="das-definition-list__definition"><span class="das-breakable">@Model.AccountViewModel.Providers.First().Email</span></dd> </dl> <p><a href="@Url.ProviderRelationshipsAction("providers")" class="govuk-link govuk-link--no-visited-state">View permissions</a> </p>
 @model SFA.DAS.EmployerAccounts.Web.ViewModels.AccountDashboardViewModel <h3 class="das-panel__heading">@Model.AccountViewModel.Providers.First().Name</h3> <dl class="das-definition-list das-definition-list--inline das-definition-list--muted govuk-!-font-size-16"> <dt class="das-definition-list__title">UK Provider Reference Number</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Ukprn</dd> </dl> <p> @if (@Model.AccountViewModel.Providers.First().Street != null) { @(Model.AccountViewModel.Providers.First().Street)@:, <br> } @(Model.AccountViewModel.Providers.First().Town)<text>, </text>@(Model.AccountViewModel.Providers.First().Postcode) </p> <dl class="das-definition-list das-definition-list--inline"> <dt class="das-definition-list__title">Tel</dt> <dd class="das-definition-list__definition">@Model.AccountViewModel.Providers.First().Phone</dd> <dt class="das-definition-list__title">Email</dt> <dd class="das-definition-list__definition"><span class="das-breakable">@Model.AccountViewModel.Providers.First().Email</span></dd> </dl> <p><a href="@Url.ProviderRelationshipsAction("providers")" class="govuk-link govuk-link--no-visited-state">View permissions</a> </p>
mit
C#
f94728547617160837baedc43b7786a457b3e45f
Remove 2 suffix step 1 (dotnet/corefx#35904)
wtgodbe/coreclr,cshung/coreclr,cshung/coreclr,cshung/coreclr,krk/coreclr,poizan42/coreclr,krk/coreclr,poizan42/coreclr,poizan42/coreclr,wtgodbe/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,poizan42/coreclr,krk/coreclr,wtgodbe/coreclr,cshung/coreclr,cshung/coreclr
src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Stat.cs
src/System.Private.CoreLib/shared/Interop/Unix/System.Native/Interop.Stat.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.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Sys { // Even though csc will by default use a sequential layout, a CS0649 warning as error // is produced for un-assigned fields when no StructLayout is specified. // // Explicitly saying Sequential disables that warning/error for consumers which only // use Stat in debug builds. [StructLayout(LayoutKind.Sequential)] internal struct FileStatus { internal FileStatusFlags Flags; internal int Mode; internal uint Uid; internal uint Gid; internal long Size; internal long ATime; internal long ATimeNsec; internal long MTime; internal long MTimeNsec; internal long CTime; internal long CTimeNsec; internal long BirthTime; internal long BirthTimeNsec; internal long Dev; internal long Ino; internal uint UserFlags; } internal static class FileTypes { internal const int S_IFMT = 0xF000; internal const int S_IFIFO = 0x1000; internal const int S_IFCHR = 0x2000; internal const int S_IFDIR = 0x4000; internal const int S_IFREG = 0x8000; internal const int S_IFLNK = 0xA000; internal const int S_IFSOCK = 0xC000; } [Flags] internal enum FileStatusFlags { None = 0, HasBirthTime = 1, } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)] internal static extern int FStat(SafeFileHandle fd, out FileStatus output); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)] internal static extern int Stat(string path, out FileStatus output); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", SetLastError = true)] internal static extern int LStat(string path, out FileStatus output); } }
// 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.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Sys { // Even though csc will by default use a sequential layout, a CS0649 warning as error // is produced for un-assigned fields when no StructLayout is specified. // // Explicitly saying Sequential disables that warning/error for consumers which only // use Stat in debug builds. [StructLayout(LayoutKind.Sequential)] internal struct FileStatus { internal FileStatusFlags Flags; internal int Mode; internal uint Uid; internal uint Gid; internal long Size; internal long ATime; internal long ATimeNsec; internal long MTime; internal long MTimeNsec; internal long CTime; internal long CTimeNsec; internal long BirthTime; internal long BirthTimeNsec; internal long Dev; internal long Ino; internal uint UserFlags; } internal static class FileTypes { internal const int S_IFMT = 0xF000; internal const int S_IFIFO = 0x1000; internal const int S_IFCHR = 0x2000; internal const int S_IFDIR = 0x4000; internal const int S_IFREG = 0x8000; internal const int S_IFLNK = 0xA000; internal const int S_IFSOCK = 0xC000; } [Flags] internal enum FileStatusFlags { None = 0, HasBirthTime = 1, } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat2", SetLastError = true)] internal static extern int FStat(SafeFileHandle fd, out FileStatus output); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat2", SetLastError = true)] internal static extern int Stat(string path, out FileStatus output); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat2", SetLastError = true)] internal static extern int LStat(string path, out FileStatus output); } }
mit
C#
26be28b4ab9ab321db31774956612777ce392b55
Remove comments
takenet/messaginghub-client-csharp
src/Takenet.MessagingHub.Client/LimeProtocol/OnDemandClientChannelFactory.cs
src/Takenet.MessagingHub.Client/LimeProtocol/OnDemandClientChannelFactory.cs
using System; using Lime.Protocol.Client; namespace Takenet.MessagingHub.Client.LimeProtocol { internal class OnDemandClientChannelFactory : IOnDemandClientChannelFactory { public IEstablishedClientChannelBuilder ChannelBuilder { get; set; } public OnDemandClientChannelFactory(IEstablishedClientChannelBuilder channelBuilder) { if (channelBuilder == null) throw new ArgumentNullException(nameof(channelBuilder)); ChannelBuilder = channelBuilder; } public IOnDemandClientChannel Create() { return new MultiplexerClientChannel(ChannelBuilder as EstablishedClientChannelBuilder); } } }
using System; using Lime.Protocol.Client; namespace Takenet.MessagingHub.Client.LimeProtocol { internal class OnDemandClientChannelFactory : IOnDemandClientChannelFactory { public IEstablishedClientChannelBuilder ChannelBuilder { get; set; } public OnDemandClientChannelFactory(IEstablishedClientChannelBuilder channelBuilder) { if (channelBuilder == null) throw new ArgumentNullException(nameof(channelBuilder)); ChannelBuilder = channelBuilder; } public IOnDemandClientChannel Create() { //return new OnDemandClientChannel(ChannelBuilder); return new MultiplexerClientChannel(ChannelBuilder as EstablishedClientChannelBuilder); } } }
apache-2.0
C#
50b77663f8b734f39cd4b33ef235bf0874ffcbed
Change string formatting
MrRoundRobin/telegram.bot,TelegramBots/telegram.bot
test/Telegram.Bot.Tests.Unit/Serialization/ReplyMarkupSerializationTests.cs
test/Telegram.Bot.Tests.Unit/Serialization/ReplyMarkupSerializationTests.cs
using Newtonsoft.Json; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class ReplyMarkupSerializationTests { [Theory(DisplayName = "Should serialize request poll keyboard button")] [InlineData(null)] [InlineData("regular")] [InlineData("quiz")] public void Should_Serialize_Request_Poll_Keyboard_Button(string type) { IReplyMarkup replyMarkup = new ReplyKeyboardMarkup( KeyboardButton.WithRequestPoll("Create a poll", type) ); string serializedReplyMarkup = JsonConvert.SerializeObject(replyMarkup); string formattedType = string.IsNullOrEmpty(type) ? "{}" : string.Format(@"{{""type"":""{0}""}}", type); string expectedString = string.Format(@"""request_poll"":{0}", formattedType); Assert.Contains(expectedString, serializedReplyMarkup); } } }
using Newtonsoft.Json; using Telegram.Bot.Types.ReplyMarkups; using Xunit; namespace Telegram.Bot.Tests.Unit.Serialization { public class ReplyMarkupSerializationTests { [Theory(DisplayName = "Should serialize request poll keyboard button")] [InlineData(null)] [InlineData("regular")] [InlineData("quiz")] public void Should_Serialize_Request_Poll_Keyboard_Button(string type) { IReplyMarkup replyMarkup = new ReplyKeyboardMarkup( KeyboardButton.WithRequestPoll("Create a poll", type) ); string serializedReplyMarkup = JsonConvert.SerializeObject(replyMarkup); string expectedType = string.IsNullOrEmpty(type) ? "{}" : string.Format(@"{{""type"":""{0}""}}", type); Assert.Contains(@$"""request_poll"":{expectedType}", serializedReplyMarkup); } } }
mit
C#
fa7cfdfff4bd146aaf6648d5d40aadaadc1e0ca1
Remove unused parameter
smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework
osu.Framework.Templates/templates/template-flappy/FlappyDon.Game/FlappyDonGameBase.cs
osu.Framework.Templates/templates/template-flappy/FlappyDon.Game/FlappyDonGameBase.cs
using FlappyDon.Resources; using osu.Framework.Allocation; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osuTK.Graphics.ES30; namespace FlappyDon.Game { /// <summary> /// Set up the relevant resource stores and texture settings. /// </summary> public abstract class FlappyDonGameBase : osu.Framework.Game { private TextureStore textures; private DependencyContainer dependencies; [BackgroundDependencyLoader] private void load() { // Load the assets from our Resources project Resources.AddStore(new DllResourceStore(FlappyDonResources.ResourceAssembly)); // To preserve the 8-bit aesthetic, disable texture filtering // so they won't become blurry when upscaled textures = new TextureStore(Textures, filteringMode: All.Nearest); dependencies.Cache(textures); } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); } }
using FlappyDon.Resources; using osu.Framework.Allocation; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osuTK.Graphics.ES30; namespace FlappyDon.Game { /// <summary> /// Set up the relevant resource stores and texture settings. /// </summary> public abstract class FlappyDonGameBase : osu.Framework.Game { private TextureStore textures; private DependencyContainer dependencies; [BackgroundDependencyLoader] private void load(GameHost host) { // Load the assets from our Resources project Resources.AddStore(new DllResourceStore(FlappyDonResources.ResourceAssembly)); // To preserve the 8-bit aesthetic, disable texture filtering // so they won't become blurry when upscaled textures = new TextureStore(Textures, filteringMode: All.Nearest); dependencies.Cache(textures); } protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); } }
mit
C#
1ab987f6d23891db688d0b77735d49ea15e34835
Fix ConnectionInfo dialog for users that do not have a password
fknx/linqpad-postgresql-driver
DynamicLinqPadPostgreSqlDriver.Shared/Extensions/ConnectionInfoExtensions.cs
DynamicLinqPadPostgreSqlDriver.Shared/Extensions/ConnectionInfoExtensions.cs
using LINQPad.Extensibility.DataContext; using System; using System.Text; namespace DynamicLinqPadPostgreSqlDriver.Shared.Extensions { public static class ConnectionInfoExtensions { public static string GetPostgreSqlConnectionString(this IConnectionInfo cxInfo) { if (cxInfo == null) throw new ArgumentNullException(nameof(cxInfo)); if (!string.IsNullOrWhiteSpace(cxInfo.DatabaseInfo.CustomCxString)) return cxInfo.DatabaseInfo.CustomCxString; return BuildConnectionString(cxInfo.DatabaseInfo.Server, cxInfo.DatabaseInfo.Database, cxInfo.DatabaseInfo.UserName, cxInfo.DatabaseInfo.Password); } internal static string BuildConnectionString(string serverWithPort, string database, string userName, string password) { if (string.IsNullOrWhiteSpace(serverWithPort)) throw new ArgumentException("The argument may not be null or empty.", nameof(serverWithPort)); if (string.IsNullOrWhiteSpace(database)) throw new ArgumentException("The argument may not be null or empty.", nameof(database)); var server = ""; var port = ""; if (serverWithPort.Contains(":")) { var parts = serverWithPort.Split(':'); server = parts[0]; port = parts[1]; } else { server = serverWithPort; } var sb = new StringBuilder(); sb.AppendFormat("Server={0};", server); if (!string.IsNullOrWhiteSpace(port)) { sb.AppendFormat("Port={0};", port); } sb.AppendFormat("Database={0};", database); if (!string.IsNullOrWhiteSpace(userName)) { sb.AppendFormat("User Id={0};", userName); if (!string.IsNullOrWhiteSpace(password)) { sb.AppendFormat("Password={0};", password); } } else { sb.Append("Integrated Security=true;"); } return sb.ToString(); } } }
using LINQPad.Extensibility.DataContext; using System; using System.Text; namespace DynamicLinqPadPostgreSqlDriver.Shared.Extensions { public static class ConnectionInfoExtensions { public static string GetPostgreSqlConnectionString(this IConnectionInfo cxInfo) { if (cxInfo == null) throw new ArgumentNullException(nameof(cxInfo)); if (!string.IsNullOrWhiteSpace(cxInfo.DatabaseInfo.CustomCxString)) return cxInfo.DatabaseInfo.CustomCxString; return BuildConnectionString(cxInfo.DatabaseInfo.Server, cxInfo.DatabaseInfo.Database, cxInfo.DatabaseInfo.UserName, cxInfo.DatabaseInfo.Password); } internal static string BuildConnectionString(string serverWithPort, string database, string userName, string password) { if (string.IsNullOrWhiteSpace(serverWithPort)) throw new ArgumentException("The argument may not be null or empty.", nameof(serverWithPort)); if (string.IsNullOrWhiteSpace(database)) throw new ArgumentException("The argument may not be null or empty.", nameof(database)); var server = ""; var port = ""; if (serverWithPort.Contains(":")) { var parts = serverWithPort.Split(':'); server = parts[0]; port = parts[1]; } else { server = serverWithPort; } var sb = new StringBuilder(); sb.AppendFormat("Server={0};", server); if (!string.IsNullOrWhiteSpace(port)) { sb.AppendFormat("Port={0};", port); } sb.AppendFormat("Database={0};", database); if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(password)) { sb.AppendFormat("User Id={0};", userName); sb.AppendFormat("Password={0};", password); } else { sb.Append("Integrated Security=true;"); } return sb.ToString(); } } }
mit
C#
f0b700ae1ffeb394316ae5d0624ea3967ddea52d
increment patch 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.16.1")] [assembly: AssemblyInformationalVersion("0.16.1")] /* * Version 0.16.1 * * - [FIX, BREAKING-CHANGE] Introduces the new `ITestFixtureFactory` insterface, * which is replaced `Func<MethodInfo, ITestFixture>`. * * - [FIX] Lets IndirectReferenceAssertion verify whether a base type of a * certain type exposes any indirect reference. */
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.16.0")] [assembly: AssemblyInformationalVersion("0.16.0")] /* * Version 0.16.1 * * - [FIX, BREAKING-CHANGE] Introduces the new `ITestFixtureFactory` insterface, * which is replaced `Func<MethodInfo, ITestFixture>`. * * - [FIX] Lets IndirectReferenceAssertion verify whether a base type of a * certain type exposes any indirect reference. */
mit
C#
dc49af2f2a77f5874208ac8f85fd2f16f49aa533
add using and use service instead of dbcontext
remcoros/InspectR,remcoros/InspectR
InspectR/Controllers/RequestLogger/InspectRHandlerHttpHandler.cs
InspectR/Controllers/RequestLogger/InspectRHandlerHttpHandler.cs
namespace InspectR.Controllers.RequestLogger { using System.Web; using System.Web.Routing; using InspectR.Core; using InspectR.Core.RequestLogger; using InspectR.Data; public class InspectRHandlerHttpHandler : IHttpHandler { private readonly RequestContext _requestContext; public InspectRHandlerHttpHandler(RequestContext requestContext) { _requestContext = requestContext; } public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { var requestCache = new RequestCache(); var requestLogger = new RequestLogger(requestCache, new DefaultRequestCollector()); InspectorInfo inspectorInfo; using (var dbContext = new InspectRContext()) { var service = new InspectRService(dbContext); var id = _requestContext.RouteData.Values["id"] as string; inspectorInfo = service.GetInspectorInfoByKey(id); // TODO: check private // .. } if (inspectorInfo == null) { throw new HttpException(404, "404 - Inspector Not found"); } requestLogger.LogRequest(inspectorInfo); // TODO: random response? :) context.Response.Write("ok"); } } }
using System.Web; using System.Web.Routing; using InspectR.Core; using InspectR.Core.RequestLogger; using InspectR.Data; namespace InspectR.Controllers.RequestLogger { public class InspectRHandlerHttpHandler : IHttpHandler { private readonly RequestContext _requestContext; public InspectRHandlerHttpHandler(RequestContext requestContext) { _requestContext = requestContext; } public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { var requestCache = new RequestCache(); var requestLogger = new Core.RequestLogger.RequestLogger(requestCache, new DefaultRequestCollector()); var dbContext = new InspectRContext(); var id = _requestContext.RouteData.Values["id"] as string; InspectorInfo inspectorInfo = dbContext.GetInspectorInfoByKey(id); // TODO: check private // .. dbContext.Dispose(); if (inspectorInfo == null) throw new HttpException(404, "404 - Inspector Not found"); requestLogger.LogRequest(inspectorInfo); // TODO: random response? :) context.Response.Write("ok"); } } }
mit
C#
9918490c45f9a3a96895a46d7f75a7e0fdea338f
Fix warning
rsdn/CodeJam,NN---/CodeJam
Main/src/Targeting/FW40/ValueTuple/TupleElementNamesAttribute.cs
Main/src/Targeting/FW40/ValueTuple/TupleElementNamesAttribute.cs
#if FW40 // BASEDON: https://github.com/dotnet/corefx/blob/master/src/System.ValueTuple/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.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; namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref="System.ValueTuple"/> on a member is meant to be treated as a tuple with element names. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event )] public sealed class TupleElementNamesAttribute : Attribute { private readonly string[] _transformNames; /// <summary> /// Initializes a new instance of the <see /// cref="TupleElementNamesAttribute"/> class. /// </summary> /// <param name="transformNames"> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="System.ValueType"/> occurrences are /// meant to carry element names. /// </param> /// <remarks> /// This constructor is meant to be used on types that contain an /// instantiation of <see cref="System.ValueType"/> that contains /// element names. For instance, if <c>C</c> is a generic type with /// two type parameters, then a use of the constructed type <c>C{<see /// cref="System.ValueTuple{T1, T2}"/>, <see /// cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to /// treat the first type argument as a tuple with element names and the /// second as a tuple without element names. In which case, the /// appropriate attribute specification should use a /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null, /// null }</c>. /// </remarks> public TupleElementNamesAttribute(string[] transformNames) { if (transformNames == null) { throw new ArgumentNullException(nameof(transformNames)); } _transformNames = transformNames; } /// <summary> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="System.ValueTuple"/> elements are /// meant to carry element names. /// </summary> public IList<string> TransformNames => _transformNames; } } #endif
#if FW40 // BASEDON: https://github.com/dotnet/corefx/blob/master/src/System.ValueTuple/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.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; namespace System.Runtime.CompilerServices { /// <summary> /// Indicates that the use of <see cref="System.ValueTuple"/> on a member is meant to be treated as a tuple with element names. /// </summary> [CLSCompliant(false)] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event )] public sealed class TupleElementNamesAttribute : Attribute { private readonly string[] _transformNames; /// <summary> /// Initializes a new instance of the <see /// cref="TupleElementNamesAttribute"/> class. /// </summary> /// <param name="transformNames"> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="System.ValueType"/> occurrences are /// meant to carry element names. /// </param> /// <remarks> /// This constructor is meant to be used on types that contain an /// instantiation of <see cref="System.ValueType"/> that contains /// element names. For instance, if <c>C</c> is a generic type with /// two type parameters, then a use of the constructed type <c>C{<see /// cref="System.ValueTuple{T1, T2}"/>, <see /// cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to /// treat the first type argument as a tuple with element names and the /// second as a tuple without element names. In which case, the /// appropriate attribute specification should use a /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null, /// null }</c>. /// </remarks> public TupleElementNamesAttribute(string[] transformNames) { if (transformNames == null) { throw new ArgumentNullException(nameof(transformNames)); } _transformNames = transformNames; } /// <summary> /// Specifies, in a pre-order depth-first traversal of a type's /// construction, which <see cref="System.ValueTuple"/> elements are /// meant to carry element names. /// </summary> public IList<string> TransformNames => _transformNames; } } #endif
mit
C#
fd357f043de1fe180a6bfbe557cae8b8779ffc8d
Fix the problem that `Hint` information cannot be displayed (#10584)
xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.ContentFields/Views/TextField-Monaco.Edit.cshtml
src/OrchardCore.Modules/OrchardCore.ContentFields/Views/TextField-Monaco.Edit.cshtml
@model OrchardCore.ContentFields.ViewModels.EditTextFieldViewModel @{ var settings = Model.PartFieldDefinition.GetSettings<TextFieldSettings>(); var monacoSettings = Model.PartFieldDefinition.GetSettings<TextFieldMonacoEditorSettings>(); var culture = await Orchard.GetContentCultureAsync(Model.Field.ContentItem); } <div class="form-group"> <label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label> <div id="@Html.IdFor(x => x.Text)_editor" asp-for="Text" style="min-height: 400px;" class="form-control" dir="@culture.GetLanguageDirection()"></div> <textarea asp-for="Text" hidden>@Html.Raw(Model.Text)</textarea> @if (!String.IsNullOrEmpty(settings.Hint)) { <span class="hint">@settings.Hint</span> } </div> <script asp-name="monaco" depends-on="admin" at="Foot"></script> <script at="Foot" depends-on="monaco"> $(document).ready(function () { require(['vs/editor/editor.main'], function () { var settings = @Html.Raw(monacoSettings.Options); if (settings.automaticLayout == undefined) { settings.automaticLayout = true; } var html = document.getElementsByTagName("html")[0]; const mutationObserver = new MutationObserver(setTheme); mutationObserver.observe(html, { attributes: true }); function setTheme() { var theme = html.dataset.theme; if (theme === "darkmode") { monaco.editor.setTheme('vs-dark') } else { monaco.editor.setTheme('vs') } } setTheme(); var editor = monaco.editor.create(document.getElementById('@Html.IdFor(x => x.Text)_editor'), settings); var textArea = document.getElementById('@Html.IdFor(x => x.Text)'); editor.getModel().setValue(textArea.value); window.addEventListener("submit", function () { textArea.value = editor.getValue(); }); }); }); </script>
@model OrchardCore.ContentFields.ViewModels.EditTextFieldViewModel @{ var settings = Model.PartFieldDefinition.GetSettings<HtmlFieldSettings>(); var monacoSettings = Model.PartFieldDefinition.GetSettings<TextFieldMonacoEditorSettings>(); var culture = await Orchard.GetContentCultureAsync(Model.Field.ContentItem); } <div class="form-group"> <label asp-for="Text">@Model.PartFieldDefinition.DisplayName()</label> <div id="@Html.IdFor(x => x.Text)_editor" asp-for="Text" style="min-height: 400px;" class="form-control" dir="@culture.GetLanguageDirection()"></div> <textarea asp-for="Text" hidden>@Html.Raw(Model.Text)</textarea> @if (!String.IsNullOrEmpty(settings.Hint)) { <span class="hint">@settings.Hint</span> } </div> <script asp-name="monaco" depends-on="admin" at="Foot"></script> <script at="Foot" depends-on="monaco"> $(document).ready(function () { require(['vs/editor/editor.main'], function () { var settings = @Html.Raw(monacoSettings.Options); if (settings.automaticLayout == undefined) { settings.automaticLayout = true; } var html = document.getElementsByTagName("html")[0]; const mutationObserver = new MutationObserver(setTheme); mutationObserver.observe(html, { attributes: true }); function setTheme() { var theme = html.dataset.theme; if (theme === "darkmode") { monaco.editor.setTheme('vs-dark') } else { monaco.editor.setTheme('vs') } } setTheme(); var editor = monaco.editor.create(document.getElementById('@Html.IdFor(x => x.Text)_editor'), settings); var textArea = document.getElementById('@Html.IdFor(x => x.Text)'); editor.getModel().setValue(textArea.value); window.addEventListener("submit", function () { textArea.value = editor.getValue(); }); }); }); </script>
bsd-3-clause
C#
fc8cd02b168566dafd284f8417e2cb9b3b68f478
support reading from authorization header
0xFireball/PenguinUpload,0xFireball/PenguinUpload,0xFireball/PenguinUpload,0xFireball/PenguinUpload
src/PenguinUpload/PenguinUploadBootstrapper.cs
src/PenguinUpload/PenguinUploadBootstrapper.cs
using Nancy; using Nancy.Authentication.Stateless; using Nancy.Bootstrapper; using Nancy.TinyIoc; using PenguinUpload.Services.Authentication; namespace PenguinUpload { public class PenguinUploadBootstrapper : DefaultNancyBootstrapper { public IPenguinUploadContext ServerContext { get; set; } public PenguinUploadBootstrapper(IPenguinUploadContext serverContext) { ServerContext = serverContext; } protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { // Check for the API key string accessToken = null; if (ctx.Request.Query.apikey.HasValue) { accessToken = ctx.Request.Query.apikey; } else if (ctx.Request.Form["apikey"].HasValue) { accessToken = ctx.Request.Form["apikey"]; } else { var authHeader = ctx.Request.Headers.Authorization; if (!string.IsNullOrWhiteSpace(authHeader)) { accessToken = authHeader; } } // Authenticate the request var authService = new ApiClientAuthenticationService(ServerContext); return accessToken == null ? null : authService.ResolveClientIdentity(accessToken); })); } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register<IPenguinUploadContext>(ServerContext); } } }
using Nancy; using Nancy.Authentication.Stateless; using Nancy.Bootstrapper; using Nancy.TinyIoc; using PenguinUpload.Services.Authentication; namespace PenguinUpload { public class PenguinUploadBootstrapper : DefaultNancyBootstrapper { public IPenguinUploadContext ServerContext { get; set; } public PenguinUploadBootstrapper(IPenguinUploadContext serverContext) { ServerContext = serverContext; } protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); StatelessAuthentication.Enable(pipelines, new StatelessAuthenticationConfiguration(ctx => { // Check for the API key string accessToken = null; if (ctx.Request.Query.apikey.HasValue) { accessToken = ctx.Request.Query.apikey; } else if (ctx.Request.Form["apikey"].HasValue) { accessToken = ctx.Request.Form["apikey"]; } // Authenticate the request var authService = new ApiClientAuthenticationService(ServerContext); return accessToken == null ? null : authService.ResolveClientIdentity(accessToken); })); } protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register<IPenguinUploadContext>(ServerContext); } } }
apache-2.0
C#
56a5dcea0ef791ffcb7c6aa1fe088cfad590fd90
Bump assembly version of Stratis.Bitcoin to 3.0.5 (#3586)
fassadlr/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode
src/Stratis.Bitcoin/Properties/AssemblyInfo.cs
src/Stratis.Bitcoin/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("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // 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("3.0.5.0")] [assembly: AssemblyFileVersion("3.0.5.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // 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("3.0.4.0")] [assembly: AssemblyFileVersion("3.0.4.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
mit
C#
40cb77588dacf8177ef3fc08b5d70d37f15639ff
add read-only property for default culture
uzimmermann/wpf-localization,uzimmermann/wpf-localization
src/WpfLocalization.Framework/ILocalizeAnApplication.cs
src/WpfLocalization.Framework/ILocalizeAnApplication.cs
using System; using System.Globalization; namespace WpfLocalization.Framework { /// <summary> /// Provides the features required to localize an application. /// </summary> public interface ILocalizeAnApplication { /// <summary> /// Raised when <see cref="CurrentCulture"/> has a new value. /// </summary> event EventHandler<CultureChangedEventArgs> CultureChanged; /// <summary> /// Gets or sets the current culture. /// </summary> CultureInfo CurrentCulture { get; set; } /// <summary> /// Gets the default culture. /// </summary> CultureInfo DefaultCulture { get; } /// <summary> /// Gets the localized texts. /// </summary> IHandleLocalizedTexts LocalizedTexts { get; } /// <summary> /// Gets the count of registered objects supporting localization. /// </summary> int CountOfRegisteredLocalizationSupporters { get; } /// <summary> /// Registers the given object for localization. /// </summary> /// <param name="localizationSupporter">The object which to register for localization.</param> void RegisterForLocalization(ISupportLocalization localizationSupporter); /// <summary> /// Deregisters the given object from localization. /// </summary> /// <param name="localizationSupporter">The object which to deregister from localization.</param> void DeregisterFromLocalization(ISupportLocalization localizationSupporter); } }
using System; using System.Globalization; namespace WpfLocalization.Framework { /// <summary> /// Provides the features required to localize an application. /// </summary> public interface ILocalizeAnApplication { /// <summary> /// Raised when <see cref="CurrentCulture"/> has a new value. /// </summary> event EventHandler<CultureChangedEventArgs> CultureChanged; /// <summary> /// Gets or sets the current culture. /// </summary> CultureInfo CurrentCulture { get; set; } /// <summary> /// Gets the localized texts. /// </summary> IHandleLocalizedTexts LocalizedTexts { get; } /// <summary> /// Gets the count of registered objects supporting localization. /// </summary> int CountOfRegisteredLocalizationSupporters { get; } /// <summary> /// Registers the given object for localization. /// </summary> /// <param name="localizationSupporter">The object which to register for localization.</param> void RegisterForLocalization(ISupportLocalization localizationSupporter); /// <summary> /// Deregisters the given object from localization. /// </summary> /// <param name="localizationSupporter">The object which to deregister from localization.</param> void DeregisterFromLocalization(ISupportLocalization localizationSupporter); } }
unlicense
C#
6ddf3a5c5e12bbf37609ffb332e062db63d9013e
Update ILineDisassembler.cs
informedcitizenry/6502.Net
6502.Net/ILineDisassembler.cs
6502.Net/ILineDisassembler.cs
//----------------------------------------------------------------------------- // Copyright (c) 2017 informedcitizenry <informedcitizenry@gmail.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; namespace Asm6502.Net { /// <summary> /// Represents an interface for a line disassembler. /// </summary> public interface ILineDisassembler { /// <summary> /// Disassemble a line of 6502 source. /// </summary> /// <param name="line">The SourceLine.</param> /// <returns>A string representation of the source.</returns> string DisassembleLine(SourceLine line); /// <summary> /// Disassemble a line of 6502 source to a supplied /// System.Text.StringBuilder. /// </summary> /// <param name="line">The SourceLine to disassemble.</param> /// <param name="sb">A System.Text.StringBuilder to output disassembly.</param> void DisassembleLine(SourceLine line, StringBuilder sb); /// <summary> /// Gets a flag indicating if printing is on. /// </summary> bool PrintingOn { get; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2017 informedcitizenry <informedcitizenry@gmail.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.Collections.Generic; using System.Text; namespace Asm6502.Net { /// <summary> /// Represents an interface for a line disassembler. /// </summary> public interface ILineDisassembler { /// <summary> /// Disassemble a line of 6502 source. /// </summary> /// <param name="line">The SourceLine.</param> /// <returns>A string representation of the source.</returns> string DisassembleLine(SourceLine line); /// <summary> /// Disassemble a line of 6502 source to a supplied /// System.Text.StringBuilder. /// </summary> /// <param name="line">The SourceLine to disassemble.</param> /// <param name="sb">A System.Text.StringBuilder to output disassembly.</param> void DisassembleLine(SourceLine line, StringBuilder sb); /// <summary> /// Gets a flag indicating if printing is on. /// </summary> bool PrintingOn { get; } } }
mit
C#
507e651ca5520b42adcabdbaad46da3c5c45d862
Disable test debug logging in appveyor.
mchaloupka/DotNetR2RMLStore,mchaloupka/EVI
src/Slp.Evi.Storage/Slp.Evi.Test.System/SPARQL/SPARQL_TestSuite/Db/MSSQLDb.cs
src/Slp.Evi.Storage/Slp.Evi.Test.System/SPARQL/SPARQL_TestSuite/Db/MSSQLDb.cs
using System; using System.Collections.Generic; using System.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.VisualStudio.TestTools.UnitTesting; using Slp.Evi.Storage; using Slp.Evi.Storage.Bootstrap; using Slp.Evi.Storage.Database; using Slp.Evi.Storage.Database.Vendor.MsSql; namespace Slp.Evi.Test.System.SPARQL.SPARQL_TestSuite.Db { [TestClass] public class MSSQLDb : TestSuite { private static Dictionary<string, EviQueryableStorage> _storages; [ClassInitialize] public static void TestSuiteInitialization(TestContext context) { _storages = new Dictionary<string, EviQueryableStorage>(); foreach (var dataset in StorageNames) { var storage = InitializeDataset(dataset, GetSqlDb(), GetStorageFactory()); _storages.Add(dataset, storage); } } private static ISqlDatabase GetSqlDb() { var connectionString = ConfigurationManager.ConnectionStrings["mssql_connection"].ConnectionString; return (new MsSqlDbFactory()).CreateSqlDb(connectionString); } private static IEviQueryableStorageFactory GetStorageFactory() { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(LogLevel.Trace); if (Environment.GetEnvironmentVariable("APPVEYOR") != "True") { loggerFactory.AddDebug(LogLevel.Trace); } return new DefaultEviQueryableStorageFactory(loggerFactory); } protected override EviQueryableStorage GetStorage(string storageName) { return _storages[storageName]; } } }
using System.Collections.Generic; using System.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using Microsoft.VisualStudio.TestTools.UnitTesting; using Slp.Evi.Storage; using Slp.Evi.Storage.Bootstrap; using Slp.Evi.Storage.Database; using Slp.Evi.Storage.Database.Vendor.MsSql; namespace Slp.Evi.Test.System.SPARQL.SPARQL_TestSuite.Db { [TestClass] public class MSSQLDb : TestSuite { private static Dictionary<string, EviQueryableStorage> _storages; [ClassInitialize] public static void TestSuiteInitialization(TestContext context) { _storages = new Dictionary<string, EviQueryableStorage>(); foreach (var dataset in StorageNames) { var storage = InitializeDataset(dataset, GetSqlDb(), GetStorageFactory()); _storages.Add(dataset, storage); } } private static ISqlDatabase GetSqlDb() { var connectionString = ConfigurationManager.ConnectionStrings["mssql_connection"].ConnectionString; return (new MsSqlDbFactory()).CreateSqlDb(connectionString); } private static IEviQueryableStorageFactory GetStorageFactory() { var loggerFactory = new LoggerFactory(); loggerFactory.AddConsole(LogLevel.Trace); loggerFactory.AddDebug(LogLevel.Trace); return new DefaultEviQueryableStorageFactory(loggerFactory); } protected override EviQueryableStorage GetStorage(string storageName) { return _storages[storageName]; } } }
mit
C#
af38c72b6cc9d8b0a37b29d7143f4a8cfffffa9d
Add one more unit test
kriasoft/Diffbot
test/Diffbot.Client.Tests/DiffbotClientTest.cs
test/Diffbot.Client.Tests/DiffbotClientTest.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DiffbotClientTest.cs" company="KriaSoft LLC"> // Copyright © 2014 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Diffbot.Client.Tests { using System.Net.Http; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class DiffbotClientTest { private const string ValidApiKey = "<your api key>"; private const string InvalidApiKey = "b2571e7c9108ac25ef31cdd30ef83194"; private const string WebPageUrl1 = "http://gigaom.com/cloud/silicon-valley-royalty-pony-up-2m-to-scale-diffbots-visual-learning-robot/"; [TestMethod, TestCategory("Integration")] public async Task DiffbotClient_GetArticle_Should_Return_an_Article() { // Arrange var client = new DiffbotClient(ValidApiKey); // Act var article = await client.GetArticle(WebPageUrl1); // Assert Assert.IsNotNull(article); Assert.AreEqual("Silicon Valley stars pony up $2M to scale Diffbot’s visual learning robot", article.Title); } [TestMethod, TestCategory("Integration"), ExpectedException(typeof(HttpRequestException))] public async Task DiffbotClient_GetArticle_Should_Throw_an_Exception() { // Arrange var client = new DiffbotClient(InvalidApiKey); // Act await client.GetArticle(WebPageUrl1); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DiffbotClientTest.cs" company="KriaSoft LLC"> // Copyright © 2014 Konstantin Tarkus, KriaSoft LLC. See LICENSE.txt // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Diffbot.Client.Tests { using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class DiffbotClientTest { private const string ValidApiKey = "<your api key>"; private const string InvalidApiKey = "b2571e7c9108ac25ef31cdd30ef83194"; [TestMethod, TestCategory("Integration")] public async Task DiffbotClient_GetArticle_Should_Return_an_Article() { // Arrange var client = new DiffbotClient(ValidApiKey); // Act var article = await client.GetArticle( "http://gigaom.com/cloud/silicon-valley-royalty-pony-up-2m-to-scale-diffbots-visual-learning-robot/"); // Assert Assert.IsNotNull(article); Assert.AreEqual("Silicon Valley stars pony up $2M to scale Diffbot’s visual learning robot", article.Title); } } }
apache-2.0
C#
0acfbb05e922d7612e3b324fe1efd24d73319848
simplify type verification
zmira/abremir.AllMyBricks
abremir.AllMyBricks.Onboarding.Tests/Helpers/RandomKeyOptionGeneratorTests.cs
abremir.AllMyBricks.Onboarding.Tests/Helpers/RandomKeyOptionGeneratorTests.cs
using abremir.AllMyBricks.Core.Enumerations; using abremir.AllMyBricks.Onboarding.Helpers; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace abremir.AllMyBricks.Onboarding.Tests.Helpers { [TestClass] public class RandomKeyOptionGeneratorTests { [TestMethod] public void GetRandomKeyOption() { const int count = 1000; var algorithmTypeEnumList = new List<AlgorithmTypeEnum>(); for (int i = 0; i < count; i++) { var next = RandomKeyOptionGenerator.GetRandomKeyOption(); algorithmTypeEnumList.Add(next); } algorithmTypeEnumList.Should().HaveCount(count); algorithmTypeEnumList.Should().OnlyContain(algoType => algoType is AlgorithmTypeEnum); } } }
using abremir.AllMyBricks.Core.Enumerations; using abremir.AllMyBricks.Onboarding.Helpers; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace abremir.AllMyBricks.Onboarding.Tests.Helpers { [TestClass] public class RandomKeyOptionGeneratorTests { [TestMethod] public void GetRandomKeyOption() { const int count = 1000; var algorithmTypeEnumList = new List<AlgorithmTypeEnum>(); for (int i = 0; i < count; i++) { var next = RandomKeyOptionGenerator.GetRandomKeyOption(); algorithmTypeEnumList.Add(next); } algorithmTypeEnumList.Should().HaveCount(count); algorithmTypeEnumList.Should().OnlyContain(algoType => algoType.GetType() == typeof(AlgorithmTypeEnum)); } } }
mit
C#
09af49baae1353516381c8ce8569a48ad2a3fdb4
increase BrokerSenderSendTimeout to 10s
zesus19/hermes.net,sdgdsffdsfff/hermes.net
Arch.CMessaging.Client/Producer/Config/ProducerConfig.cs
Arch.CMessaging.Client/Producer/Config/ProducerConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Arch.CMessaging.Client.Core.Ioc; namespace Arch.CMessaging.Client.Producer.Config { [Named (ServiceType = typeof(ProducerConfig ))] public class ProducerConfig { public string DefaultBrokerSenderNetworkIoThreadCount { get { return "10"; } } public string DefaultBrokerSenderNetworkIoCheckIntervalBaseMillis { get { return "5"; } } public string DefaultBrokerSenderNetworkIoCheckIntervalMaxMillis { get { return "50"; } } public string DefaultBrokerSenderBatchSize { get { return "10000"; } } public int DefaultBrokerSenderSendTimeoutMillis { get { return 10000; } } public string DefaultBrokerSenderTaskQueueSize { get { return "500000"; } } public string DefaultProducerCallbackThreadCount { get { return "3"; } } public int SendMessageReadResultTimeoutMillis { get { return 10 * 1000; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Arch.CMessaging.Client.Core.Ioc; namespace Arch.CMessaging.Client.Producer.Config { [Named (ServiceType = typeof(ProducerConfig ))] public class ProducerConfig { public string DefaultBrokerSenderNetworkIoThreadCount { get { return "10"; } } public string DefaultBrokerSenderNetworkIoCheckIntervalBaseMillis { get { return "5"; } } public string DefaultBrokerSenderNetworkIoCheckIntervalMaxMillis { get { return "50"; } } public string DefaultBrokerSenderBatchSize { get { return "10000"; } } public int DefaultBrokerSenderSendTimeoutMillis { get { return 2000; } } public string DefaultBrokerSenderTaskQueueSize { get { return "500000"; } } public string DefaultProducerCallbackThreadCount { get { return "3"; } } public int SendMessageReadResultTimeoutMillis { get { return 10 * 1000; } } } }
apache-2.0
C#
a0e2ae155eb9e09d0f96869461fc5d5ec40c018c
Implement DisplayModeCollection.GetEnumerator
alesliehughes/monoDX,alesliehughes/monoDX
Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DisplayModeCollection.cs
Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DisplayModeCollection.cs
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Runtime.InteropServices; namespace Microsoft.DirectX.Direct3D { public sealed class DisplayModeCollection : IEnumerable, IEnumerator { public DisplayModeCollection this [Format f] { get { throw new NotImplementedException (); } } public int Count { get { throw new NotImplementedException (); } } public object Current { get { throw new NotImplementedException (); } } public void Reset () { throw new NotImplementedException (); } public bool MoveNext () { throw new NotImplementedException (); } public IEnumerator GetEnumerator () { return this; } public override bool Equals (object compare) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Runtime.InteropServices; namespace Microsoft.DirectX.Direct3D { public sealed class DisplayModeCollection : IEnumerable, IEnumerator { public DisplayModeCollection this [Format f] { get { throw new NotImplementedException (); } } public int Count { get { throw new NotImplementedException (); } } public object Current { get { throw new NotImplementedException (); } } public void Reset () { throw new NotImplementedException (); } public bool MoveNext () { throw new NotImplementedException (); } public IEnumerator GetEnumerator () { throw new NotImplementedException (); } public override bool Equals (object compare) { throw new NotImplementedException (); } public override int GetHashCode () { throw new NotImplementedException (); } } }
mit
C#
df4a71573dd0cc50e89afb9bb762d603f39a9a93
Update D2DGeometry.cs
jingwood/d2dlib,jingwood/d2dlib,jingwood/d2dlib
src/D2DLibExport/D2DGeometry.cs
src/D2DLibExport/D2DGeometry.cs
/* * MIT License * * Copyright (c) 2009-2018 Jingwood, unvell.com. All right reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using FLOAT = System.Single; using UINT = System.UInt32; using UINT32 = System.UInt32; using HWND = System.IntPtr; using HANDLE = System.IntPtr; using HRESULT = System.Int64; using BOOL = System.Int32; namespace unvell.D2DLib { public class D2DGeometry : D2DObject { internal HANDLE DeviceHandle { get; private set; } internal D2DGeometry(HANDLE deviceHandle, HANDLE geoHandle) : base(geoHandle) { this.DeviceHandle = deviceHandle; } // FIXME: TO be implemented //public void FillGeometry(D2DBrush brush, [Optional] D2DBrush opacityBrush) //{ // // TODO //} public D2DRect GetBounds() { var rect = new D2DRect(); D2D.GetGeometryBounds(this.Handle, ref rect); return rect; } public override void Dispose() { if (this.Handle != IntPtr.Zero) D2D.DestroyGeometry(this.Handle); this.handle = IntPtr.Zero; } } }
/* * MIT License * * Copyright (c) 2009-2018 Jingwood, unvell.com. All right reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using FLOAT = System.Single; using UINT = System.UInt32; using UINT32 = System.UInt32; using HWND = System.IntPtr; using HANDLE = System.IntPtr; using HRESULT = System.Int64; using BOOL = System.Int32; namespace unvell.D2DLib { public class D2DGeometry : D2DObject { internal HANDLE DeviceHandle { get; private set; } internal D2DGeometry(HANDLE deviceHandle, HANDLE geoHandle) : base(geoHandle) { this.DeviceHandle = deviceHandle; } // FIXME: TO be implemented //public void FillGeometry(D2DBrush brush, [Optional] D2DBrush opacityBrush) //{ // // TODO //} public D2DRect GetBounds() { var rect = new D2DRect(); D2D.GetGeometryBounds(this.Handle, ref rect); return rect; } } }
mit
C#
12b33966380ed2f9b76fcb09efe1286c6a517b29
Rename for clarity.
arlobelshee/Minions,Minions/Minions,Minions/Minions,arlobelshee/Minions
src/Fools.Tests/Tokenization.cs
src/Fools.Tests/Tokenization.cs
using FluentAssertions; using Fools.Tokenization; using NUnit.Framework; namespace Fools.Tests { [TestFixture] public class Tokenization { [Test] public void EmptyFileShouldTokenizeToSingleEmptyStatementWithNoIndentation() { var tokens = new FoolsTokenStream(""); tokens.Tokens.Should().Equal(new Token[] {new IndentationToken(0), new EndOfStatementToken()}); } } }
using FluentAssertions; using Fools.Tokenization; using NUnit.Framework; namespace Fools.Tests { [TestFixture] public class Tokenization { [Test] public void ShouldGetCorrectIndentationLevelForEmptyLine() { var tokens = new FoolsTokenStream(""); tokens.Tokens.Should().Equal(new Token[] {new IndentationToken(0), new EndOfStatementToken()}); } } }
bsd-3-clause
C#
a0efdd321b8394d94bf07796b9ffe1f18696bec2
Support all particle vector providers that have m_vLiteralValue
SteamDatabase/ValveResourceFormat
GUI/Types/ParticleRenderer/IVectorProvider.cs
GUI/Types/ParticleRenderer/IVectorProvider.cs
using System; using System.Numerics; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer { public interface IVectorProvider { Vector3 NextVector(); } public class LiteralVectorProvider : IVectorProvider { private readonly Vector3 value; public LiteralVectorProvider(Vector3 value) { this.value = value; } public LiteralVectorProvider(double[] value) { this.value = new Vector3((float)value[0], (float)value[1], (float)value[2]); } public Vector3 NextVector() => value; } public static class IVectorProviderExtensions { public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName) { var property = keyValues.GetProperty<object>(propertyName); if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType")) { var type = numberProviderParameters.GetProperty<string>("m_nType"); switch (type) { case "PVEC_TYPE_LITERAL": return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue")); default: if (numberProviderParameters.ContainsKey("m_vLiteralValue")) { Console.Error.WriteLine($"Vector provider of type {type} is not directly supported, but it has m_vLiteralValue."); return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue")); } throw new InvalidCastException($"Could not create vector provider of type {type}."); } } return new LiteralVectorProvider(keyValues.GetArray<double>(propertyName)); } } }
using System; using System.Numerics; using ValveResourceFormat.Serialization; namespace GUI.Types.ParticleRenderer { public interface IVectorProvider { Vector3 NextVector(); } public class LiteralVectorProvider : IVectorProvider { private readonly Vector3 value; public LiteralVectorProvider(Vector3 value) { this.value = value; } public LiteralVectorProvider(double[] value) { this.value = new Vector3((float)value[0], (float)value[1], (float)value[2]); } public Vector3 NextVector() => value; } public static class IVectorProviderExtensions { public static IVectorProvider GetVectorProvider(this IKeyValueCollection keyValues, string propertyName) { var property = keyValues.GetProperty<object>(propertyName); if (property is IKeyValueCollection numberProviderParameters && numberProviderParameters.ContainsKey("m_nType")) { var type = numberProviderParameters.GetProperty<string>("m_nType"); switch (type) { case "PVEC_TYPE_LITERAL": return new LiteralVectorProvider(numberProviderParameters.GetArray<double>("m_vLiteralValue")); default: throw new InvalidCastException($"Could not create vector provider of type {type}."); } } return new LiteralVectorProvider(keyValues.GetArray<double>(propertyName)); } } }
mit
C#
4714a7364df83f4c9c73f732c1d9d4cef702e824
Fix TcpSocketManager not using assigned IP address
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
osu!StreamCompanion/Code/Modules/MapDataGetters/TcpSocket/TcpSocketManager.cs
osu!StreamCompanion/Code/Modules/MapDataGetters/TcpSocket/TcpSocketManager.cs
using System; using System.IO; using System.Net; using System.Net.Sockets; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.TcpSocket { public class TcpSocketManager : IDisposable { private TcpClient _tcpClient; BinaryWriter _writer = null; public int ServerPort = 7839; public string ServerIp = "127.0.0.1"; public bool Connect() { if (_writer != null) return true; _tcpClient = new TcpClient(); try { _tcpClient.Connect(IPAddress.Parse(ServerIp), ServerPort); _writer = new BinaryWriter(_tcpClient.GetStream()); } catch (SocketException) { //No server avaliable, or it is busy/full. return false; } return true; } public void Write(string data) { try { if (_tcpClient.Connected) _writer?.Write(data); } catch (IOException) { //connection most likely closed _writer?.Dispose(); _writer = null; ((IDisposable)_tcpClient)?.Dispose(); } } public void Dispose() { ((IDisposable)_tcpClient)?.Dispose(); _writer?.Dispose(); } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; namespace osu_StreamCompanion.Code.Modules.MapDataGetters.TcpSocket { public class TcpSocketManager : IDisposable { private TcpClient _tcpClient; BinaryWriter _writer = null; public int ServerPort = 7839; public string ServerIp = "127.0.0.1"; public bool Connect() { if (_writer != null) return true; _tcpClient = new TcpClient(); try { _tcpClient.Connect(IPAddress.Parse("127.0.0.1"), ServerPort); _writer = new BinaryWriter(_tcpClient.GetStream()); } catch (SocketException) { //No server avaliable, or it is busy/full. return false; } return true; } public void Write(string data) { try { if (_tcpClient.Connected) _writer?.Write(data); } catch (IOException) { //connection most likely closed _writer?.Dispose(); _writer = null; ((IDisposable)_tcpClient)?.Dispose(); } } public void Dispose() { ((IDisposable)_tcpClient)?.Dispose(); _writer?.Dispose(); } } }
mit
C#
6fea0901113f9192d2bc415dace2daa3891aaf68
Fix encoding
leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net
JoinRpg.CommonUI.Models/CommentExtraAction.cs
JoinRpg.CommonUI.Models/CommentExtraAction.cs
using System.ComponentModel.DataAnnotations; using JetBrains.Annotations; namespace JoinRpg.CommonUI.Models { public enum CommentExtraAction { [Display(Name = "Финансовая операция подтверждена", ShortName = "отмечено")] [UsedImplicitly] ApproveFinance, [Display(Name = "Финансовая операция отклонена", ShortName = "отмечено")] [UsedImplicitly] RejectFinance, [Display(Name = "Заявка одобрена мастером", ShortName = "одобрена")] [UsedImplicitly] ApproveByMaster, [Display(Name = "Заявка отклонена мастером", ShortName = "отклонена")] [UsedImplicitly] DeclineByMaster, [Display(Name = "Заявка восстановлена мастером", ShortName = "восстановлена")] [UsedImplicitly] RestoreByMaster, [Display(Name = "Заявка перемещена мастером", ShortName = "изменена")] [UsedImplicitly] MoveByMaster, [Display(Name = "Заявка отозвана игроком", ShortName = "отозвана")] [UsedImplicitly] DeclineByPlayer, [Display(Name = "Ответственный мастер изменен", ShortName = "изменена")] [UsedImplicitly] ChangeResponsible, [Display(Name = "Новая заявка", ShortName = "подана")] [UsedImplicitly] NewClaim, [Display(Name = "Заявка поставлена в лист ожидания", ShortName = "изменена")] [UsedImplicitly] OnHoldByMaster } }
using System.ComponentModel.DataAnnotations; using JetBrains.Annotations; namespace JoinRpg.CommonUI.Models { public enum CommentExtraAction { [Display(Name = " ", ShortName = "")] [UsedImplicitly] ApproveFinance, [Display(Name = " ", ShortName = "")] [UsedImplicitly] RejectFinance, [Display(Name = " ", ShortName = "")] [UsedImplicitly] ApproveByMaster, [Display(Name = " ", ShortName = "")] [UsedImplicitly] DeclineByMaster, [Display(Name = " ", ShortName = "")] [UsedImplicitly] RestoreByMaster, [Display(Name = " ", ShortName = "")] [UsedImplicitly] MoveByMaster, [Display(Name = " ", ShortName = "")] [UsedImplicitly] DeclineByPlayer, [Display(Name = " ", ShortName = "")] [UsedImplicitly] ChangeResponsible, [Display(Name = " ", ShortName = "")] [UsedImplicitly] NewClaim, [Display(Name = " ", ShortName = "")] [UsedImplicitly] OnHoldByMaster } }
mit
C#
0196256e6e99452917ae13e14d0559aa52ca6226
Change VsShellInfo to specifically look for Dev11
dolkensp/node.net,mrward/nuget,alluran/node.net,chester89/nugetApi,oliver-feng/nuget,mrward/NuGet.V2,GearedToWar/NuGet2,mrward/NuGet.V2,rikoe/nuget,mrward/NuGet.V2,zskullz/nuget,RichiCoder1/nuget-chocolatey,atheken/nuget,ctaggart/nuget,OneGet/nuget,pratikkagda/nuget,indsoft/NuGet2,anurse/NuGet,jmezach/NuGet2,pratikkagda/nuget,pratikkagda/nuget,oliver-feng/nuget,ctaggart/nuget,mrward/NuGet.V2,GearedToWar/NuGet2,OneGet/nuget,indsoft/NuGet2,chocolatey/nuget-chocolatey,indsoft/NuGet2,chester89/nugetApi,pratikkagda/nuget,ctaggart/nuget,ctaggart/nuget,oliver-feng/nuget,antiufo/NuGet2,antiufo/NuGet2,dolkensp/node.net,kumavis/NuGet,pratikkagda/nuget,oliver-feng/nuget,jholovacs/NuGet,themotleyfool/NuGet,themotleyfool/NuGet,jholovacs/NuGet,antiufo/NuGet2,xoofx/NuGet,OneGet/nuget,zskullz/nuget,jmezach/NuGet2,jholovacs/NuGet,chocolatey/nuget-chocolatey,anurse/NuGet,jmezach/NuGet2,xoofx/NuGet,mono/nuget,RichiCoder1/nuget-chocolatey,mrward/nuget,themotleyfool/NuGet,dolkensp/node.net,akrisiun/NuGet,mono/nuget,RichiCoder1/nuget-chocolatey,mrward/nuget,kumavis/NuGet,xoofx/NuGet,GearedToWar/NuGet2,akrisiun/NuGet,oliver-feng/nuget,indsoft/NuGet2,OneGet/nuget,xoofx/NuGet,GearedToWar/NuGet2,chocolatey/nuget-chocolatey,zskullz/nuget,mrward/nuget,xero-github/Nuget,alluran/node.net,jholovacs/NuGet,jholovacs/NuGet,zskullz/nuget,oliver-feng/nuget,mono/nuget,mrward/nuget,alluran/node.net,atheken/nuget,jholovacs/NuGet,dolkensp/node.net,mrward/NuGet.V2,mrward/NuGet.V2,GearedToWar/NuGet2,xoofx/NuGet,mono/nuget,mrward/nuget,chocolatey/nuget-chocolatey,rikoe/nuget,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,xoofx/NuGet,alluran/node.net,RichiCoder1/nuget-chocolatey,rikoe/nuget,jmezach/NuGet2,jmezach/NuGet2,jmezach/NuGet2,rikoe/nuget,GearedToWar/NuGet2,antiufo/NuGet2,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,antiufo/NuGet2,chocolatey/nuget-chocolatey,antiufo/NuGet2,indsoft/NuGet2,chocolatey/nuget-chocolatey
src/VisualStudio/VsShellInfo.cs
src/VisualStudio/VsShellInfo.cs
using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(IVsShellInfo))] public class VsShellInfo : IVsShellInfo { private const int ExpressSku = 500; private const int WindowsSubSku = 0x4000; private readonly Lazy<bool> _isVisualStudioExpressForWindows8Thunk = new Lazy<bool>(ShellIsVisualStudioExpressForWindows8); public bool IsVisualStudioExpressForWindows8 { get { return _isVisualStudioExpressForWindows8Thunk.Value; } } private static bool ShellIsVisualStudioExpressForWindows8() { if (VsVersionHelper.VsMajorVersion != 11) { // We only care for the Dev11 version of the express SKU. return false; } var vsShell = ServiceLocator.GetGlobalService<SVsShell, IVsShell>(); if (vsShell == null) { return false; } object skuValue; var isExpress = ErrorHandler.Succeeded(vsShell.GetProperty((int)__VSSPROPID2.VSSPROPID_SKUEdition, out skuValue)) && skuValue is int && (int)skuValue == ExpressSku; if (!isExpress) { return false; } object subSkuValue; var isWindows = ErrorHandler.Succeeded(vsShell.GetProperty((int)__VSSPROPID2.VSSPROPID_SubSKUEdition, out subSkuValue)) && subSkuValue is int && (int)subSkuValue == WindowsSubSku; if (!isWindows) { return false; } return true; } } }
using System; using System.ComponentModel.Composition; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(IVsShellInfo))] public class VsShellInfo : IVsShellInfo { private const int ExpressSku = 500; private const int WindowsSubSku = 0x4000; private readonly Lazy<bool> _isVisualStudioExpressForWindows8Thunk = new Lazy<bool>(ShellIsVisualStudioExpressForWindows8); public bool IsVisualStudioExpressForWindows8 { get { return _isVisualStudioExpressForWindows8Thunk.Value; } } private static bool ShellIsVisualStudioExpressForWindows8() { if (VsVersionHelper.VsMajorVersion >= 11) { return false; } var vsShell = ServiceLocator.GetGlobalService<SVsShell, IVsShell>(); if (vsShell == null) { return false; } object skuValue; var isExpress = ErrorHandler.Succeeded(vsShell.GetProperty((int)__VSSPROPID2.VSSPROPID_SKUEdition, out skuValue)) && skuValue is int && (int)skuValue == ExpressSku; if (!isExpress) { return false; } object subSkuValue; var isWindows = ErrorHandler.Succeeded(vsShell.GetProperty((int)__VSSPROPID2.VSSPROPID_SubSKUEdition, out subSkuValue)) && subSkuValue is int && (int)subSkuValue == WindowsSubSku; if (!isWindows) { return false; } return true; } } }
apache-2.0
C#
1ab6e58254d8675a10fe7fa7473fa10ba14a9169
enhance GetCultureRequest.
signumsoftware/extensions,AlejandroCano/extensions,AlejandroCano/extensions,signumsoftware/framework,signumsoftware/extensions,signumsoftware/framework
Signum.React.Extensions/Translation/TranslationServer.cs
Signum.React.Extensions/Translation/TranslationServer.cs
using Signum.Engine.Basics; using Signum.Engine.Translation; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Signum.React.Facades; using Signum.Entities.Translation; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace Signum.React.Translation { public class TranslationServer { public static ITranslator Translator; public static void Start(IApplicationBuilder app, ITranslator translator) { ReflectionServer.RegisterLike(typeof(TranslationMessage)); SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod()); Translator = translator; } public static CultureInfo? GetCultureRequest(ActionContext actionContext) { var acceptedLanguages = actionContext.HttpContext.Request.GetTypedHeaders().AcceptLanguage; foreach (var lang in acceptedLanguages.Select(l => l.Value)) { var cleanLang = lang.Value.Contains('-') ? lang.Value.Split('-')[0] : lang.Value; var culture = CultureInfoLogic.ApplicationCultures .FirstOrDefault(ci => ci.Name.StartsWith(cleanLang)); if (culture != null) return culture; } return null; } public static string? ReadLanguageCookie(ActionContext ac) { return ac.HttpContext.Request.Cookies.TryGetValue("language", out string value) ? value : null; } } }
using Signum.Engine.Basics; using Signum.Engine.Translation; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Signum.React.Facades; using Signum.Entities.Translation; using Microsoft.AspNetCore.Builder; namespace Signum.React.Translation { public class TranslationServer { public static ITranslator Translator; public static void Start(IApplicationBuilder app, ITranslator translator) { ReflectionServer.RegisterLike(typeof(TranslationMessage)); SignumControllerFactory.RegisterArea(MethodInfo.GetCurrentMethod()); Translator = translator; } public static CultureInfo? GetCultureRequest(ActionContext actionContext) { foreach (string lang in actionContext.HttpContext.Request.Headers["accept-languages"]) { string cleanLang = lang.Contains('-') ? lang.Split('-')[0] : lang; var culture = CultureInfoLogic.ApplicationCultures .Where(ci => ci.Name.StartsWith(cleanLang)) .FirstOrDefault(); if (culture != null) return culture; } return null; } public static string? ReadLanguageCookie(ActionContext ac) { return ac.HttpContext.Request.Cookies.TryGetValue("language", out string value) ? value : null; } } }
mit
C#
874576d8d166393696765bd60867c72c8a14582c
Fix bug where drawn objects are also transparent, and add pen variable.
VuWall/VuWall-Motion,DanH91/vuwall-motion
vuwall-motion/vuwall-motion/TransparentForm.cs
vuwall-motion/vuwall-motion/TransparentForm.cs
using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { private Pen pen = new Pen(Color.Red, 5); public TransparentForm() { InitializeComponent(); DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); TransparencyKey = BackColor; ShowInTaskbar = false; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(pen, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & y positions, used to invalidate } }
using System; using System.Drawing; using System.Windows.Forms; namespace vuwall_motion { public partial class TransparentForm : Form { public TransparentForm() { InitializeComponent(); DoubleBuffered = true; ShowInTaskbar = false; } private void TransparentForm_Load(object sender, EventArgs e) { int wl = TransparentWindowAPI.GetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle); wl = wl | 0x80000 | 0x20; TransparentWindowAPI.SetWindowLong(this.Handle, TransparentWindowAPI.GWL.ExStyle, wl); TransparentWindowAPI.SetLayeredWindowAttributes(this.Handle, 0, 128, TransparentWindowAPI.LWA.Alpha); Invalidate(); } private void TransparentForm_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawEllipse(Pens.Red, 250, 250, 20, 20); } // TODO: Method to get an event from MYO to get x & y positions, used to invalidate } }
mit
C#
323d48439648eaf95493f021dc50e7e81c606825
Add journals and self relations.
TeamYAGNI/LibrarySystem
LibrarySystem/LibrarySystem.Models/Subject.cs
LibrarySystem/LibrarySystem.Models/Subject.cs
// <copyright file="Subject.cs" company="YAGNI"> // All rights reserved. // </copyright> // <summary>Holds implementation of Book model.</summary> using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace LibrarySystem.Models { /// <summary> /// Represent a <see cref="Subject"/> entity model. /// </summary> public class Subject { /// <summary> /// Child nodes of the <see cref="Subject"/> entity. /// </summary> private ICollection<Subject> subSubjects; /// <summary> /// Journal of the <see cref="Subject"/> entity. /// </summary> private ICollection<Journal> journals; /// <summary> /// Initializes a new instance of the <see cref="Subject"/> class. /// </summary> public Subject() { this.subSubjects = new HashSet<Subject>(); this.journals = new HashSet<Journal>(); } /// <summary> /// Gets or sets the primary key of the <see cref="Subject"/> entity. /// </summary> /// <value>Primary key of the <see cref="Subject"/> entity.</value> [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } /// <summary> /// Gets or sets the name of the <see cref="Subject"/> entity. /// </summary> /// <value>Name of the <see cref="Subject"/> entity.</value> [Required] [StringLength(50, ErrorMessage = "Subject Name Invalid Length", MinimumLength = 1)] public string Name { get; set; } /// <summary> /// Gets or sets foreign key of the parent node of the <see cref="Subject"/> entity. /// </summary> /// <value>Primary key of the parent node of the <see cref="Subject"/> entity.</value> public int? SuperSubjectId { get; set; } /// <summary> /// Gets or sets the parent node of the <see cref="Subject"/> entity. /// </summary> /// <value>Parent node of the <see cref="Subject"/> entity.</value> public virtual Subject SuperSubject { get; set; } /// <summary> /// Gets or sets the child nodes of the <see cref="Subject"/> entity. /// </summary> /// <value>Initial collection of child nodes of the <see cref="Subject"/> entity.</value> public virtual ICollection<Subject> SubSubjects { get { return this.subSubjects; } set { this.subSubjects = value; } } /// <summary> /// Gets or sets the journals related to the <see cref="Subject"/> entity. /// </summary> /// <value>Initial collection of journals related to the <see cref="Subject"/> entity.</value> public virtual ICollection<Journal> Journals { get { return this.journals; } set { this.journals = value; } } } }
using System.ComponentModel.DataAnnotations; namespace LibrarySystem.Models { public class Subject { public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } } }
mit
C#
1f39efa1195bb4fbe64e7df6692fc9d43ea6b353
Fix bug in IQuickInfoModelProvider for SELECT column aliases
terrajobst/nquery-vnext
src/NQuery.Authoring/QuickInfo/ExpressionSelectColumnQuickInfoModelProvider.cs
src/NQuery.Authoring/QuickInfo/ExpressionSelectColumnQuickInfoModelProvider.cs
using System; using System.ComponentModel.Composition; using NQuery.Syntax; namespace NQuery.Authoring.QuickInfo { [Export(typeof(IQuickInfoModelProvider))] internal sealed class ExpressionSelectColumnQuickInfoModelProvider : QuickInfoModelProvider<ExpressionSelectColumnSyntax> { protected override QuickInfoModel CreateModel(SemanticModel semanticModel, int position, ExpressionSelectColumnSyntax node) { if (node.Alias == null || !node.Alias.Span.Contains(position)) return null; var symbol = semanticModel.GetDeclaredSymbol(node); return symbol == null ? null : QuickInfoModel.ForSymbol(semanticModel, node.Alias.Identifier.Span, symbol); } } }
using System; using System.ComponentModel.Composition; using NQuery.Syntax; namespace NQuery.Authoring.QuickInfo { [Export(typeof(IQuickInfoModelProvider))] internal sealed class ExpressionSelectColumnQuickInfoModelProvider : QuickInfoModelProvider<ExpressionSelectColumnSyntax> { protected override QuickInfoModel CreateModel(SemanticModel semanticModel, int position, ExpressionSelectColumnSyntax node) { if (node.Alias == null) return null; var symbol = semanticModel.GetDeclaredSymbol(node); return symbol == null ? null : QuickInfoModel.ForSymbol(semanticModel, node.Alias.Identifier.Span, symbol); } } }
mit
C#
64be41967f02afb44c3546bcf6d0f72bac6ef100
check that waypoints are actually populated
AlexCuse/PathFinder
PathFinder.Loaders.Tests/Gpx/GpxLoaderTest.cs
PathFinder.Loaders.Tests/Gpx/GpxLoaderTest.cs
using System; using NUnit.Framework; using System.Linq; using PathFinder.Loaders.Gpx; namespace PathFinder.Loaders.Tests.Gpx { [TestFixture] public class GpxFileLoaderTest { [TestCase("SampleFiles\\DamLoop.gpx", 1, 1155)] [TestCase("SampleFiles\\GreenLane.gpx", 1, 1665)]//with garmin extensions public void Load(string filePath, int wayCount, int waypointCount) { var loader = new GpxFileLoader(); var gpsData = loader.Load(filePath); Assert.AreEqual(wayCount, gpsData.Count); Assert.AreEqual(waypointCount, gpsData[0].Count); Assert.True(gpsData[0].All(wp => Math.Abs(wp.Latitude) > 0 && Math.Abs(wp.Longitude) > 0 && wp.Elevation > 0)); } } }
using NUnit.Framework; using PathFinder.Loaders.Gpx; namespace PathFinder.Loaders.Tests.Gpx { [TestFixture] public class GpxFileLoaderTest { [TestCase("SampleFiles\\DamLoop.gpx", 1, 1155)] [TestCase("SampleFiles\\GreenLane.gpx", 1, 1665)]//with garmin extensions public void Load(string filePath, int trackCount, int trackpointCount) { var loader = new GpxFileLoader(); var gpsData = loader.Load(filePath); Assert.AreEqual(trackCount, gpsData.Count); Assert.AreEqual(trackpointCount, gpsData[0].Count); } } }
mit
C#
de0086e888ccf9570e890ef13113853ff478aff9
change user config AbsolutePath to LocalPath
quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot
CactbotOverlay/CactbotEventSourceConfigPanel.cs
CactbotOverlay/CactbotEventSourceConfigPanel.cs
using System; using System.Globalization; using System.Windows.Forms; namespace Cactbot { public partial class CactbotEventSourceConfigPanel : UserControl { private CactbotEventSourceConfig config; private CactbotEventSource source; public CactbotEventSourceConfigPanel(CactbotEventSource source) { InitializeComponent(); this.source = source; this.config = source.Config; SetupControlProperties(); SetupConfigEventHandlers(); } private void SetupControlProperties() { this.textUserConfigFile.Text = config.UserConfigFile; this.checkWatchFileChanges.Checked = config.WatchFileChanges; } private void SetupConfigEventHandlers() { } private void InvokeIfRequired(Action action) { if (this.InvokeRequired) { this.Invoke(action); } else { action(); } } private void buttonSelectUserConfigFile_Click(object sender, EventArgs e) { var ofd = new FolderBrowserDialog(); try { ofd.SelectedPath = System.IO.Path.GetDirectoryName(new Uri(config.UserConfigFile).AbsolutePath); } catch (Exception) { } if (ofd.ShowDialog() == DialogResult.OK) { this.config.UserConfigFile = new Uri(ofd.SelectedPath).AbsoluteUri; this.textUserConfigFile.Text = this.config.UserConfigFile; } } private void textUserConfigFile_Leave(object sender, EventArgs e) { try { if (!String.IsNullOrWhiteSpace(textUserConfigFile.Text)) { var path = new Uri(textUserConfigFile.Text); if (!System.IO.Directory.Exists(path.LocalPath)) path = new Uri(path, "."); this.config.UserConfigFile = path.AbsoluteUri; } else { this.config.UserConfigFile = ""; } this.textUserConfigFile.Text = this.config.UserConfigFile; } catch (Exception ex) { this.source.LogError("User Config Directory Uri must be a valid directory."); this.source.LogError(ex.Message); } } private void checkWatchFileChanges_CheckedChanged(object sender, EventArgs e) { this.config.WatchFileChanges = this.checkWatchFileChanges.Checked; } } }
using System; using System.Globalization; using System.Windows.Forms; namespace Cactbot { public partial class CactbotEventSourceConfigPanel : UserControl { private CactbotEventSourceConfig config; private CactbotEventSource source; public CactbotEventSourceConfigPanel(CactbotEventSource source) { InitializeComponent(); this.source = source; this.config = source.Config; SetupControlProperties(); SetupConfigEventHandlers(); } private void SetupControlProperties() { this.textUserConfigFile.Text = config.UserConfigFile; this.checkWatchFileChanges.Checked = config.WatchFileChanges; } private void SetupConfigEventHandlers() { } private void InvokeIfRequired(Action action) { if (this.InvokeRequired) { this.Invoke(action); } else { action(); } } private void buttonSelectUserConfigFile_Click(object sender, EventArgs e) { var ofd = new FolderBrowserDialog(); try { ofd.SelectedPath = System.IO.Path.GetDirectoryName(new Uri(config.UserConfigFile).AbsolutePath); } catch (Exception) { } if (ofd.ShowDialog() == DialogResult.OK) { this.config.UserConfigFile = new Uri(ofd.SelectedPath).AbsoluteUri; this.textUserConfigFile.Text = this.config.UserConfigFile; } } private void textUserConfigFile_Leave(object sender, EventArgs e) { try { if (!String.IsNullOrWhiteSpace(textUserConfigFile.Text)) { var path = new Uri(textUserConfigFile.Text); if (!System.IO.Directory.Exists(path.AbsolutePath)) path = new Uri(path, "."); this.config.UserConfigFile = path.AbsoluteUri; } else { this.config.UserConfigFile = ""; } this.textUserConfigFile.Text = this.config.UserConfigFile; } catch (Exception ex) { this.source.LogError("User Config Directory Uri must be a valid directory."); this.source.LogError(ex.Message); } } private void checkWatchFileChanges_CheckedChanged(object sender, EventArgs e) { this.config.WatchFileChanges = this.checkWatchFileChanges.Checked; } } }
apache-2.0
C#
7cfc27529e2d4c91eb66323be2d4f845ffd9322b
Update tests/SixLabors.Fonts.Tests/Tables/AdvancedTypographic/Gsub/GSubTableTests.cs
SixLabors/Fonts
tests/SixLabors.Fonts.Tests/Tables/AdvancedTypographic/Gsub/GSubTableTests.cs
tests/SixLabors.Fonts.Tests/Tables/AdvancedTypographic/Gsub/GSubTableTests.cs
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using Xunit; namespace SixLabors.Fonts.Tests.Tables.AdvancedTypographic.Gsub { public class GSubTableTests { // TODO: add all other arabic letters [Fact] public void RenderArabicCharacters_WithIsolatedForm_Works() { // arrange Font arabicFont = new FontCollection().Add(TestFonts.ArabicFontFile).CreateFont(8); string testStr = "ب"; var rendererTtf = new ColorGlyphRenderer(); bool applyKerning = true; int expectedGlyphIndex = 157; // act TextRenderer.RenderTextTo(rendererTtf, testStr, new RendererOptions(arabicFont) { ApplyKerning = applyKerning, ColorFontSupport = ColorFontSupport.MicrosoftColrFormat }); // assert var glyphKey = Assert.Single(rendererTtf.GlyphKeys); Assert.Equal(expectedGlyphIndex, glyphKey.GlyphIndex); } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using Xunit; namespace SixLabors.Fonts.Tests.Tables.AdvancedTypographic.Gsub { public class GSubTableTests { // TODO: add all other arabic letters [Fact] public void RenderArabicCharacters_WithIsolatedForm_Works() { // arrange Font arabicFont = new FontCollection().Add(TestFonts.ArabicFontFile).CreateFont(8); string testStr = "ب"; var rendererTtf = new ColorGlyphRenderer(); bool applyKerning = true; int expectedGlyphIndex = 157; // act TextRenderer.RenderTextTo(rendererTtf, testStr, new RendererOptions(arabicFont) { ApplyKerning = applyKerning, ColorFontSupport = ColorFontSupport.MicrosoftColrFormat }); // assert Assert.Single(rendererTtf.GlyphKeys); Assert.Equal(expectedGlyphIndex, rendererTtf.GlyphKeys[0].GlyphIndex); } } }
apache-2.0
C#
51e4995e3575efc47985c527db0cc018b36602f4
Add hash code to work/username
windowsphonehacker/SparklrWP
SparklrLib/Objects/Responses/Work/Username.cs
SparklrLib/Objects/Responses/Work/Username.cs
 using System; namespace SparklrLib.Objects.Responses.Work { public class Username : IEquatable<Username> { public string username { get; set; } public string displayname { get; set; } public int id { get; set; } public override string ToString() { return id + ": " + displayname + " (@" + username + ")"; } public override int GetHashCode() { return id; } public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. Username u = obj as Username; if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(Username u) { // If parameter is null return false: if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(int newid) { // If parameter is null return false: if ((object)newid == null) { return false; } // Return true if the fields match: return id == newid; } } }
 using System; namespace SparklrLib.Objects.Responses.Work { public class Username : IEquatable<Username> { public string username { get; set; } public string displayname { get; set; } public int id { get; set; } public override string ToString() { return id + ": " + displayname + " (@" + username + ")"; } public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. Username u = obj as Username; if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(Username u) { // If parameter is null return false: if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(int newid) { // If parameter is null return false: if ((object)newid == null) { return false; } // Return true if the fields match: return id == newid; } } }
mit
C#
b3666f2d21ba3358cfdcd280afd39296c5a778f0
Update work/username
windowsphonehacker/SparklrWP
SparklrLib/Objects/Responses/Work/Username.cs
SparklrLib/Objects/Responses/Work/Username.cs
 using System; namespace SparklrLib.Objects.Responses.Work { public class Username : IEquatable<Username> { public string username { get; set; } public string displayname { get; set; } public int id { get; set; } public override string ToString() { return id + ": " + displayname + " (@" + username + ")"; } public override bool Equals(object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. Username u = obj as Username; if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(Username u) { // If parameter is null return false: if ((object)u == null) { return false; } // Return true if the fields match: return id == u.id; } public bool Equals(int newid) { // If parameter is null return false: if ((object)newid == null) { return false; } // Return true if the fields match: return id == newid; } } }
 namespace SparklrLib.Objects.Responses.Work { public class Username { public string username { get; set; } public int id { get; set; } public override string ToString() { return id + ": " + username; } } }
mit
C#
f1fa9304331a129f9dfd5a251969d6413e7ec184
Fix formatting
RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate
Source/Boilerplate.Templates/Content/ApiTemplate/Options/CertificateOptions.cs
Source/Boilerplate.Templates/Content/ApiTemplate/Options/CertificateOptions.cs
namespace ApiTemplate.Options { public class CertificateOptions { public bool AllowInvalid { get; set; } public string Subject { get; set; } public string Store { get; set; } public string Location { get; set; } public string Path { get; set; } public string Password { get; set; } } }
namespace ApiTemplate.Options { public class CertificateOptions { public bool AllowInvalid { get;set; } public string Subject { get; set; } public string Store { get; set; } public string Location { get; set; } public string Path { get; set; } public string Password { get; set; } } }
mit
C#
8ebf5d3f378135aabb10326d533d6c3b9d60f7ae
Fix comments.
cube-soft/Cube.Core,cube-soft/Cube.Core
Libraries/Sources/Collections/LambdaComparer.cs
Libraries/Sources/Collections/LambdaComparer.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System; using System.Collections.Generic; namespace Cube.Collections { /* --------------------------------------------------------------------- */ /// /// LambdaComparer(T) /// /// <summary> /// Provides functionality to convert from the Func(T, T, bool) to /// the instance of Comparer(T) inherited class. /// </summary> /// /* --------------------------------------------------------------------- */ public class LambdaComparer<T> : Comparer<T> { #region Constructors /* ----------------------------------------------------------------- */ /// /// LambdaComparer(T) /// /// <summary> /// Initializes a new instance of the LambdaComparer(T) with the /// specified function. /// </summary> /// /// <param name="src">Function to compare.</param> /// /* ----------------------------------------------------------------- */ public LambdaComparer(Func<T, T, int> src) { _comparer = src; } #endregion #region Methods /* ----------------------------------------------------------------- */ /// /// Compare /// /// <summary> /// Compares two objects of type T and returns an indication of /// their relative sort order. /// </summary> /// /// <param name="x">The first object to compare.</param> /// <param name="y">The second object to compare.</param> /// /// <returns> /// Zero if the specified objects are equal; /// Less than zero if x is less than y; /// otherwise, Greater than zero. /// </returns> /// /* ----------------------------------------------------------------- */ public override int Compare(T x, T y) => _comparer(x, y); #endregion #region Fields private readonly Func<T, T, int> _comparer; #endregion } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System; using System.Collections.Generic; namespace Cube.Collections { /* --------------------------------------------------------------------- */ /// /// LambdaComparer(T) /// /// <summary> /// Provides functionality to convert from the Func(T, T, bool) to /// the instance of Comparer(T) inherited class. /// </summary> /// /* --------------------------------------------------------------------- */ public class LambdaComparer<T> : Comparer<T> { #region Constructors /* ----------------------------------------------------------------- */ /// /// LambdaComparer(T) /// /// <summary> /// Initializes a new instance of the LambdaComparer(T) with the /// specified function. /// </summary> /// /// <param name="src">Function to compare.</param> /// /* ----------------------------------------------------------------- */ public LambdaComparer(Func<T, T, int> src) { _comparer = src; } #endregion #region Methods /* ----------------------------------------------------------------- */ /// /// Equals /// /// <summary> /// Determines whether two objects of type T are equal. /// </summary> /// /// <param name="x">The first object to compare.</param> /// <param name="y">The second object to compare.</param> /// /// <returns> /// Zero if the specified objects are equal; /// Less than zero if x is less than y; /// otherwise, Greater than zero. /// </returns> /// /* ----------------------------------------------------------------- */ public override int Compare(T x, T y) => _comparer(x, y); #endregion #region Fields private readonly Func<T, T, int> _comparer; #endregion } }
apache-2.0
C#
d6297823419371fcbfe75e148a6ffdfb9db1b66f
Update test suite for latest changes
nwoolls/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner
MultiMiner.Win/Extensions/DateTimeExtensions.cs
MultiMiner.Win/Extensions/DateTimeExtensions.cs
using System; using System.Globalization; namespace MultiMiner.Win.Extensions { public static class DateTimeExtensions { private static string ToReallyShortDateString(this DateTime dateTime) { //short date no year string shortDateString = dateTime.ToShortDateString(); //year could be at beginning (JP) or end (EN) string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator; string value1 = dateTime.Year + dateSeparator; string value2 = dateSeparator + dateTime.Year; return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty); } public static string ToReallyShortDateTimeString(this DateTime dateTime) { return String.Format("{0} {1}", dateTime.ToReallyShortDateString(), dateTime.ToShortTimeString()); } } }
using System; using System.Globalization; namespace MultiMiner.Win.Extensions { public static class DateTimeExtensions { public static string ToReallyShortDateString(this DateTime dateTime) { //short date no year string shortDateString = dateTime.ToShortDateString(); //year could be at beginning (JP) or end (EN) string dateSeparator = CultureInfo.CurrentCulture.DateTimeFormat.DateSeparator; string value1 = dateTime.Year + dateSeparator; string value2 = dateSeparator + dateTime.Year; return shortDateString.Replace(value1, String.Empty).Replace(value2, String.Empty); } public static string ToReallyShortDateTimeString(this DateTime dateTime) { return String.Format("{0} {1}", dateTime.ToReallyShortDateString(), dateTime.ToShortTimeString()); } } }
mit
C#
b9e0c471ddf65b06c5398faeb860b89b5ccf1ef8
Add bytes support to TempFile path
Ermiar/corefx,nbarbettini/corefx,wtgodbe/corefx,wtgodbe/corefx,ptoonen/corefx,ravimeda/corefx,ViktorHofer/corefx,the-dwyer/corefx,mmitche/corefx,fgreinacher/corefx,mazong1123/corefx,Jiayili1/corefx,axelheer/corefx,JosephTremoulet/corefx,ericstj/corefx,nchikanov/corefx,stone-li/corefx,seanshpark/corefx,mazong1123/corefx,parjong/corefx,richlander/corefx,ViktorHofer/corefx,DnlHarvey/corefx,stone-li/corefx,MaggieTsang/corefx,axelheer/corefx,zhenlan/corefx,ptoonen/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,jlin177/corefx,yizhang82/corefx,krk/corefx,Jiayili1/corefx,parjong/corefx,nbarbettini/corefx,twsouthwick/corefx,rubo/corefx,ptoonen/corefx,MaggieTsang/corefx,richlander/corefx,ViktorHofer/corefx,JosephTremoulet/corefx,zhenlan/corefx,cydhaselton/corefx,ravimeda/corefx,axelheer/corefx,ViktorHofer/corefx,mazong1123/corefx,wtgodbe/corefx,richlander/corefx,parjong/corefx,jlin177/corefx,seanshpark/corefx,MaggieTsang/corefx,the-dwyer/corefx,yizhang82/corefx,fgreinacher/corefx,richlander/corefx,BrennanConroy/corefx,shimingsg/corefx,wtgodbe/corefx,krk/corefx,fgreinacher/corefx,yizhang82/corefx,jlin177/corefx,parjong/corefx,ericstj/corefx,nchikanov/corefx,Ermiar/corefx,shimingsg/corefx,DnlHarvey/corefx,nbarbettini/corefx,jlin177/corefx,Ermiar/corefx,cydhaselton/corefx,ericstj/corefx,tijoytom/corefx,ravimeda/corefx,JosephTremoulet/corefx,shimingsg/corefx,yizhang82/corefx,yizhang82/corefx,seanshpark/corefx,shimingsg/corefx,richlander/corefx,the-dwyer/corefx,twsouthwick/corefx,nbarbettini/corefx,mmitche/corefx,nchikanov/corefx,seanshpark/corefx,jlin177/corefx,Jiayili1/corefx,cydhaselton/corefx,tijoytom/corefx,cydhaselton/corefx,mazong1123/corefx,krk/corefx,fgreinacher/corefx,rubo/corefx,zhenlan/corefx,krk/corefx,ericstj/corefx,yizhang82/corefx,jlin177/corefx,Jiayili1/corefx,tijoytom/corefx,DnlHarvey/corefx,ravimeda/corefx,MaggieTsang/corefx,stone-li/corefx,cydhaselton/corefx,Ermiar/corefx,krk/corefx,wtgodbe/corefx,shimingsg/corefx,Ermiar/corefx,nchikanov/corefx,shimingsg/corefx,Ermiar/corefx,zhenlan/corefx,seanshpark/corefx,krk/corefx,twsouthwick/corefx,ptoonen/corefx,DnlHarvey/corefx,zhenlan/corefx,BrennanConroy/corefx,twsouthwick/corefx,nchikanov/corefx,Jiayili1/corefx,axelheer/corefx,Ermiar/corefx,the-dwyer/corefx,the-dwyer/corefx,parjong/corefx,stone-li/corefx,the-dwyer/corefx,rubo/corefx,nbarbettini/corefx,mazong1123/corefx,twsouthwick/corefx,zhenlan/corefx,mmitche/corefx,mazong1123/corefx,wtgodbe/corefx,shimingsg/corefx,mmitche/corefx,stone-li/corefx,parjong/corefx,ericstj/corefx,ptoonen/corefx,DnlHarvey/corefx,ViktorHofer/corefx,BrennanConroy/corefx,wtgodbe/corefx,stone-li/corefx,tijoytom/corefx,axelheer/corefx,mmitche/corefx,ptoonen/corefx,parjong/corefx,MaggieTsang/corefx,jlin177/corefx,cydhaselton/corefx,JosephTremoulet/corefx,mmitche/corefx,stone-li/corefx,yizhang82/corefx,ViktorHofer/corefx,zhenlan/corefx,ptoonen/corefx,tijoytom/corefx,cydhaselton/corefx,nchikanov/corefx,twsouthwick/corefx,rubo/corefx,Jiayili1/corefx,seanshpark/corefx,seanshpark/corefx,axelheer/corefx,rubo/corefx,mmitche/corefx,nbarbettini/corefx,the-dwyer/corefx,Jiayili1/corefx,JosephTremoulet/corefx,ericstj/corefx,DnlHarvey/corefx,mazong1123/corefx,tijoytom/corefx,tijoytom/corefx,ViktorHofer/corefx,ravimeda/corefx,krk/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,richlander/corefx,ravimeda/corefx,richlander/corefx,DnlHarvey/corefx,ravimeda/corefx,twsouthwick/corefx,nchikanov/corefx,ericstj/corefx,nbarbettini/corefx
src/Common/tests/System/IO/TempFile.cs
src/Common/tests/System/IO/TempFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using Xunit; namespace System.IO { /// <summary> /// Represents a temporary file. Creating an instance creates a file at the specified path, /// and disposing the instance deletes the file. /// </summary> public sealed class TempFile : IDisposable { /// <summary>Gets the created file's path.</summary> public string Path { get; } public TempFile(string path, long length = 0) : this(path, length > -1 ? new byte[length] : null) { } public TempFile(string path, byte[] data) { Path = path; if (data != null) { File.WriteAllBytes(path, data); } } ~TempFile() => DeleteFile(); public static TempFile Create(byte[] bytes, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) { return new TempFile(GetFilePath(memberName, lineNumber), bytes); } public static TempFile Create(long length = -1, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) { return new TempFile(GetFilePath(memberName, lineNumber), length); } public void AssertExists() => Assert.True(File.Exists(Path)); public string ReadAllText() => File.ReadAllText(Path); public void Dispose() { GC.SuppressFinalize(this); DeleteFile(); } private void DeleteFile() { try { File.Delete(Path); } catch { /* Ignore exceptions on disposal paths */ } } private static string GetFilePath(string memberName, int lineNumber) { string file = $"{IO.Path.GetRandomFileName()}_{memberName}_{lineNumber}"; return IO.Path.Combine(IO.Path.GetTempPath(), file); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using Xunit; namespace System.IO { /// <summary> /// Represents a temporary file. Creating an instance creates a file at the specified path, /// and disposing the instance deletes the file. /// </summary> public sealed class TempFile : IDisposable { /// <summary>Gets the created file's path.</summary> public string Path { get; } public TempFile(string path, long length = 0) { Path = path; if (length > -1) File.WriteAllBytes(path, new byte[length]); } ~TempFile() { DeleteFile(); } public static TempFile Create(long length = -1, [CallerMemberName] string memberName = null, [CallerLineNumber] int lineNumber = 0) { string file = string.Format("{0}_{1}_{2}", System.IO.Path.GetRandomFileName(), memberName, lineNumber); string path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), file); return new TempFile(path, length); } public void AssertExists() { Assert.True(File.Exists(Path)); } public string ReadAllText() { return File.ReadAllText(Path); } public void Dispose() { GC.SuppressFinalize(this); DeleteFile(); } private void DeleteFile() { try { File.Delete(Path); } catch { /* Ignore exceptions on disposal paths */ } } } }
mit
C#
a49f8de84690665228cbcfa575903661a0ddb6ba
Fix compilation
criteo/zipkin4net,criteo/zipkin4net
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs
zipkin4net-aspnetcore/Criteo.Profiling.Tracing.Middleware/TracingMiddleware.cs
using System; using Microsoft.AspNetCore.Builder; using Criteo.Profiling.Tracing; using Criteo.Profiling.Tracing.Utils; namespace Criteo.Profiling.Tracing.Middleware { public static class TracingMiddleware { public static void UseTracing(this IApplicationBuilder app, string serviceName) { var extractor = new Middleware.ZipkinHttpTraceExtractor(); app.Use(async (context, next) => { Trace trace; if (!extractor.TryExtract(context.Request.Headers, out trace)) { trace = Trace.Create(); } Trace.Current = trace; using (new ServerTrace(serviceName, context.Request.Method)) { await TraceHelper.TracedActionAsync(next()); } }); } } }
using System; using Microsoft.AspNetCore.Builder; using Criteo.Profiling.Tracing; namespace Criteo.Profiling.Tracing.Middleware { public static class TracingMiddleware { public static void UseTracing(this IApplicationBuilder app, string serviceName) { var extractor = new Middleware.ZipkinHttpTraceExtractor(); app.Use(async (context, next) => { Trace trace; if (!extractor.TryExtract(context.Request.Headers, out trace)) { trace = Trace.Create(); } Trace.Current = trace; using (new ServerTrace(serviceName, context.Request.Method)) { await TraceHelper.TracedActionAsync(next()); } }); } } }
apache-2.0
C#
fde41e6b97093e31966dd8d3a9d219e56b92c6db
Fix the build
github/VisualStudio,HeadhunterXamd/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio/Settings.cs
src/GitHub.VisualStudio/Settings.cs
// Guids.cs // MUST match guids.h using Microsoft.TeamFoundation.Controls; using System; namespace GitHub.VisualStudio { static class GuidList { public const string guidGitHubPkgString = "c3d3dc68-c977-411f-b3e8-03b0dccf7dfc"; public const string guidGitHubCmdSetString = "c4c91892-8881-4588-a5d9-b41e8f540f5a"; public const string guidGitHubToolbarCmdSetString = "C5F1193E-F300-41B3-B4C4-5A703DD3C1C6"; public const string guidContextMenuSetString = "31057D08-8C3C-4C5B-9F91-8682EA08EC27"; public static readonly Guid guidGitHubCmdSet = new Guid(guidGitHubCmdSetString); public static readonly Guid guidGitHubToolbarCmdSet = new Guid(guidGitHubToolbarCmdSetString); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Justification = "Already used in https://github.com/github/VisualStudio/pull/156")] public static readonly Guid guidContextMenuSet = new Guid(guidContextMenuSetString); } static class NavigationItemPriority { public const int PullRequests = TeamExplorerNavigationItemPriority.GitCommits - 1; public const int Wiki = TeamExplorerNavigationItemPriority.Settings - 1; public const int Pulse = Wiki - 3; public const int Graphs = Wiki - 2; public const int Issues = Wiki - 1; } }
// Guids.cs // MUST match guids.h using Microsoft.TeamFoundation.Controls; using System; namespace GitHub.VisualStudio { static class GuidList { public const string guidGitHubPkgString = "c3d3dc68-c977-411f-b3e8-03b0dccf7dfc"; public const string guidGitHubCmdSetString = "c4c91892-8881-4588-a5d9-b41e8f540f5a"; public const string guidGitHubToolbarCmdSetString = "C5F1193E-F300-41B3-B4C4-5A703DD3C1C6"; public const string guidContextMenuSetString = "31057D08-8C3C-4C5B-9F91-8682EA08EC27"; public static readonly Guid guidGitHubCmdSet = new Guid(guidGitHubCmdSetString); public static readonly Guid guidGitHubToolbarCmdSet = new Guid(guidGitHubToolbarCmdSetString); public static readonly Guid guidContextMenuSet = new Guid(guidContextMenuSetString); } static class NavigationItemPriority { public const int PullRequests = TeamExplorerNavigationItemPriority.GitCommits - 1; public const int Wiki = TeamExplorerNavigationItemPriority.Settings - 1; public const int Pulse = Wiki - 3; public const int Graphs = Wiki - 2; public const int Issues = Wiki - 1; } }
mit
C#
c5ed0f7c6765c79b38edf1d0f83cecb126df1b1f
Adjust validation in AddRockLib extension method
RockFramework/RockLib.Configuration
RockLibConfigurationBuilderExtensions.cs
RockLibConfigurationBuilderExtensions.cs
using System; using Microsoft.Extensions.Configuration; namespace RockLib.Configuration { public static class RockLibConfigurationBuilderExtensions { /// <summary> /// /// </summary> /// <param name="builder"></param> /// <returns></returns> public static IConfigurationBuilder AddRockLib(this IConfigurationBuilder builder) { return builder.AddRockLib("rocklib.config.json"); } /// <summary> /// /// </summary> /// <param name="builder">Non-null instance of an IConfigurationBuilder</param> /// <param name="rockLibConfigJson">Required value which provides the name of the file to pull the configuration values from</param> /// <exception cref="NullReferenceException">Will be thrown if the value for rockLibConfigJson is null or empty</exception> /// <exception cref="FileNotFoundException">Will be thrown if the provided file name is not found in the runtime folder</exception> /// <returns>A built instance of IConfigurationbuilder</returns> public static IConfigurationBuilder AddRockLib(this IConfigurationBuilder builder, string rockLibConfigJson) { if (string.IsNullOrEmpty(jsonConfigPath)) throw new ArgumentNullException(nameof(builder)); if (string.IsNullOrEmpty(jsonConfigPath)) throw new ArgumentException($"'{nameof(jsonConfigPath)}' must be a non-empty string.", nameof(jsonConfigPath)); // we want the optional value to be false so that it will throw a runtime exception if the file is not found // if this is set to true no exception is throw and no config values are found/returned. var builtBuilder = builder .AddJsonFile(jsonConfigPath, optional: false); return builtBuilder; } } }
 using System; using System.IO; using Microsoft.Extensions.Configuration; namespace RockLib.Configuration { public static class RockLibConfigurationBuilderExtensions { /// <summary> /// /// </summary> /// <param name="builder"></param> /// <returns></returns> public static IConfigurationBuilder AddRockLib(this IConfigurationBuilder builder) { return builder.AddRockLib("rocklib.config.json"); } /// <summary> /// /// </summary> /// <param name="builder">Non-null instance of an IConfigurationBuilder</param> /// <param name="rockLibConfigJson">Required value which provides the name of the file to pull the configuration values from</param> /// <exception cref="NullReferenceException">Will be thrown if the value for rockLibConfigJson is null or empty</exception> /// <exception cref="FileNotFoundException">Will be thrown if the provided file name is not found in the runtime folder</exception> /// <returns>A built instance of IConfigurationbuilder</returns> public static IConfigurationBuilder AddRockLib(this IConfigurationBuilder builder, string rockLibConfigJson) { if (string.IsNullOrEmpty(rockLibConfigJson)) { throw new NullReferenceException($"You attempted to provide a null or empty value for the configuration file name, this is not allowed. Make sure you provide a valid file name."); } var fullFilePath = Path.Combine(Directory.GetCurrentDirectory(), rockLibConfigJson); if (!File.Exists(fullFilePath)) { throw new FileNotFoundException(rockLibConfigJson, $"Unable to use the configuration file at location {rockLibConfigJson} as it was not found. Please make sure you have included the configuration file in your project and that is being deployed at runtime."); } // we want the optional value to be false so that it will throw a runtime exception if the file is not found // if this is set to true no exception is throw and no config values are found/returned. var builtBuilder = builder .AddJsonFile(jsonConfigPath, optional: false); return builtBuilder; } } }
mit
C#
b35b5879741aa1a43734d1df1f6f12918ec6bb11
Use existing bool menu item helper
unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl
SlicerConfiguration/SliceSettingsOverflowMenu.cs
SlicerConfiguration/SliceSettingsOverflowMenu.cs
/* Copyright (c) 2018, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 OWNER 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Linq; using MatterHackers.Agg; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PartPreviewWindow; namespace MatterHackers.MatterControl.SlicerConfiguration { public class SliceSettingsOverflowMenu : OverflowMenuButton { public SliceSettingsOverflowMenu(PrinterConfig printer, ThemeConfig theme) : base(theme) { this.VAnchor = VAnchor.Fit | VAnchor.Center; this.AlignToRightEdge = true; this.Name = "Slice Settings Overflow Menu"; var popupMenu = new PopupMenu(ApplicationController.Instance.Theme); popupMenu.CreateMenuItem("View Just My Settings".Localize()).Click += (s, e) => { this.TabView.FilterToOverrides(); }; popupMenu.CreateHorizontalLine(); popupMenu.CreateBoolMenuItem( "Show Help".Localize(), () => ApplicationController.Instance.ShowHelpControls, (value) => ApplicationController.Instance.ShowHelpControls = value); this.PopupContent = popupMenu; } // On load walk back to the first ancestor with background colors and copy public override void OnLoad(EventArgs args) { var firstBackgroundColor = this.Parents<GuiWidget>().Where(p => p.BackgroundColor.Alpha0To1 == 1).FirstOrDefault()?.BackgroundColor; this.BackgroundColor = firstBackgroundColor ?? Color.Transparent; base.OnLoad(args); } public SliceSettingsTabView TabView { get; internal set; } } }
/* Copyright (c) 2017, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 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 OWNER 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System; using System.Linq; using MatterHackers.Agg; using MatterHackers.Agg.Platform; using MatterHackers.Agg.UI; using MatterHackers.Localizations; using MatterHackers.MatterControl.PartPreviewWindow; namespace MatterHackers.MatterControl.SlicerConfiguration { public class SliceSettingsOverflowMenu : OverflowMenuButton { // showHelpControls public SliceSettingsOverflowMenu(PrinterConfig printer, ThemeConfig theme) : base(theme) { this.VAnchor = VAnchor.Fit | VAnchor.Center; this.AlignToRightEdge = true; this.Name = "Slice Settings Overflow Menu"; var popupMenu = new PopupMenu(ApplicationController.Instance.Theme); var checkedIcon = AggContext.StaticData.LoadIcon("fa-check_16.png"); popupMenu.CreateMenuItem("View Just My Settings".Localize()).Click += (s, e) => { this.TabView.FilterToOverrides(); }; popupMenu.CreateHorizontalLine(); var icon = (ApplicationController.Instance.ShowHelpControls) ? checkedIcon : null; popupMenu.CreateMenuItem("Show Help".Localize(), icon).Click += (s, e) => { ApplicationController.Instance.ShowHelpControls = !ApplicationController.Instance.ShowHelpControls; }; this.PopupContent = popupMenu; } public PopupMenu PopupMenu { get; } // On load walk back to the first ancestor with background colors and copy public override void OnLoad(EventArgs args) { var firstBackgroundColor = this.Parents<GuiWidget>().Where(p => p.BackgroundColor.Alpha0To1 == 1).FirstOrDefault()?.BackgroundColor; this.BackgroundColor = firstBackgroundColor ?? Color.Transparent; base.OnLoad(args); } public SliceSettingsTabView TabView { get; internal set; } } }
bsd-2-clause
C#
de982563f0e76980524e6534e6a9fcda41c1611f
Fix error when using JSON serializer and converting integer types to smallest possible type.
anakic/Jot
Thingie.Tracking/Serialization/JsonSerializer.cs
Thingie.Tracking/Serialization/JsonSerializer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Thingie.Tracking.Serialization { public class JsonSerializer : ISerializer { JsonSerializerSettings _serializationSettings = new JsonSerializerSettings() { TypeNameHandling=TypeNameHandling.Objects }; public byte[] Serialize(object obj) { return GetBytes(JsonConvert.SerializeObject(obj, Formatting.None, _serializationSettings)); } public object Deserialize(byte[] bytes) { object obj = JsonConvert.DeserializeObject(GetString(bytes), _serializationSettings); //HACK: //JSON.NET deserializes all Int values as Int64 because it's less likely to overflow. //This is a problem because reflection throws an exception when setting the Int64 value to a smaller //type (byte/Int16/Int32) property. The reverse (i.e. Int32 value -> Int64 property)is not a problem. //Because of this I convert integer values to the smallest possible type. if (obj is Int64) { Int64 value = (Int64)obj; if (value >= 0 && value <= byte.MaxValue) obj = Convert.ToByte(obj); else if (Math.Abs(value) <= Int16.MaxValue) obj = Convert.ToInt16(obj); else if (Math.Abs(value) <= Int32.MaxValue) obj = Convert.ToInt32(obj); } return obj; } static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace Thingie.Tracking.Serialization { public class JsonSerializer : ISerializer { JsonSerializerSettings _serializationSettings = new JsonSerializerSettings() { TypeNameHandling=TypeNameHandling.Objects }; public byte[] Serialize(object obj) { return GetBytes(JsonConvert.SerializeObject(obj, Formatting.None, _serializationSettings)); } public object Deserialize(byte[] bytes) { object obj = JsonConvert.DeserializeObject(GetString(bytes), _serializationSettings); //HACK: //JSON.NET deserializes all Int values as Int64 because it's less likely to overflow. //This is a problem because reflection throws an exception when setting the Int64 value to a smaller //type (byte/Int16/Int32) property. The reverse (i.e. Int32 value -> Int64 property)is not a problem. //Because of this I convert integer values to the smallest possible type. if (obj is Int64) { Int64 value = (Int64)obj; if (value >= 0 && value < byte.MaxValue) obj = Convert.ToByte(obj); else if (Math.Abs(value) < Int16.MaxValue) obj = Convert.ToInt16(obj); else if (Math.Abs(value) < Int32.MaxValue) obj = Convert.ToInt32(obj); } return obj; } static byte[] GetBytes(string str) { byte[] bytes = new byte[str.Length * sizeof(char)]; System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } static string GetString(byte[] bytes) { char[] chars = new char[bytes.Length / sizeof(char)]; System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length); return new string(chars); } } }
mit
C#
4dbe7398961fb2c584c413cd74b5aa6ab142e6cb
Bump to 0.6.0
dancol90/mi-360
Source/mi-360/Properties/AssemblyInfo.cs
Source/mi-360/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Le informazioni generali relative a un assembly sono controllate dal seguente // set di attributi. Modificare i valori di questi attributi per modificare le informazioni // associate a un assembly. [assembly: AssemblyTitle("mi-360")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniele Colanardi")] [assembly: AssemblyProduct("mi-360")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili // ai componenti COM. Se è necessario accedere a un tipo in questo assembly da // COM, impostare su true l'attributo ComVisible per tale tipo. [assembly: ComVisible(false)] // Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi [assembly: Guid("885b11ae-354c-4690-a0a5-e9a82f51f262")] // Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: // // Versione principale // Versione secondaria // Numero di build // Revisione // // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build // usando l'asterisco '*' come illustrato di seguito: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.6.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Le informazioni generali relative a un assembly sono controllate dal seguente // set di attributi. Modificare i valori di questi attributi per modificare le informazioni // associate a un assembly. [assembly: AssemblyTitle("mi-360")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniele Colanardi")] [assembly: AssemblyProduct("mi-360")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili // ai componenti COM. Se è necessario accedere a un tipo in questo assembly da // COM, impostare su true l'attributo ComVisible per tale tipo. [assembly: ComVisible(false)] // Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi [assembly: Guid("885b11ae-354c-4690-a0a5-e9a82f51f262")] // Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: // // Versione principale // Versione secondaria // Numero di build // Revisione // // È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build // usando l'asterisco '*' come illustrato di seguito: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.5.2")]
bsd-3-clause
C#
46bde1d73cd9c1736e78ae5a7f99ddf11bbb8116
Use the configuration with fallback for snapshot store (#112)
Aaronontheweb/Akka.Persistence.SqlServer,akkadotnet/Akka.Persistence.SqlServer,Aaronontheweb/Akka.Persistence.SqlServer,akkadotnet/Akka.Persistence.SqlServer
src/Akka.Persistence.SqlServer/Snapshot/SqlServerSnapshotStore.cs
src/Akka.Persistence.SqlServer/Snapshot/SqlServerSnapshotStore.cs
// ----------------------------------------------------------------------- // <copyright file="SqlServerSnapshotStore.cs" company="Akka.NET Project"> // Copyright (C) 2013 - 2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> // ----------------------------------------------------------------------- using System.Data.Common; using System.Data.SqlClient; using Akka.Configuration; using Akka.Persistence.Sql.Common.Snapshot; namespace Akka.Persistence.SqlServer.Snapshot { public class SqlServerSnapshotStore : SqlSnapshotStore { protected readonly SqlServerPersistence Extension = SqlServerPersistence.Get(Context.System); public SqlServerSnapshotStore(Config snapshotConfig) : base(snapshotConfig) { var config = snapshotConfig.WithFallback(Extension.DefaultSnapshotConfig); QueryExecutor = new SqlServerQueryExecutor(new QueryConfiguration( schemaName: config.GetString("schema-name"), snapshotTableName: config.GetString("table-name"), persistenceIdColumnName: "PersistenceId", sequenceNrColumnName: "SequenceNr", payloadColumnName: "Snapshot", manifestColumnName: "Manifest", timestampColumnName: "Timestamp", serializerIdColumnName: "SerializerId", timeout: config.GetTimeSpan("connection-timeout"), defaultSerializer: config.GetString("serializer"), useSequentialAccess: config.GetBoolean("sequential-access")), Context.System.Serialization); } public override ISnapshotQueryExecutor QueryExecutor { get; } protected override DbConnection CreateDbConnection(string connectionString) { return new SqlConnection(connectionString); } } }
// ----------------------------------------------------------------------- // <copyright file="SqlServerSnapshotStore.cs" company="Akka.NET Project"> // Copyright (C) 2013 - 2019 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> // ----------------------------------------------------------------------- using System.Data.Common; using System.Data.SqlClient; using Akka.Configuration; using Akka.Persistence.Sql.Common.Snapshot; namespace Akka.Persistence.SqlServer.Snapshot { public class SqlServerSnapshotStore : SqlSnapshotStore { protected readonly SqlServerPersistence Extension = SqlServerPersistence.Get(Context.System); public SqlServerSnapshotStore(Config config) : base(config) { var sqlConfig = config.WithFallback(Extension.DefaultSnapshotConfig); QueryExecutor = new SqlServerQueryExecutor(new QueryConfiguration( config.GetString("schema-name"), config.GetString("table-name"), "PersistenceId", "SequenceNr", "Snapshot", "Manifest", "Timestamp", "SerializerId", sqlConfig.GetTimeSpan("connection-timeout"), config.GetString("serializer"), config.GetBoolean("sequential-access")), Context.System.Serialization); } public override ISnapshotQueryExecutor QueryExecutor { get; } protected override DbConnection CreateDbConnection(string connectionString) { return new SqlConnection(connectionString); } } }
apache-2.0
C#
a4ba451c95a32c0bfe3f931e9dd89e6e0ef2666a
fix merge issue
dotnetgeek/dng.Syndication,dotnetgeek/dng.Syndication
src/Enclosure.cs
src/Enclosure.cs
namespace dng.Syndication { public class Enclosure { public Enclosure() { Length = 0; } public string Url { get; set; } public int Length { get; set; } public string MediaType { get; set; } } }
namespace dng.Syndication { public class Enclosure { <<<<<<< HEAD public Enclosure() { Length = 0; } ======= >>>>>>> 173348ac0538654dbb2c584a392fa3ed4b52d57d public string Url { get; set; } public int Length { get; set; } public string MediaType { get; set; } } }
mit
C#
10c2cd1bc338053bf7fcc1ee3e184d11a432dfd0
revert of migrating deserialiser
LykkeCity/MT,LykkeCity/MT,LykkeCity/MT
src/MarginTrading.Common/RabbitMq/DeserializerWithErrorLogging.cs
src/MarginTrading.Common/RabbitMq/DeserializerWithErrorLogging.cs
using System; using System.Text; using Common.Log; using Lykke.RabbitMqBroker.Subscriber; namespace MarginTrading.Common.RabbitMq { public class DeserializerWithErrorLogging<TMessage> : IMessageDeserializer<TMessage> { private readonly ILog _log; private readonly IMessageDeserializer<TMessage> _baseDeserializer; public DeserializerWithErrorLogging(ILog log, IMessageDeserializer<TMessage> baseDeserializer = null) { _log = log; _baseDeserializer = baseDeserializer ?? new JsonMessageDeserializer<TMessage>(); } public TMessage Deserialize(byte[] data) { try { return _baseDeserializer.Deserialize(data); } catch (Exception e) { var rawObject = Encoding.UTF8.GetString(data); _log.WriteWarningAsync("RabbitMqSubscriber", "Deserialization", typeof(TMessage).FullName, $"Deserializing: {e.Message}. {Environment.NewLine}Raw message: [{rawObject}]"); throw; } } } }
using System; using System.Text; using Common.Log; using Lykke.RabbitMqBroker.Subscriber; namespace MarginTrading.Common.RabbitMq { public class DeserializerWithErrorLogging<TMessage> : IMessageDeserializer<TMessage> { private readonly ILog _log; private readonly IMessageDeserializer<TMessage> _baseDeserializer; public DeserializerWithErrorLogging(ILog log, IMessageDeserializer<TMessage> baseDeserializer = null) { _log = log; _baseDeserializer = baseDeserializer ?? FormatMigrationMessageDeserializerFactory.JsonToMessagePack<TMessage>(); } public TMessage Deserialize(byte[] data) { try { return _baseDeserializer.Deserialize(data); } catch (Exception e) { var rawObject = Encoding.UTF8.GetString(data); _log.WriteWarningAsync("RabbitMqSubscriber", "Deserialization", typeof(TMessage).FullName, $"Deserializing: {e.Message}. {Environment.NewLine}Raw message: [{rawObject}]"); throw; } } } }
mit
C#
002540193d2419f744e7b421da878198657a573a
Move field
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/AboutViewModel.cs
WalletWasabi.Fluent/ViewModels/AboutViewModel.cs
using System; using System.IO; using System.Reactive; using System.Reactive.Linq; using JetBrains.Annotations; using ReactiveUI; using WalletWasabi.Fluent.ViewModels.Navigation; using WalletWasabi.WebClients.Wasabi; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Fluent.ViewModels { public class AboutViewModel : RoutableViewModel { private string _currentBackendMajorVersion; public AboutViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.HomeScreen) { OpenBrowserCommand = ReactiveCommand.CreateFromTask<string>(IoHelpers.OpenBrowserAsync); CurrentBackendMajorVersion = WasabiClient.ApiVersion.ToString(); OpenBrowserCommand.ThrownExceptions .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => Logger.LogError(ex)); } public ReactiveCommand<string, Unit> OpenBrowserCommand { get; } public Version ClientVersion { get; } = Constants.ClientVersion; public string BackendCompatibleVersions { get; } = Constants.ClientSupportBackendVersionText; public string CurrentBackendMajorVersion { get => _currentBackendMajorVersion; set => this.RaiseAndSetIfChanged(ref _currentBackendMajorVersion, value); } public Version BitcoinCoreVersion { get; } = Constants.BitcoinCoreVersion; public Version HwiVersion { get; } = Constants.HwiVersion; public string ClearnetLink { get; } = "https://wasabiwallet.io/"; public string TorLink { get; } = "http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion"; public string SourceCodeLink { get; } = "https://github.com/zkSNACKs/WalletWasabi/"; public string StatusPageLink { get; } = "https://stats.uptimerobot.com/YQqGyUL8A7"; public string UserSupportLink { get; } = "https://www.reddit.com/r/WasabiWallet/"; public string BugReportLink { get; } = "https://github.com/zkSNACKs/WalletWasabi/issues/"; public string FAQLink { get; } = "https://docs.wasabiwallet.io/FAQ/"; public string DocsLink { get; } = "https://docs.wasabiwallet.io/"; } }
using System; using System.IO; using System.Reactive; using System.Reactive.Linq; using JetBrains.Annotations; using ReactiveUI; using WalletWasabi.Fluent.ViewModels.Navigation; using WalletWasabi.WebClients.Wasabi; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Fluent.ViewModels { public class AboutViewModel : RoutableViewModel { public AboutViewModel(NavigationStateViewModel navigationState) : base(navigationState, NavigationTarget.HomeScreen) { OpenBrowserCommand = ReactiveCommand.CreateFromTask<string>(IoHelpers.OpenBrowserAsync); CurrentBackendMajorVersion = WasabiClient.ApiVersion.ToString(); OpenBrowserCommand.ThrownExceptions .ObserveOn(RxApp.TaskpoolScheduler) .Subscribe(ex => Logger.LogError(ex)); } public ReactiveCommand<string, Unit> OpenBrowserCommand { get; } public Version ClientVersion { get; } = Constants.ClientVersion; public string BackendCompatibleVersions { get; } = Constants.ClientSupportBackendVersionText; private string _currentBackendMajorVersion; public string CurrentBackendMajorVersion { get => _currentBackendMajorVersion; set => this.RaiseAndSetIfChanged(ref _currentBackendMajorVersion, value); } public Version BitcoinCoreVersion { get; } = Constants.BitcoinCoreVersion; public Version HwiVersion { get; } = Constants.HwiVersion; public string ClearnetLink { get; } = "https://wasabiwallet.io/"; public string TorLink { get; } = "http://wasabiukrxmkdgve5kynjztuovbg43uxcbcxn6y2okcrsg7gb6jdmbad.onion"; public string SourceCodeLink { get; } = "https://github.com/zkSNACKs/WalletWasabi/"; public string StatusPageLink { get; } = "https://stats.uptimerobot.com/YQqGyUL8A7"; public string UserSupportLink { get; } = "https://www.reddit.com/r/WasabiWallet/"; public string BugReportLink { get; } = "https://github.com/zkSNACKs/WalletWasabi/issues/"; public string FAQLink { get; } = "https://docs.wasabiwallet.io/FAQ/"; public string DocsLink { get; } = "https://docs.wasabiwallet.io/"; } }
mit
C#
e36bdaafaf7ac04b4fa8eb71a6e4e05f02eb5036
Remove dead line from autocomplete
kswoll/WootzJs,kswoll/WootzJs,x335/WootzJs,x335/WootzJs,x335/WootzJs,kswoll/WootzJs
WootzJs.Mvc/Views/AutocompleteTextBox.cs
WootzJs.Mvc/Views/AutocompleteTextBox.cs
using WootzJs.Web; namespace WootzJs.Mvc.Views { public class AutocompleteTextBox<T> : Control { private Control content; private Control overlay; private Element contentNode; private Element overlayContainer; private DropDownAlignment alignment; private T selectedItem; protected override Element CreateNode() { contentNode = Browser.Document.CreateElement("input"); contentNode.SetAttribute("type", "text"); contentNode.Style.Height = "100%"; overlayContainer = Browser.Document.CreateElement("div"); overlayContainer.Style.Position = "absolute"; overlayContainer.Style.Display = "none"; overlayContainer.AppendChild(overlay.Node); Add(overlay); var overlayAnchor = Browser.Document.CreateElement("div"); overlayAnchor.Style.Position = "relative"; overlayAnchor.AppendChild(overlayContainer); var result = Browser.Document.CreateElement("div"); result.AppendChild(contentNode); result.AppendChild(overlayAnchor); return result; } } }
using WootzJs.Web; namespace WootzJs.Mvc.Views { public class AutocompleteTextBox<T> : Control { private Control content; private Control overlay; private Element contentNode; private Element overlayContainer; private DropDownAlignment alignment; private T selectedItem; protected override Element CreateNode() { contentNode = Browser.Document.CreateElement("input"); contentNode.SetAttribute("type", "text"); contentNode.Style.Height = "100%"; var dropdown = Browser.Document.CreateElement(""); overlayContainer = Browser.Document.CreateElement("div"); overlayContainer.Style.Position = "absolute"; overlayContainer.Style.Display = "none"; overlayContainer.AppendChild(overlay.Node); Add(overlay); var overlayAnchor = Browser.Document.CreateElement("div"); overlayAnchor.Style.Position = "relative"; overlayAnchor.AppendChild(overlayContainer); var result = Browser.Document.CreateElement("div"); result.AppendChild(contentNode); result.AppendChild(overlayAnchor); return result; } } }
mit
C#
0450b700bfe8ea345e0139cc3f4eb3010b184b01
Add order after MoveTypeToFile
weltkante/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,stephentoub/roslyn,nguerrera/roslyn,jmarolf/roslyn,heejaechang/roslyn,aelij/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,gafter/roslyn,wvdd007/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,agocke/roslyn,panopticoncentral/roslyn,diryboy/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,gafter/roslyn,davkean/roslyn,AlekseyTs/roslyn,sharwell/roslyn,genlu/roslyn,reaction1989/roslyn,agocke/roslyn,physhi/roslyn,brettfo/roslyn,davkean/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,eriawan/roslyn,weltkante/roslyn,bartdesmet/roslyn,reaction1989/roslyn,abock/roslyn,diryboy/roslyn,nguerrera/roslyn,brettfo/roslyn,jmarolf/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,abock/roslyn,KevinRansom/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,mavasani/roslyn,aelij/roslyn,ErikSchierboom/roslyn,abock/roslyn,AlekseyTs/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,physhi/roslyn,stephentoub/roslyn,physhi/roslyn,reaction1989/roslyn,sharwell/roslyn,KevinRansom/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,aelij/roslyn,sharwell/roslyn,stephentoub/roslyn,brettfo/roslyn,swaroop-sridhar/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,weltkante/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,genlu/roslyn,agocke/roslyn,heejaechang/roslyn,heejaechang/roslyn,dotnet/roslyn,genlu/roslyn,tmat/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn
src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceCodeActionProvider.cs
src/Features/Core/Portable/MoveToNamespace/MoveToNamespaceCodeActionProvider.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.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MoveToNamespace { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.MoveToNamespace), Shared] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.SyncNamespace)] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.MoveTypeToFile)] internal class MoveToNamespaceCodeActionProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var service = context.Document.GetLanguageService<AbstractMoveToNamespaceService>(); var actions = await service.GetCodeActionsAsync(context.Document, context.Span, context.CancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
// 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.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.MoveToNamespace { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.MoveToNamespace), Shared] [ExtensionOrder(After = PredefinedCodeRefactoringProviderNames.SyncNamespace)] internal class MoveToNamespaceCodeActionProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var service = context.Document.GetLanguageService<AbstractMoveToNamespaceService>(); var actions = await service.GetCodeActionsAsync(context.Document, context.Span, context.CancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
mit
C#
00bf59111cf07c9145993fde5f8c31bfc4c05b59
Update ConductorBaseWithActiveItem.cs
tibel/Caliburn.Light
src/Caliburn.Light.Core/ViewModel/ConductorBaseWithActiveItem.cs
src/Caliburn.Light.Core/ViewModel/ConductorBaseWithActiveItem.cs
using System.Collections.Generic; namespace Caliburn.Light { /// <summary> /// A base class for various implementations of <see cref="IConductor"/> that maintain an active item. /// </summary> /// <typeparam name="T">The type that is being conducted.</typeparam> public abstract class ConductorBaseWithActiveItem<T> : ConductorBase<T>, IConductActiveItem where T : class { private T _activeItem; /// <summary> /// The currently active item. /// </summary> public T ActiveItem { get { return _activeItem; } set { ActivateItem(value); } } object IHaveActiveItem.ActiveItem { get { return ActiveItem; } } /// <summary> /// Changes the active item. /// </summary> /// <param name="newItem">The new item to activate.</param> /// <param name="closePrevious">Indicates whether or not to close the previous active item.</param> protected virtual void ChangeActiveItem(T newItem, bool closePrevious) { if (EqualityComparer<T>.Default.Equals(_activeItem, newItem)) return; if (_activeItem is IDeactivate deactivator) deactivator.Deactivate(closePrevious); newItem = EnsureItem(newItem); if (IsActive && newItem is IActivate activator) activator.Activate(); SetProperty(ref _activeItem, newItem, nameof(ActiveItem)); OnActivationProcessed(_activeItem, true); } } }
using System.Collections.Generic; namespace Caliburn.Light { /// <summary> /// A base class for various implementations of <see cref="IConductor"/> that maintain an active item. /// </summary> /// <typeparam name="T">The type that is being conducted.</typeparam> public abstract class ConductorBaseWithActiveItem<T> : ConductorBase<T>, IConductActiveItem where T : class { private T _activeItem; /// <summary> /// The currently active item. /// </summary> public T ActiveItem { get { return _activeItem; } set { ActivateItem(value); } } /// <summary> /// The currently active item. /// </summary> /// <value></value> object IHaveActiveItem.ActiveItem { get { return ActiveItem; } } /// <summary> /// Changes the active item. /// </summary> /// <param name="newItem">The new item to activate.</param> /// <param name="closePrevious">Indicates whether or not to close the previous active item.</param> protected virtual void ChangeActiveItem(T newItem, bool closePrevious) { if (EqualityComparer<T>.Default.Equals(_activeItem, newItem)) return; if (_activeItem is IDeactivate deactivator) deactivator.Deactivate(closePrevious); newItem = EnsureItem(newItem); if (IsActive && newItem is IActivate activator) activator.Activate(); SetProperty(ref _activeItem, newItem, nameof(ActiveItem)); OnActivationProcessed(_activeItem, true); } } }
mit
C#
25063dec8db055d39f274c84e5809e0ca16fb652
Change ListPictures.cshtml
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListPictures.cshtml
AstroPhotoGallery/AstroPhotoGallery/Views/Home/ListPictures.cshtml
@model List<AstroPhotoGallery.Models.Picture> @{ ViewBag.Title = "List Pictures"; } <div class="container"> <h2>@TempData["CategoryName"]</h2> <div class="row"> @foreach (var picture in Model) { <div class="row"> <div class="col-sm-12"> <div class="well col-sm-4"> <h3>@Html.ActionLink(@picture.PicTitle, "Details", "Picture", new { @id = picture.Id }, null)</h3> <a target="_blank" href="@Url.Content(picture.ImagePath)"> <img class="thumbnail img-responsive" alt="Gallery photo" src="@Url.Content(picture.ImagePath)" /> </a> <div class="pull-left" style="word-wrap: break-word"> Uploader: @picture.PicUploader.FirstName @picture.PicUploader.LastName </div> <br /> <div class="pull-left"> Category: @picture.CategoryName </div> </div> <div class="col-sm-8"> <div style="word-wrap: break-word;"> @picture.PicDescription </div> <br /> <div class="pull-left"> Tags:&nbsp; @foreach (var tag in picture.Tags) { <span>@Html.ActionLink(tag.Name, "List", "Tag", new { @id = tag.Id }, new { @class = "btn btn-default btn-xs" })</span> } </div> </div> </div> </div> <br /> } </div> </div>
@model List<AstroPhotoGallery.Models.Picture> @{ ViewBag.Title = "List Pictures"; } <div class="container"> <h2>@TempData["CategoryName"]</h2> <div class="row"> @foreach (var picture in Model) { <div class="col-sm-6 text-center"> <article> <header> <h3> @Html.ActionLink(@picture.PicTitle, "Details", "Picture", new { @id = picture.Id }, null) </h3> </header> <div class="img-thumbnail"> <img src="@Url.Content(picture.ImagePath)" style="width: 360px" class="img-responsive img-rounded center-block" alt="Astro picture" /> </div> <p> <br /> <div style="word-wrap: break-word;"> @picture.PicDescription </div> </p> <footer> <small> Uploader: @picture.PicUploader.FirstName @picture.PicUploader.LastName </small> </footer> </article> </div> } </div> </div>
mit
C#
7bc0838440484129d6a1886b04d6e06ddeb82ad7
rename asteroids to objs
ad510/time-fields-game
Assets/Scripts/Manager.cs
Assets/Scripts/Manager.cs
using UnityEngine; using System.Collections.Generic; public class Manager : MonoBehaviour { public GameObject playerPrefab, asteroidPrefab, clockPrefab, fieldPrefab, propelPrefab; const float updateRate = 33; const float radius = 2000; const float clockRotSpd = Mathf.PI / 1000 * updateRate; const float propelSpd = 1 * updateRate; public static int level = 1; public static float timeScale = 1; public static Obj player; public static List<Obj> objs = new List<Obj>(); public static List<Obj> fields = new List<Obj>(); // Use this for initialization void Start() { Time.fixedDeltaTime = updateRate / 1000; LoadLevel(); } void LoadLevel() { if (player != null) { Destroy(player.go); foreach (Obj obj in objs) Destroy(obj.go); foreach (Obj field in fields) Destroy(field.go); objs.Clear(); fields.Clear(); } player = new Obj(Instantiate(playerPrefab), new Vector2(), new Vector2(), Mathf.PI / 2); fields.Add(player); switch (level) { case 1: objs.Add(new Obj(Instantiate(clockPrefab), new Vector2(-200, 0), new Vector2(), 0, clockRotSpd, true, true)); objs.Add(new Obj(Instantiate(clockPrefab), new Vector2(200, 0), new Vector2(), Mathf.PI, clockRotSpd, true, true)); break; case 2: objs.Add(new Obj(Instantiate(clockPrefab), new Vector2(200, 0), new Vector2(), 0, clockRotSpd, true)); objs.Add(new Obj(Instantiate(clockPrefab), new Vector2(400, 0), new Vector2(), 0, clockRotSpd, true)); break; } } // Update is called once per frame void Update() { if (Input.GetMouseButton(0)) player.rot = Mathf.Atan2(Input.mousePosition.y - Screen.height / 2, Input.mousePosition.x - Screen.width / 2); player.Draw(); foreach (Obj obj in objs) obj.Draw(); foreach (Obj field in fields) field.Draw(); } void FixedUpdate() { if (level == 1 && Mathf.Abs(objs[0].rot - objs[1].rot) < 0.1 || level == 2 && Vector2.Distance(objs[0].pos, objs[1].pos) < 100) { level++; LoadLevel(); } if (Input.GetMouseButton(0) && Random.value < 0.02f * updateRate) { objs.Add(new Obj(Instantiate(propelPrefab), player.pos, player.vel - propelSpd * new Vector2(Mathf.Cos(player.rot), Mathf.Sin(player.rot)) + Random.insideUnitCircle * propelSpd / 6, 0)); } foreach (Obj field in fields) field.prevPos = field.pos; foreach (Obj field in fields) if (field != player) field.UpdatePos(0); foreach (Obj obj in objs) obj.UpdatePos(0); timeScale = player.UpdatePos(Input.GetMouseButton(0) ? 0.2f : 0); } }
using UnityEngine; using System.Collections.Generic; public class Manager : MonoBehaviour { public GameObject playerPrefab, asteroidPrefab, clockPrefab, fieldPrefab, propelPrefab; const float updateRate = 33; const float radius = 2000; const float clockRotSpd = Mathf.PI / 1000 * updateRate; const float propelSpd = 1 * updateRate; public static int level = 1; public static float timeScale = 1; public static Obj player; public static List<Obj> asteroids = new List<Obj>(); public static List<Obj> fields = new List<Obj>(); // Use this for initialization void Start() { Time.fixedDeltaTime = updateRate / 1000; LoadLevel(); } void LoadLevel() { if (player != null) { Destroy(player.go); foreach (Obj asteroid in asteroids) Destroy(asteroid.go); foreach (Obj field in fields) Destroy(field.go); asteroids.Clear(); fields.Clear(); } player = new Obj(Instantiate(playerPrefab), new Vector2(), new Vector2(), Mathf.PI / 2); fields.Add(player); switch (level) { case 1: asteroids.Add(new Obj(Instantiate(clockPrefab), new Vector2(-200, 0), new Vector2(), 0, clockRotSpd, true, true)); asteroids.Add(new Obj(Instantiate(clockPrefab), new Vector2(200, 0), new Vector2(), Mathf.PI, clockRotSpd, true, true)); break; case 2: asteroids.Add(new Obj(Instantiate(clockPrefab), new Vector2(200, 0), new Vector2(), 0, clockRotSpd, true)); asteroids.Add(new Obj(Instantiate(clockPrefab), new Vector2(400, 0), new Vector2(), 0, clockRotSpd, true)); break; } } // Update is called once per frame void Update() { if (Input.GetMouseButton(0)) player.rot = Mathf.Atan2(Input.mousePosition.y - Screen.height / 2, Input.mousePosition.x - Screen.width / 2); player.Draw(); foreach (Obj asteroid in asteroids) asteroid.Draw(); foreach (Obj field in fields) field.Draw(); } void FixedUpdate() { if (level == 1 && Mathf.Abs(asteroids[0].rot - asteroids[1].rot) < 0.1 || level == 2 && Vector2.Distance(asteroids[0].pos, asteroids[1].pos) < 100) { level++; LoadLevel(); } if (Input.GetMouseButton(0) && Random.value < 0.02f * updateRate) { asteroids.Add(new Obj(Instantiate(propelPrefab), player.pos, player.vel - propelSpd * new Vector2(Mathf.Cos(player.rot), Mathf.Sin(player.rot)) + Random.insideUnitCircle * propelSpd / 6, 0)); } foreach (Obj field in fields) field.prevPos = field.pos; foreach (Obj field in fields) if (field != player) field.UpdatePos(0); foreach (Obj asteroid in asteroids) asteroid.UpdatePos(0); timeScale = player.UpdatePos(Input.GetMouseButton(0) ? 0.2f : 0); } }
cc0-1.0
C#
c9e04570ba4b708c909bcfcca5da26bf120a7bc7
Add Owin startup routing.
swegner/CareerPoll
CareerPoll.Web/Startup.cs
CareerPoll.Web/Startup.cs
using System.Web.Http; using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(CareerPoll.Web.Startup))] namespace CareerPoll.Web { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); } } }
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(CareerPoll.Web.Startup))] namespace CareerPoll.Web { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
mit
C#
d226d06b508fff46c6aa776eaa703a28f41a01b9
Update SampleService.cs
Fody/FodyAddinSamples,Fody/FodyAddinSamples
MimickSample/SampleService.cs
MimickSample/SampleService.cs
using System; using Mimick; namespace MimickSample { /// <summary> /// A service class which persists as a singleton within the framework. /// </summary> [Component] public class SampleService { [Value("{Message}")] string message; /// <summary> /// Gets the application name configured in the configuration class. /// </summary> [Value("{Application.Name}")] public string ApplicationName { get; set; } /// <summary> /// Gets the application ID configured in the configuration class. /// </summary> [Value("{Application.Id}")] public int ApplicationId { get; set; } /// <summary> /// Gets the internal constructor count. /// </summary> public int ConstructCount { get; private set; } /// <summary> /// Checks whether the provided argument falls within the bounds of a short value. /// </summary> /// <param name="data">The data.</param> public void CheckIsShortValue([Minimum(short.MinValue), Maximum(short.MaxValue)] int data) { } /// <summary> /// Checks whether the provided argument is not <c>null</c> or empty. /// </summary> /// <param name="str">The data.</param> public void CheckNotEmpty([NotEmpty] string str) { } /// <summary> /// Checks whether the provided argument is not <c>null</c>. /// </summary> /// <param name="data">The data.</param> public void CheckNotNull([NotNull] object data) { } /// <summary> /// Gets the message configured in the key-value configuration source. /// </summary> /// <returns></returns> public string GetMessage() => message; /// <summary> /// Invoked before the class constructor method body executes. /// </summary> [PreConstruct] void PreConstruct() => ConstructCount++; /// <summary> /// Invoked after the class constructor method body executes. /// </summary> [PostConstruct] void PostConstruct() => ConstructCount++; /// <summary> /// Throws an exception which should be consumed and ignored. /// </summary> /// <param name="ex">The exception.</param> /// <returns>The default value of an integer.</returns> [Suppress] public int ThrowAndIgnore(Exception ex) => throw ex; } }
using System; using Mimick; namespace MimickSample { /// <summary> /// A service class which persists as a singleton within the framework. /// </summary> [Component] public class SampleService { int count; [Value("{Message}")] string message; /// <summary> /// Gets the application name configured in the configuration class. /// </summary> [Value("{Application.Name}")] public string ApplicationName { get; set; } /// <summary> /// Gets the application ID configured in the configuration class. /// </summary> [Value("{Application.Id}")] public int ApplicationId { get; set; } /// <summary> /// Gets the internal constructor count. /// </summary> public int ConstructCount => count; /// <summary> /// Checks whether the provided argument falls within the bounds of a short value. /// </summary> /// <param name="data">The data.</param> public void CheckIsShortValue([Minimum(short.MinValue), Maximum(short.MaxValue)] int data) { } /// <summary> /// Checks whether the provided argument is not <c>null</c> or empty. /// </summary> /// <param name="str">The data.</param> public void CheckNotEmpty([NotEmpty] string str) { } /// <summary> /// Checks whether the provided argument is not <c>null</c>. /// </summary> /// <param name="data">The data.</param> public void CheckNotNull([NotNull] object data) { } /// <summary> /// Gets the message configured in the key-value configuration source. /// </summary> /// <returns></returns> public string GetMessage() => message; /// <summary> /// Invoked before the class constructor method body executes. /// </summary> [PreConstruct] void PreConstruct() => count++; /// <summary> /// Invoked after the class constructor method body executes. /// </summary> [PostConstruct] void PostConstruct() => count++; /// <summary> /// Throws an exception which should be consumed and ignored. /// </summary> /// <param name="ex">The exception.</param> /// <returns>The default value of an integer.</returns> [Suppress] public int ThrowAndIgnore(Exception ex) => throw ex; } }
mit
C#
803c016ec329dc96ee031cf2c413f906ea184104
update algorithm to allow for line loop resistance and reactance to be passed in as parameters.
GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA,GridProtectionAlliance/openXDA
Source/Libraries/FaultData/DataWriters/TreeProbabilityGenerator.cs
Source/Libraries/FaultData/DataWriters/TreeProbabilityGenerator.cs
using GSF.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FaultData.DataWriters { public class TreeProbabilityGenerator { public static XElement GetTreeProbability(AdoDataConnection connection, XElement element) { XElement returnElement = new XElement("span"); string faultType = (string)element.Attribute("faultType") ?? "AB"; string reactanceRatioString = (string)element.Attribute("reactanceRatio") ?? "1.0"; double reactanceRatio; if (!double.TryParse(reactanceRatioString, out reactanceRatio)) reactanceRatio = 1.0; reactanceRatio = Math.Abs(reactanceRatio); string distanceString = (string)element.Attribute("distance") ?? "-1.0"; double distance; if (!double.TryParse(distanceString, out distance)) distance = -1.0; string RsString = (string)element.Attribute("Rs") ?? "1.27"; double Rs; if (!double.TryParse(RsString, out Rs)) Rs = 1.27; string XsString = (string)element.Attribute("Xs") ?? ".31"; double Xs; if (!double.TryParse(XsString, out Xs)) Xs = .31; double lowToMediumBorder = (Rs * distance) / Math.Sqrt(Math.Pow((Xs * distance + 10), 2) + Math.Pow((Rs * distance), 2)); double mediumToHighBorder = (Rs * distance) / Math.Sqrt(Math.Pow((Xs * distance + 20), 2) + Math.Pow((Rs * distance), 2)); returnElement.Value = "Undetermined"; if (faultType.ToLower().Contains("n")) { if (reactanceRatio <= mediumToHighBorder) returnElement.Value = "High"; else if (reactanceRatio <= lowToMediumBorder && reactanceRatio >= mediumToHighBorder) returnElement.Value = "Medium"; else returnElement.Value = "Low"; } return returnElement; } } }
using GSF.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace FaultData.DataWriters { public class TreeProbabilityGenerator { public static XElement GetTreeProbability(AdoDataConnection connection, XElement element) { XElement returnElement = new XElement("span"); string faultType = (string)element.Attribute("faultType") ?? "AB"; double reactanceRatio = Convert.ToDouble((string)element.Attribute("reactanceRatio") ?? "-1.0"); reactanceRatio = Math.Abs(reactanceRatio); double distance = Convert.ToDouble((string)element.Attribute("distance") ?? "-1.0"); double lowToMediumBorder = (1.27 * distance) / Math.Sqrt(Math.Pow((.31 * distance + 10), 2) + Math.Pow((1.27 * distance), 2)); double mediumToHighBorder = (1.27 * distance) / Math.Sqrt(Math.Pow((.31 * distance + 20), 2) + Math.Pow((1.27 * distance), 2)); returnElement.Value = "Undetermined"; if (faultType.ToLower().Contains("n")) { if (reactanceRatio <= mediumToHighBorder) returnElement.Value = "High"; else if (reactanceRatio <= lowToMediumBorder && reactanceRatio >= mediumToHighBorder) returnElement.Value = "Medium"; else returnElement.Value = "Low"; } return returnElement; } } }
mit
C#
4e655da05b2313663147312678023f677a17a390
clean up
asipe/SupaCharge
src/SupaCharge.Core/ConfigurationWrapper/ConfigurationWrapper.cs
src/SupaCharge.Core/ConfigurationWrapper/ConfigurationWrapper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using SupaCharge.Core.Converter; namespace SupaCharge.Core.ConfigurationWrapper { public class ConfigurationWrapper { public bool Contains(string key) { return (ConfigurationManager.AppSettings[key] != null); } public T Get<T>(string key) { return _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } public T Get<T>(string key, T defValue) { return ConfigurationManager.AppSettings[key] == null ? defValue : _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } private static readonly ValueConverter _Converter = new ValueConverter(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using SupaCharge.Core.Converter; namespace SupaCharge.Core.ConfigurationWrapper { public class ConfigurationWrapper { public bool Contains(string key) { return (ConfigurationManager.AppSettings[key] != null); } public T Get<T>(string key) { return _Converter.Get<T>(ConfigurationManager.AppSettings[key]); } public T Get<T>(string key, T defValue) { return (ConfigurationManager.AppSettings[key] == null ? _Converter.Get<T>(defValue) : _Converter.Get<T>(ConfigurationManager.AppSettings[key])); } private static readonly ValueConverter _Converter = new ValueConverter(); } }
mit
C#
6cab3b6d8cb8bd20d5ff033e46bdf909cf7a0f6b
Fix app always showing the login page after orientation change
KallynGowdy/ReactiveUI.Routing
src/UseCases/ReactiveUI.Routing.UseCases.Android/MainActivity.cs
src/UseCases/ReactiveUI.Routing.UseCases.Android/MainActivity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.V4.App; using Android.Views; using Android.Widget; using ReactiveUI.Routing.Android; using ReactiveUI.Routing.Presentation; using ReactiveUI.Routing.UseCases.Common.ViewModels; using Splat; namespace ReactiveUI.Routing.UseCases.Android { [Activity(Label = "ReactiveUI.Routing.UseCases.Android", MainLauncher = true)] public class MainActivity : FragmentActivity, IActivatable { protected override void OnCreate(Bundle savedInstanceState) { Locator.CurrentMutable.InitializeRoutingAndroid(this); this.WhenActivated(d => { Locator.Current.GetService<FragmentActivationForViewFetcher>().SetFragmentManager(SupportFragmentManager); PagePresenter.RegisterHost(SupportFragmentManager, Resource.Id.Container) .DisposeWith(d); var presenter = Locator.Current.GetService<IAppPresenter>(); if (!presenter.ActiveViews.Any()) { presenter.PresentPage(new LoginViewModel()) .Subscribe() .DisposeWith(d); } }); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Support.V4.App; using Android.Views; using Android.Widget; using ReactiveUI.Routing.Android; using ReactiveUI.Routing.Presentation; using ReactiveUI.Routing.UseCases.Common.ViewModels; using Splat; namespace ReactiveUI.Routing.UseCases.Android { [Activity(Label = "ReactiveUI.Routing.UseCases.Android", MainLauncher = true)] public class MainActivity : FragmentActivity, IActivatable { protected override void OnCreate(Bundle savedInstanceState) { Locator.CurrentMutable.InitializeRoutingAndroid(this); this.WhenActivated(d => { Locator.Current.GetService<FragmentActivationForViewFetcher>().SetFragmentManager(SupportFragmentManager); PagePresenter.RegisterHost(SupportFragmentManager, Resource.Id.Container) .DisposeWith(d); Locator.Current.GetService<IAppPresenter>() .PresentPage(new LoginViewModel()) .Subscribe() .DisposeWith(d); }); base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main); } } }
mit
C#
d0e46de7d20d7a896e1014821bdbd83663ce7722
Add filter property to popular movies request.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Movies/Common/TraktMoviesPopularRequest.cs
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Movies/Common/TraktMoviesPopularRequest.cs
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Movies; internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie> { internal TraktMoviesPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/popular{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internet TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base.Get; using Objects.Basic; using Objects.Get.Movies; internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie> { internal TraktMoviesPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/popular{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
mit
C#
7231c97ab77c67382f1d126bbe2e3d7f434a6b27
Fix typo.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Movies/Common/TraktMoviesPopularRequest.cs
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Movies/Common/TraktMoviesPopularRequest.cs
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Movies; internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie> { internal TraktMoviesPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/popular{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Movies.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Movies; internal class TraktMoviesPopularRequest : TraktGetRequest<TraktPaginationListResult<TraktMovie>, TraktMovie> { internal TraktMoviesPopularRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "movies/popular{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internet TraktMovieFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
mit
C#
83a85292f797472ab84f22299b57ec2a56f9047b
Fix truncated text, bug #38567
xamarin/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples
HttpClient/AppDelegate.cs
HttpClient/AppDelegate.cs
using System; using System.IO; using CoreGraphics; using Foundation; using UIKit; namespace HttpClientSample { // The name AppDelegate is referenced in the MainWindow.xib file. public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { window.RootViewController = navigationController; button1.TouchDown += Button1TouchDown; TableViewSelector.Configure (stack, new [] { "http - WebRequest", "https - WebRequest", "http - NSUrlConnection", "http - HttpClient", "https - HttpClient" }); window.MakeKeyAndVisible (); return true; } async void Button1TouchDown (object sender, EventArgs e) { // Do not queue more than one request if (UIApplication.SharedApplication.NetworkActivityIndicatorVisible) return; HandlerType = null; button1.Enabled = false; switch (stack.SelectedRow ()) { case 0: new DotNet (this).HttpSample (); break; case 1: new DotNet (this).HttpSecureSample (); break; case 2: new Cocoa (this).HttpSample (); break; case 3: await new NetHttp (this).HttpSample (secure: false); break; case 4: await new NetHttp (this).HttpSample (secure: true); break; } } public Type HandlerType { get; set; } public void RenderStream (Stream stream) { var reader = new StreamReader (stream); InvokeOnMainThread (delegate { button1.Enabled = true; var view = new UIViewController (); var handler = new UILabel (new CGRect (20, 20, 300, 40)) { Text = "HttpClient is using " + HandlerType?.Name, Lines = 0 }; handler.SizeToFit (); var label = new UILabel (new CGRect (20, 40, 300, 80)) { Text = "The HTML returned by the server:" }; var tv = new UITextView (new CGRect (20, 100, 300, 400)) { Text = reader.ReadToEnd () }; if (HandlerType != null) view.Add (handler); view.Add (label); view.Add (tv); if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) { view.EdgesForExtendedLayout = UIRectEdge.None; } navigationController.PushViewController (view, true); }); } } }
using System; using System.IO; using CoreGraphics; using Foundation; using UIKit; namespace HttpClientSample { // The name AppDelegate is referenced in the MainWindow.xib file. public partial class AppDelegate : UIApplicationDelegate { // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { window.RootViewController = navigationController; button1.TouchDown += Button1TouchDown; TableViewSelector.Configure (stack, new [] { "http - WebRequest", "https - WebRequest", "http - NSUrlConnection", "http - HttpClient", "https - HttpClient" }); window.MakeKeyAndVisible (); return true; } async void Button1TouchDown (object sender, EventArgs e) { // Do not queue more than one request if (UIApplication.SharedApplication.NetworkActivityIndicatorVisible) return; HandlerType = null; button1.Enabled = false; switch (stack.SelectedRow ()) { case 0: new DotNet (this).HttpSample (); break; case 1: new DotNet (this).HttpSecureSample (); break; case 2: new Cocoa (this).HttpSample (); break; case 3: await new NetHttp (this).HttpSample (secure: false); break; case 4: await new NetHttp (this).HttpSample (secure: true); break; } } public Type HandlerType { get; set; } public void RenderStream (Stream stream) { var reader = new StreamReader (stream); InvokeOnMainThread (delegate { button1.Enabled = true; var view = new UIViewController (); var handler = new UILabel (new CGRect (20, 20, 300, 40)) { Text = "HttpClient is using " + HandlerType?.Name }; var label = new UILabel (new CGRect (20, 20, 300, 80)) { Text = "The HTML returned by the server:" }; var tv = new UITextView (new CGRect (20, 100, 300, 400)) { Text = reader.ReadToEnd () }; if (HandlerType != null) view.Add (handler); view.Add (label); view.Add (tv); if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) { view.EdgesForExtendedLayout = UIRectEdge.None; } navigationController.PushViewController (view, true); }); } } }
mit
C#
0b1ddad558b68ac56e42af617a90429b9cd3f34e
Update MainActivity.cs
iperezmx87/Xamarin30Labs
Lab8/Lab8/MainActivity.cs
Lab8/Lab8/MainActivity.cs
using Android.App; using Android.Widget; using Android.OS; using System; namespace Lab8 { [Activity(Label = "@string/ApplicationName", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //var viewGroup = (Android.Views.ViewGroup)Window.DecorView.FindViewById(Android.Resource.Id.Content); //var MainLayout = viewGroup.GetChildAt(0) as LinearLayout; //var headerImage = new ImageView(this); //headerImage.SetImageResource(Resource.Drawable.Xamarin_Diplomado_30); //MainLayout.AddView(headerImage); //var userNameTextView = new TextView(this); //userNameTextView.Text = GetString(Resource.String.UserName); //MainLayout.AddView(userNameTextView); ValidarActividad(); } private async void ValidarActividad() { try { SALLab08.ServiceClient client = new SALLab08.ServiceClient(); SALLab08.ResultInfo result = await client.ValidateAsync("", "", Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId)); RunOnUiThread(() => { FindViewById<TextView>(Resource.Id.UserNameValue).Text = result.Fullname; FindViewById<TextView>(Resource.Id.StatusValue).Text = Enum.GetName(typeof(SALLab08.Status), result.Status); FindViewById<TextView>(Resource.Id.TokenValue).Text = result.Token; }); } catch (Exception ex) { Toast.MakeText(this, $"Error: {ex.Message}", ToastLength.Long).Show(); } } } }
using Android.App; using Android.Widget; using Android.OS; using System; namespace Lab8 { [Activity(Label = "@string/ApplicationName", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //var viewGroup = (Android.Views.ViewGroup)Window.DecorView.FindViewById(Android.Resource.Id.Content); //var MainLayout = viewGroup.GetChildAt(0) as LinearLayout; //var headerImage = new ImageView(this); //headerImage.SetImageResource(Resource.Drawable.Xamarin_Diplomado_30); //MainLayout.AddView(headerImage); //var userNameTextView = new TextView(this); //userNameTextView.Text = GetString(Resource.String.UserName); //MainLayout.AddView(userNameTextView); ValidarActividad(); } private async void ValidarActividad() { try { SALLab08.ServiceClient client = new SALLab08.ServiceClient(); SALLab08.ResultInfo result = await client.ValidateAsync("israel.perez@cencel.com.mx", "Isra-mx87", Android.Provider.Settings.Secure.GetString(ContentResolver, Android.Provider.Settings.Secure.AndroidId)); RunOnUiThread(() => { FindViewById<TextView>(Resource.Id.UserNameValue).Text = result.Fullname; FindViewById<TextView>(Resource.Id.StatusValue).Text = Enum.GetName(typeof(SALLab08.Status), result.Status); FindViewById<TextView>(Resource.Id.TokenValue).Text = result.Token; }); } catch (Exception ex) { Toast.MakeText(this, $"Error: {ex.Message}", ToastLength.Long).Show(); } } } }
mit
C#
9136d77c92f9b35f47b468049e4e8ad17b848ab2
Create EventSystem if there is none
loicteixeira/gj-unity-api
Assets/Plugins/Editor/GameJolt/Tools.cs
Assets/Plugins/Editor/GameJolt/Tools.cs
using UnityEngine; using UnityEngine.EventSystems; using UnityEditor; namespace GameJolt.Editor { public class Tools : MonoBehaviour { [MenuItem("Edit/Project Settings/Game Jolt API")] public static void Settings() { var asset = AssetDatabase.LoadAssetAtPath(GameJolt.API.Constants.SETTINGS_ASSET_FULL_PATH, typeof(GameJolt.API.Settings)) as GameJolt.API.Settings; if (asset == null) { asset = ScriptableObject.CreateInstance<GameJolt.API.Settings>(); AssetDatabase.CreateAsset (asset, GameJolt.API.Constants.SETTINGS_ASSET_FULL_PATH); AssetDatabase.SaveAssets (); } EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; } [MenuItem("GameObject/Game Jolt API Manager")] public static void Manager() { var manager = FindObjectOfType<GameJolt.API.Manager>(); if (manager != null) { Selection.activeObject = manager; } else { var prefab = AssetDatabase.LoadAssetAtPath(GameJolt.API.Constants.MANAGER_ASSET_FULL_PATH, typeof(GameObject)) as GameObject; if (prefab == null) { Debug.LogError("Unable to locate Game Jolt API prefab."); } else { var clone = PrefabUtility.InstantiatePrefab(prefab) as GameObject; Selection.activeObject = clone; if (FindObjectOfType<EventSystem>() == null) { new GameObject( "EventSystem", typeof(EventSystem), typeof(StandaloneInputModule), typeof(StandaloneInputModule) ); } } } } } }
using UnityEngine; using UnityEditor; namespace GameJolt.Editor { public class Tools : MonoBehaviour { [MenuItem("Edit/Project Settings/Game Jolt API")] public static void Settings() { var asset = AssetDatabase.LoadAssetAtPath(GameJolt.API.Constants.SETTINGS_ASSET_FULL_PATH, typeof(GameJolt.API.Settings)) as GameJolt.API.Settings; if (asset == null) { asset = ScriptableObject.CreateInstance<GameJolt.API.Settings>(); AssetDatabase.CreateAsset (asset, GameJolt.API.Constants.SETTINGS_ASSET_FULL_PATH); AssetDatabase.SaveAssets (); } EditorUtility.FocusProjectWindow(); Selection.activeObject = asset; } [MenuItem("GameObject/Game Jolt API Manager")] public static void Manager() { var manager = FindObjectOfType<GameJolt.API.Manager>(); if (manager != null) { Selection.activeObject = manager; } else { var prefab = AssetDatabase.LoadAssetAtPath(GameJolt.API.Constants.MANAGER_ASSET_FULL_PATH, typeof(GameObject)) as GameObject; if (prefab == null) { Debug.LogError("Unable to locate Game Jolt API prefab."); } else { var clone = PrefabUtility.InstantiatePrefab(prefab) as GameObject; Selection.activeObject = clone; } } } } }
mit
C#
c266f4a835a913accc50535ca4c0b6e176d00dde
add is closed to shape
pabloengine/pablo
Pablo/Graphics/Shape/Shape.cs
Pablo/Graphics/Shape/Shape.cs
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ namespace Pablo.Graphics { /// <summary> /// Base type for all the shapes. /// </summary> public abstract class Shape : VisualElement { /// <summary> /// Gets the bounding box of the <see cref="Shape"/>. /// </summary> public abstract Box BoundingBox { get; } /// <summary> /// Gets the width of the <see cref="Shape"/>. /// </summary> public abstract double Width { get; } /// <summary> /// Gets the height of the <see cref="Shape"/>. /// </summary> public abstract double Height { get; } /// <summary> /// Determines whether the <see cref="Shape"/> is closed. /// </summary> public abstract bool IsClosed { get; } /// <summary> /// Initializes a new instance of <see cref="Shape"/>. /// </summary> internal Shape() { } } }
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (c) 2015, MPL Ali Taheri Moghaddar ali.taheri.m@gmail.com */ namespace Pablo.Graphics { /// <summary> /// Base type for all the shapes. /// </summary> public abstract class Shape : VisualElement { /// <summary> /// Gets the bounding box of the <see cref="Shape"/>. /// </summary> public abstract Box BoundingBox { get; } /// <summary> /// Gets the width of the <see cref="Shape"/>. /// </summary> public abstract double Width { get; } /// <summary> /// Gets the height of the <see cref="Shape"/>. /// </summary> public abstract double Height { get; } /// <summary> /// Initializes a new instance of <see cref="Shape"/>. /// </summary> internal Shape() { } } }
mpl-2.0
C#
ebce75908fb938b2a39047834accfaf45b5d6ff2
bump version
modulexcite/Anotar,distantcam/Anotar,mstyura/Anotar,Fody/Anotar
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Anotar")] [assembly: AssemblyProduct("Anotar")] [assembly: AssemblyVersion("2.16.2")] [assembly: AssemblyFileVersion("2.16.2")]
using System.Reflection; [assembly: AssemblyTitle("Anotar")] [assembly: AssemblyProduct("Anotar")] [assembly: AssemblyVersion("2.16.1")] [assembly: AssemblyFileVersion("2.16.1")]
mit
C#
1732eb337dbb12f4a92975051e0a47a990389818
Fix exception if Keys is null
ClemPi/radosgwadminapi
RadosGW.AdminAPI/Models/User.cs
RadosGW.AdminAPI/Models/User.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Radosgw.AdminAPI { public class User { [JsonProperty(PropertyName = "display_name")] public string DisplayName { get; set; } [JsonProperty(PropertyName = "user_id")] public string UserId { get; set; } [JsonProperty(PropertyName = "tenant")] public string Tenant { get; set; } [JsonProperty(PropertyName = "email")] public string Email { get; set; } [JsonProperty(PropertyName = "max_buckets")] public uint MaxBuckets { get; set; } [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "suspended")] public bool Suspended { get; set; } [JsonProperty(PropertyName="keys")] public List<Key> Keys { get; set; } public override string ToString() { return string.Format("[User: DisplayName={0}, UserId={1}, Tenant={2}, Email={3}, MaxBuckets={4}, Suspended={5}, Keys={6}]", DisplayName, UserId, Tenant, Email, MaxBuckets, Suspended, string.Format("[{0}]", string.Join(",", Keys ?? new List<Key>()))); } public User() { } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace Radosgw.AdminAPI { public class User { [JsonProperty(PropertyName = "display_name")] public string DisplayName { get; set; } [JsonProperty(PropertyName = "user_id")] public string UserId { get; set; } [JsonProperty(PropertyName = "tenant")] public string Tenant { get; set; } [JsonProperty(PropertyName = "email")] public string Email { get; set; } [JsonProperty(PropertyName = "max_buckets")] public uint MaxBuckets { get; set; } [JsonConverter(typeof(BoolConverter))] [JsonProperty(PropertyName = "suspended")] public bool Suspended { get; set; } [JsonProperty(PropertyName="keys")] public List<Key> Keys { get; set; } public override string ToString() { return string.Format("[User: DisplayName={0}, UserId={1}, Tenant={2}, Email={3}, MaxBuckets={4}, Suspended={5}, Keys={6}]", DisplayName, UserId, Tenant, Email, MaxBuckets, Suspended, string.Format("[{0}]", string.Join(",", Keys))); } public User() { } } }
apache-2.0
C#
facd6a05488f1606c26310c24ddb4844e7775a2a
make naming consistent for oauth flows
kjnilsson/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,kjnilsson/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,rfavillejr/Thinktecture.IdentityServer.v2
src/Libraries/Thinktecture.IdentityServer.Core/Models/Configuration/OAuth2Configuration.cs
src/Libraries/Thinktecture.IdentityServer.Core/Models/Configuration/OAuth2Configuration.cs
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license.txt */ using System.ComponentModel.DataAnnotations; namespace Thinktecture.IdentityServer.Models.Configuration { public class OAuth2Configuration : ProtocolConfiguration { [Display(Name = "Enable Implicit Flow", Description = "This flow is for native apps and client web applications.")] public bool EnableImplicitFlow { get; set; } [Display(Name = "Enable Resource Owner Flow", Description = "This flow is for trusted applications only. Users enter their credentials directly into the client.")] public bool EnableResourceOwnerFlow { get; set; } [Display(Name = "Enable Consent Page", Description = "Specifies whether a consent page is shown before a token/code is returned.")] public bool EnableConsent { get; set; } } }
/* * Copyright (c) Dominick Baier, Brock Allen. All rights reserved. * see license.txt */ using System.ComponentModel.DataAnnotations; namespace Thinktecture.IdentityServer.Models.Configuration { public class OAuth2Configuration : ProtocolConfiguration { [Display(Name = "Enable 'Resource Owner Password Credential' Flow", Description = "This flow is for trusted applications only. Users enter their credentials directly into the client.")] public bool EnableResourceOwnerFlow { get; set; } [Display(Name = "Enable 'Implicit' Flow", Description = "This flow is for native apps and client web applications.")] public bool EnableImplicitFlow { get; set; } [Display(Name = "Enable Consent Page", Description = "Specifies whether a consent page is shown before a token/code is returned.")] public bool EnableConsent { get; set; } } }
bsd-3-clause
C#
15797f6b67b2a22b2e842045fd5a0e74fd45fbff
Refactor how EntryPoint.cs handles exceptions (or doesn't) in Debug builds. This way, we get the visual studio exception dialog at the line throwing the issue.
AndrewBaker/magecrawl,jeongroseok/magecrawl
Trunk/MageCrawl/EntryPoint.cs
Trunk/MageCrawl/EntryPoint.cs
using System.IO; using libtcod; using Magecrawl.GameUI; namespace Magecrawl { public static class EntryPoint { public static void Main() { #if !DEBUG try #endif { UIHelper.SetupUI(); WelcomeWindow.Result result; using (WelcomeWindow welcomeWindow = new WelcomeWindow()) { result = welcomeWindow.Run(); } if (result.Quitting || TCODConsole.isWindowClosed()) return; using (GameInstance inst = new GameInstance()) { inst.Go(result.CharacterName, result.LoadCharacter); } } // In debug builds, we want the exception to be rethrown to make debugging easier. In release builds, we want it to get written to a file. #if !DEBUG catch (System.Exception e) { using (TextWriter tw = new StreamWriter("DebuggingLog.txt")) { tw.WriteLine("Message - " + e.Message); tw.WriteLine("Source - " + e.Source); tw.WriteLine("StackTrace - " + e.StackTrace); tw.WriteLine("TargetSite - " + e.TargetSite); } } #endif } } }
using System.IO; using libtcod; using Magecrawl.GameUI; namespace Magecrawl { public static class EntryPoint { public static void Main() { try { UIHelper.SetupUI(); WelcomeWindow.Result result; using (WelcomeWindow welcomeWindow = new WelcomeWindow()) { result = welcomeWindow.Run(); } if (result.Quitting || TCODConsole.isWindowClosed()) return; using (GameInstance inst = new GameInstance()) { inst.Go(result.CharacterName, result.LoadCharacter); } } catch (System.Exception #if !DEBUG // Work around stupid unused variable warning e #endif ) { // In debug builds, we want the exception to be rethrown to make debugging easier. In release builds, we want it to get written to a file. #if DEBUG throw; #else using (TextWriter tw = new StreamWriter("DebuggingLog.txt")) { tw.WriteLine("Message - " + e.Message); tw.WriteLine("Source - " + e.Source); tw.WriteLine("StackTrace - " + e.StackTrace); tw.WriteLine("TargetSite - " + e.TargetSite); } #endif } } } }
bsd-2-clause
C#
625fb54b75c596e77f3d7317b727672dcf4300f1
fix nonclickable links on learn pages in mobile view
smaglio81/boxstarter,napramirez/boxstarter,cam1985/boxstarter,mwrock/boxstarter,napramirez/boxstarter,tbyehl/boxstarter,fhchina/boxstarter,tbyehl/boxstarter,dex1on/pub,dex1on/pub,smaglio81/boxstarter,napramirez/boxstarter,modulexcite/boxstarter,mwrock/boxstarter,cam1985/boxstarter,fhchina/boxstarter,dhilgarth/boxstarter,modulexcite/boxstarter,smaglio81/boxstarter,dex1on/pub,modulexcite/boxstarter,dhilgarth/boxstarter,tbyehl/boxstarter,dhilgarth/boxstarter,cam1985/boxstarter,fhchina/boxstarter
Web/Learn/_ContentLayout.cshtml
Web/Learn/_ContentLayout.cshtml
@using System.Security.Policy @{ Layout = "~/_SiteLayout.cshtml"; var absPath = Request.Url.AbsolutePath; var thisPage = absPath.ToLower().Substring(absPath.LastIndexOf('/')+1); PageData[thisPage + "Style"] = "active"; PageData["Learn"] = "active"; } @section styles { @RenderSection("styles", required: false) } <div class="row"> <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation"> <div class="list-group"> <a href="WebLauncher" class="list-group-item @PageData["weblauncherStyle"]">Run with a Gist</a> <a href="SimplePackage" class="list-group-item @PageData["simplepackageStyle"]">Simple package creation</a> <a href="RemotePackageWithArtifacts" class="list-group-item @PageData["remotepackageWithartifactsStyle"]">Deploying a web application remotely</a> </div> </div> <div class="col-xs-6 col-md-9" role="main"> <div class="media"> <a class="pull-right" href="#"> <img class="media-object" src="~/images/boxlogo_sm.png"/> </a> <div class="media-body"> @RenderSection("headerBody") </div> </div> @RenderBody() </div> </div>
@using System.Security.Policy @{ Layout = "~/_SiteLayout.cshtml"; var absPath = Request.Url.AbsolutePath; var thisPage = absPath.ToLower().Substring(absPath.LastIndexOf('/')+1); PageData[thisPage + "Style"] = "active"; PageData["Learn"] = "active"; } @section styles { @RenderSection("styles", required: false) } <div class="row"> <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation"> <div class="list-group"> <a href="WebLauncher" class="list-group-item @PageData["weblauncherStyle"]">Run with a Gist</a> <a href="SimplePackage" class="list-group-item @PageData["simplepackageStyle"]">Simple package creation</a> <a href="RemotePackageWithArtifacts" class="list-group-item @PageData["remotepackageWithartifactsStyle"]">Deploying a web application remotely</a> </div> </div> <div class="col-md-9" role="main"> <div class="media"> <a class="pull-right" href="#"> <img class="media-object" src="~/images/boxlogo_sm.png"/> </a> <div class="media-body"> @RenderSection("headerBody") </div> </div> @RenderBody() </div> </div>
apache-2.0
C#