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 |
---|---|---|---|---|---|---|---|---|
5e7f78005d660ad334d29c664ca6fabdabd72e51 | Update ToolIconConverter.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Converters/ToolIconConverter.cs | src/Core2D/Converters/ToolIconConverter.cs | #nullable enable
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Core2D.Model.Editor;
namespace Core2D.Converters;
public class ToolIconConverter : IValueConverter
{
public static ToolIconConverter Instance = new();
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is ITool tool)
{
var key = $"{tool.Title}";
if (Application.Current is { } application)
{
if (application.Styles.TryGetResource(key, out var resource))
{
return resource;
}
}
}
return AvaloniaProperty.UnsetValue;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
| #nullable enable
using System;
using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Core2D.Model.Editor;
namespace Core2D.Converters;
public class ToolIconConverter : IValueConverter
{
public static ToolIconConverter Instance = new();
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is ITool tool)
{
var key = $"{tool.Title}";
if (Application.Current.Styles.TryGetResource(key, out var resource))
{
return resource;
}
}
return AvaloniaProperty.UnsetValue;
}
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
} | mit | C# |
643ed549d6084905780e67eeccfa441bafa86ed7 | Add response DTO marker interface for service documentation | dnauck/License.Manager,dnauck/License.Manager | src/License.Manager.Core/Model/Customer.cs | src/License.Manager.Core/Model/Customer.cs | using ServiceStack.ServiceHost;
namespace License.Manager.Core.Model
{
[Route("/customers", "POST")]
[Route("/customers/{Id}", "PUT, DELETE")]
[Route("/customers/{Id}", "GET, OPTIONS")]
public class Customer : EntityBase, IReturn<Customer>
{
public string Name { get; set; }
public string Company { get; set; }
public string Email { get; set; }
}
} | using ServiceStack.ServiceHost;
namespace License.Manager.Core.Model
{
[Route("/customers", "POST")]
[Route("/customers/{Id}", "PUT, DELETE")]
[Route("/customers/{Id}", "GET, OPTIONS")]
public class Customer : EntityBase
{
public string Name { get; set; }
public string Company { get; set; }
public string Email { get; set; }
}
} | mit | C# |
e39f254ff9156287d0111780cfad9e3984ad9728 | Initialize using UsePlatformDetect | wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter,wieslawsoltes/SimpleWavSplitter | src/SimpleWavSplitter.Avalonia/App.xaml.cs | src/SimpleWavSplitter.Avalonia/App.xaml.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Diagnostics;
using Avalonia.Logging.Serilog;
using Avalonia.Markup.Xaml;
using Serilog;
namespace SimpleWavSplitter.Avalonia
{
/// <summary>
/// Main application.
/// </summary>
public class App : Application
{
/// <inheritdoc/>
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
base.Initialize();
}
/// <summary>
/// Program entry point.
/// </summary>
/// <param name="args">The program arguments.</param>
static void Main(string[] args)
{
InitializeLogging();
AppBuilder.Configure<App>()
.UsePlatformDetect()
.Start<MainWindow>();
}
/// <summary>
/// Attaches development tools to window in debug mode.
/// </summary>
/// <param name="window">The window to attach development tools.</param>
public static void AttachDevTools(Window window)
{
#if DEBUG
DevTools.Attach(window);
#endif
}
/// <summary>
/// Initializes logging in debug mode.
/// </summary>
private static void InitializeLogging()
{
#if DEBUG
SerilogLogger.Initialize(new LoggerConfiguration()
.MinimumLevel.Warning()
.WriteTo.Trace(outputTemplate: "{Area}: {Message}")
.CreateLogger());
#endif
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Diagnostics;
using Avalonia.Logging.Serilog;
using Avalonia.Markup.Xaml;
using Serilog;
namespace SimpleWavSplitter.Avalonia
{
/// <summary>
/// Main application.
/// </summary>
public class App : Application
{
/// <inheritdoc/>
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
base.Initialize();
}
/// <summary>
/// Program entry point.
/// </summary>
/// <param name="args">The program arguments.</param>
static void Main(string[] args)
{
InitializeLogging();
AppBuilder.Configure<App>()
.UseWin32()
.UseDirect2D1()
.Start<MainWindow>();
}
/// <summary>
/// Attaches development tools to window in debug mode.
/// </summary>
/// <param name="window">The window to attach development tools.</param>
public static void AttachDevTools(Window window)
{
#if DEBUG
DevTools.Attach(window);
#endif
}
/// <summary>
/// Initializes logging in debug mode.
/// </summary>
private static void InitializeLogging()
{
#if DEBUG
SerilogLogger.Initialize(new LoggerConfiguration()
.MinimumLevel.Warning()
.WriteTo.Trace(outputTemplate: "{Area}: {Message}")
.CreateLogger());
#endif
}
}
}
| mit | C# |
7f89bb0cc48b6d4f32937802d28530cd05ed6fdc | fix docs | icarus-consulting/Yaapii.Atoms | src/Yaapii.Atoms/Enumerable/Partitioned.cs | src/Yaapii.Atoms/Enumerable/Partitioned.cs | // MIT License
//
// Copyright(c) 2017 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Collections.Generic;
namespace Yaapii.Atoms.Enumerable
{
/// <summary>
/// Enumerable partitioned by a given size.
/// <para>Is a IEnumerable</para>
/// </summary>
public sealed class Partitioned<T> : EnumerableEnvelope<IEnumerable<T>>
{
/// <summary>
/// Enumerable partitioned by a given size.
/// </summary>
public Partitioned(int size, IEnumerable<T> list) : base(() =>
new EnumerableOf<IEnumerable<T>>(
new Enumerator.Partitioned<T>(
size, list.GetEnumerator()
)
)
)
{ }
}
}
| // MIT License
//
// Copyright(c) 2017 ICARUS Consulting GmbH
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System.Collections.Generic;
namespace Yaapii.Atoms.Enumerable
{
/// <summary>
/// Partitiones a given enumerable by a given size.
/// <para>Is a IEnumerable</para>
/// </summary>
public sealed class Partitioned<T> : EnumerableEnvelope<IEnumerable<T>>
{
public Partitioned(int size, IEnumerable<T> list) : base(() =>
new EnumerableOf<IEnumerable<T>>(
new Enumerator.Partitioned<T>(
size, list.GetEnumerator()
)
)
)
{ }
}
}
| mit | C# |
4ee3d5adb0fbfa3f6be081ca51cd78c7f3fecaac | Fix for WebSettingsSerializer | OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core | Core/OfficeDevPnP.Core/Framework/Provisioning/Providers/Xml/Serializers/WebSettingsSerializer.cs | Core/OfficeDevPnP.Core/Framework/Provisioning/Providers/Xml/Serializers/WebSettingsSerializer.cs | using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Serializers
{
/// <summary>
/// Class to serialize/deserialize the content types
/// </summary>
[TemplateSchemaSerializer(SerializationSequence = 400, DeserializationSequence = 400,
MinimalSupportedSchemaVersion = XMLPnPSchemaVersion.V201605,
Default = true)]
internal class WebSettingsSerializer : PnPBaseSchemaSerializer<WebSettings>
{
public override void Deserialize(object persistence, ProvisioningTemplate template)
{
var webSettings = persistence.GetPublicInstancePropertyValue("WebSettings");
if (webSettings != null)
{
template.WebSettings = new WebSettings();
PnPObjectsMapper.MapProperties(webSettings, template.WebSettings, null, true);
}
}
public override void Serialize(ProvisioningTemplate template, object persistence)
{
if (template.WebSettings != null)
{
var webSettingsType = Type.GetType($"{PnPSerializationScope.Current?.BaseSchemaNamespace}.WebSettings, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}", true);
var target = Activator.CreateInstance(webSettingsType, true);
var expressions = new Dictionary<string, IResolver>();
expressions.Add($"{webSettingsType}.NoCrawlSpecified", new ExpressionValueResolver((s, p) => true));
PnPObjectsMapper.MapProperties(template.WebSettings, target, expressions, recursive: true);
persistence.GetPublicInstanceProperty("WebSettings").SetValue(persistence, target);
}
}
}
}
| using Microsoft.SharePoint.Client;
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Resolvers;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
namespace OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.Serializers
{
/// <summary>
/// Class to serialize/deserialize the content types
/// </summary>
[TemplateSchemaSerializer(SerializationSequence = 400, DeserializationSequence = 400,
MinimalSupportedSchemaVersion = XMLPnPSchemaVersion.V201605,
Default = true)]
internal class WebSettingsSerializer : PnPBaseSchemaSerializer<WebSettings>
{
public override void Deserialize(object persistence, ProvisioningTemplate template)
{
var webSettings = persistence.GetPublicInstancePropertyValue("WebSettings");
template.WebSettings = new WebSettings();
PnPObjectsMapper.MapProperties(webSettings, template.WebSettings, null, true);
}
public override void Serialize(ProvisioningTemplate template, object persistence)
{
if (template.WebSettings != null)
{
var webSettingsType = Type.GetType($"{PnPSerializationScope.Current?.BaseSchemaNamespace}.WebSettings, {PnPSerializationScope.Current?.BaseSchemaAssemblyName}", true);
var target = Activator.CreateInstance(webSettingsType, true);
var expressions = new Dictionary<string, IResolver>();
expressions.Add($"{webSettingsType}.NoCrawlSpecified", new ExpressionValueResolver((s, p) => true));
PnPObjectsMapper.MapProperties(template.WebSettings, target, expressions, recursive: true);
persistence.GetPublicInstanceProperty("WebSettings").SetValue(persistence, target);
}
}
}
}
| mit | C# |
0d91d1cf9fdfcc666cfcf9eaee8eca76f5fadae6 | Fix for two-digit year as specified by ICU. | FubarDevelopment/beanio-net | test/FubarDev.BeanIO.Test/Parser/Types/TypeHandlerLocaleTest.cs | test/FubarDev.BeanIO.Test/Parser/Types/TypeHandlerLocaleTest.cs | // <copyright file="TypeHandlerLocaleTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace BeanIO.Parser.Types
{
public class TypeHandlerLocaleTest : AbstractParserTest
{
[Fact]
public void TestFieldWithDefault()
{
var date = new DateTime(2013, 2, 1);
var factory = CreateFactory(@"
<stream name=""s"" format=""csv"" strict=""true"">
<typeHandler name=""int_de"" class=""BeanIO.Types.IntegerTypeHandler, FubarDev.BeanIO"">
<property name=""locale"" value=""de"" />
</typeHandler>
<typeHandler name=""date_de"" class=""BeanIO.Types.DateTimeTypeHandler, FubarDev.BeanIO"">
<property name=""locale"" value=""de"" />
</typeHandler>
<record name=""record"" class=""map"">
<field name=""int1"" typeHandler=""int_de"" format=""#,##0"" />
<field name=""int2"" type=""int"" format=""#,##0"" />
<field name=""date"" typeHandler=""date_de"" />
</record>
</stream>");
var cultureDe = new CultureInfo("de");
var text = string.Format("10.000,\"10,000\",{0}", date.ToString(cultureDe));
var map = new Dictionary<string, object>()
{
{ "int1", 10000 },
{ "int2", 10000 },
{ "date", date },
};
var m = factory.CreateMarshaller("s");
Assert.Equal(text, m.Marshal(map).ToString());
var u = factory.CreateUnmarshaller("s");
Assert.Equal(map, u.Unmarshal(text));
}
}
}
| // <copyright file="TypeHandlerLocaleTest.cs" company="Fubar Development Junker">
// Copyright (c) 2016 Fubar Development Junker. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
using System;
using System.Collections.Generic;
using Xunit;
namespace BeanIO.Parser.Types
{
public class TypeHandlerLocaleTest : AbstractParserTest
{
[Fact]
public void TestFieldWithDefault()
{
var date = new DateTime(2013, 2, 1);
var factory = CreateFactory(@"
<stream name=""s"" format=""csv"" strict=""true"">
<typeHandler name=""int_de"" class=""BeanIO.Types.IntegerTypeHandler, FubarDev.BeanIO"">
<property name=""locale"" value=""de"" />
</typeHandler>
<typeHandler name=""date_de"" class=""BeanIO.Types.DateTimeTypeHandler, FubarDev.BeanIO"">
<property name=""locale"" value=""de"" />
</typeHandler>
<record name=""record"" class=""map"">
<field name=""int1"" typeHandler=""int_de"" format=""#,##0"" />
<field name=""int2"" type=""int"" format=""#,##0"" />
<field name=""date"" typeHandler=""date_de"" />
</record>
</stream>");
var text = "10.000,\"10,000\",01.02.2013 00:00:00";
var map = new Dictionary<string, object>()
{
{ "int1", 10000 },
{ "int2", 10000 },
{ "date", date },
};
var m = factory.CreateMarshaller("s");
Assert.Equal(text, m.Marshal(map).ToString());
var u = factory.CreateUnmarshaller("s");
Assert.Equal(map, u.Unmarshal(text));
}
}
}
| mit | C# |
d36a0255a76cd8737772abed7b3c1951a73b69f8 | fix RequiresNotMedia implementation | RPCS3/discord-bot | CompatBot/Commands/Attributes/RequiresNotMedia.cs | CompatBot/Commands/Attributes/RequiresNotMedia.cs | using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
namespace CompatBot.Commands.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
internal class RequiresNotMedia: CheckBaseAttribute
{
public override Task<bool> ExecuteCheckAsync(CommandContext ctx, bool help)
{
return Task.FromResult(ctx.Channel.Name != "media");
}
}
} | using System;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
namespace CompatBot.Commands.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)]
internal class RequiresNotMedia: CheckBaseAttribute
{
public override async Task<bool> ExecuteCheckAsync(CommandContext ctx, bool help)
{
return ctx.Channel.Name != "media";
}
}
} | lgpl-2.1 | C# |
d12ca732aca6dfd40435ec76b2e48bc9c9e3825f | Update DbContextBulkTransaction.cs | borisdj/EFCore.BulkExtensions | EFCore.BulkExtensions/DbContextBulkTransaction.cs | EFCore.BulkExtensions/DbContextBulkTransaction.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EFCore.BulkExtensions
{
internal static class DbContextBulkTransaction
{
public static void Execute<T>(DbContext context, IList<T> entities, OperationType operationType, BulkConfig bulkConfig, Action<decimal> progress) where T : class
{
if (entities.Count == 0)
{
return;
}
TableInfo tableInfo = TableInfo.CreateInstance(context, entities, operationType, bulkConfig);
if (operationType == OperationType.Insert && !tableInfo.BulkConfig.SetOutputIdentity)
{
SqlBulkOperation.Insert(context, entities, tableInfo, progress);
}
else if (operationType == OperationType.Read)
{
SqlBulkOperation.Read(context, entities, tableInfo, progress);
}
else
{
SqlBulkOperation.Merge(context, entities, tableInfo, operationType, progress);
}
}
public static Task ExecuteAsync<T>(DbContext context, IList<T> entities, OperationType operationType, BulkConfig bulkConfig, Action<decimal> progress) where T : class
{
if (entities.Count == 0)
{
return Task.CompletedTask;
}
TableInfo tableInfo = TableInfo.CreateInstance(context, entities, operationType, bulkConfig);
if (operationType == OperationType.Insert && !tableInfo.BulkConfig.SetOutputIdentity)
{
return SqlBulkOperation.InsertAsync(context, entities, tableInfo, progress);
}
else if (operationType == OperationType.Read)
{
return SqlBulkOperation.ReadAsync(context, entities, tableInfo, progress);
}
else
{
return SqlBulkOperation.MergeAsync(context, entities, tableInfo, operationType, progress);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace EFCore.BulkExtensions
{
internal static class DbContextBulkTransaction
{
public static void Execute<T>(DbContext context, IList<T> entities, OperationType operationType, BulkConfig bulkConfig, Action<decimal> progress) where T : class
{
TableInfo tableInfo = TableInfo.CreateInstance(context, entities, operationType, bulkConfig);
if (operationType == OperationType.Insert && !tableInfo.BulkConfig.SetOutputIdentity)
{
SqlBulkOperation.Insert(context, entities, tableInfo, progress);
}
else if (operationType == OperationType.Read)
{
SqlBulkOperation.Read(context, entities, tableInfo, progress);
}
else
{
SqlBulkOperation.Merge(context, entities, tableInfo, operationType, progress);
}
}
public static Task ExecuteAsync<T>(DbContext context, IList<T> entities, OperationType operationType, BulkConfig bulkConfig, Action<decimal> progress) where T : class
{
TableInfo tableInfo = TableInfo.CreateInstance(context, entities, operationType, bulkConfig);
if (operationType == OperationType.Insert && !tableInfo.BulkConfig.SetOutputIdentity)
{
return SqlBulkOperation.InsertAsync(context, entities, tableInfo, progress);
}
else if (operationType == OperationType.Read)
{
return SqlBulkOperation.ReadAsync(context, entities, tableInfo, progress);
}
else
{
return SqlBulkOperation.MergeAsync(context, entities, tableInfo, operationType, progress);
}
}
}
}
| mit | C# |
fc9ce398671dbe1d12f2f8039166320212f87f4f | add properties to CarAdvert | mdavid626/artemis | src/Artemis.Web/Model/CarAdvert.cs | src/Artemis.Web/Model/CarAdvert.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Artemis.Web.Model
{
public class CarAdvert
{
public int Id { get; set; }
public string Title { get; set; }
public string Fuel { get; set; }
public decimal Price { get; set; }
public bool New { get; set; }
public int? Mileage { get; set; }
public DateTime? FirstRegistration { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Artemis.Web.Model
{
public class CarAdvert
{
}
} | mit | C# |
e5f8dc56347bcb1014de80e3600d314bdc958ffd | Add methods to access specific properties from a Fieldset | tomfulton/Archetype,imulus/Archetype,kjac/Archetype,tomfulton/Archetype,kipusoep/Archetype,imulus/Archetype,kgiszewski/Archetype,kipusoep/Archetype,kjac/Archetype,kgiszewski/Archetype,kipusoep/Archetype,Nicholas-Westby/Archetype,kjac/Archetype,kgiszewski/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,tomfulton/Archetype,Nicholas-Westby/Archetype | app/Umbraco/Umbraco.Archetype/Models/Fieldset.cs | app/Umbraco/Umbraco.Archetype/Models/Fieldset.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Core;
namespace Archetype.Umbraco.Models
{
public class Fieldset
{
public string Alias { get; set; }
public IEnumerable<Property> Properties;
public Fieldset()
{
Properties = new List<Property>();
}
public string GetValue(string propertyAlias)
{
return GetValue<string>(propertyAlias);
}
public T GetValue<T>(string propertyAlias)
{
var property = GetProperty(propertyAlias);
if (property == null || string.IsNullOrEmpty(property.Value))
return default(T);
var convertAttempt = property.Value.TryConvertTo<T>();
if (convertAttempt.Success)
return convertAttempt.Result;
return default(T);
}
private Property GetProperty(string propertyAlias)
{
return Properties.FirstOrDefault(p => p.Alias.InvariantEquals(propertyAlias));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Archetype.Umbraco.Models
{
public class Fieldset
{
public string Alias { get; set; }
public IEnumerable<Property> Properties;
public Fieldset()
{
Properties = new List<Property>();
}
}
}
| mit | C# |
e5f585b283aa0dbfbfd6779c18b97ef8f750b462 | Allow inline dictionary entries. | TheBerkin/Rant | Rant/Vocabulary/DicLexer.cs | Rant/Vocabulary/DicLexer.cs | using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Rant.Stringes;
namespace Rant.Vocabulary
{
internal static class DicLexer
{
public static IEnumerable<Token<DicTokenType>> Tokenize(string data)
{
var reader = new StringReader(data);
while (true)
{
int nextChar = reader.Read();
if (nextChar == -1)
{
yield return new Token<DicTokenType>(DicTokenType.EOF, "");
yield break;
}
char currentChar = (char)nextChar;
if (char.IsWhiteSpace(currentChar))
continue;
switch (currentChar)
{
// directive
case '#':
{
string value = ReadRestOfLine(reader);
yield return new Token<DicTokenType>(DicTokenType.Directive, value.Trim());
}
break;
// entry or diffentry
case '>':
{
int peekedChar = reader.Peek();
if (peekedChar == -1)
yield break;
bool diffmark = false;
// it's a diffentry
if ((char)peekedChar == '>')
{
diffmark = true;
reader.Read();
}
string value = ReadRestOfLine(reader, diffmark);
yield return new Token<DicTokenType>(diffmark ? DicTokenType.DiffEntry : DicTokenType.Entry, value.Trim());
}
break;
// property
case '|':
{
string value = ReadRestOfLine(reader);
yield return new Token<DicTokenType>(DicTokenType.Property, value.Trim());
}
break;
default:
throw new System.Exception("Unexpected character in dictionary.");
}
}
}
private static string ReadRestOfLine(StringReader reader, bool isDiffmark = false)
{
int nextChar;
char currentChar;
string value = "";
bool pipeAllowed = !isDiffmark;
// read to the end of the line
while (true)
{
nextChar = reader.Peek();
if (nextChar == -1)
break;
currentChar = (char)nextChar;
if (isDiffmark && char.IsWhiteSpace(currentChar))
pipeAllowed = true;
// we've made it to the end
if ((pipeAllowed && currentChar == '|') || currentChar == '>' || currentChar == '\n' || currentChar == '#')
break;
reader.Read();
value = string.Concat(value, currentChar);
}
return value;
}
}
internal enum DicTokenType
{
Directive,
Entry,
DiffEntry,
Property,
Ignore,
EOF
}
} | using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Rant.Stringes;
namespace Rant.Vocabulary
{
internal static class DicLexer
{
public static IEnumerable<Token<DicTokenType>> Tokenize(string data)
{
var reader = new StringReader(data);
while (true)
{
int nextChar = reader.Read();
if (nextChar == -1)
{
yield return new Token<DicTokenType>(DicTokenType.EOF, "");
yield break;
}
char currentChar = (char)nextChar;
if (char.IsWhiteSpace(currentChar))
continue;
switch (currentChar)
{
// directive
case '#':
{
string value = ReadRestOfLine(reader);
yield return new Token<DicTokenType>(DicTokenType.Directive, value.Trim());
}
break;
// entry or diffentry
case '>':
{
int peekedChar = reader.Peek();
if (peekedChar == -1)
yield break;
bool diffmark = false;
// it's a diffentry
if ((char)peekedChar == '>')
{
diffmark = true;
reader.Read();
}
string value = ReadRestOfLine(reader, diffmark);
yield return new Token<DicTokenType>(diffmark ? DicTokenType.DiffEntry : DicTokenType.Entry, value.Trim());
}
break;
// property
case '|':
{
string value = ReadRestOfLine(reader);
yield return new Token<DicTokenType>(DicTokenType.Property, value.Trim());
}
break;
default:
throw new System.Exception("Unexpected character in dictionary.");
}
}
}
private static string ReadRestOfLine(StringReader reader, bool isDiffmark = false)
{
int nextChar;
char currentChar;
string value = "";
// read to the end of the line
while (true)
{
nextChar = reader.Read();
if (nextChar == -1)
break;
currentChar = (char)nextChar;
// we've made it to the end
if ((!isDiffmark && currentChar == '|') || currentChar == '>' || currentChar == '\n' || currentChar == '#')
break;
value = string.Concat(value, currentChar);
}
return value;
}
}
internal enum DicTokenType
{
Directive,
Entry,
DiffEntry,
Property,
Ignore,
EOF
}
} | mit | C# |
4e0f2a3403bba97f49d4c3e7ba37377881b10a84 | Update KeepAlive.cs | dotnetsheff/dotnetsheff-api,dotnetsheff/dotnetsheff-api | src/dotnetsheff.Api/KeepAlive/KeepAlive.cs | src/dotnetsheff.Api/KeepAlive/KeepAlive.cs | using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace dotnetsheff.Api.KeepAlive
{
public static class KeepAlive
{
[FunctionName("KeepAlive")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, TraceWriter log)
{
// Do nothing...
}
}
}
| using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
namespace dotnetsheff.Api.KeepAlive
{
public static class KeepAlive
{
[FunctionName("KeepAlive")]
public static void Run([TimerTrigger("5 * * * *")]TimerInfo myTimer, TraceWriter log)
{
// Do nothing...
}
}
}
| mit | C# |
24e163a72dd4aa7059371e716698d1d6d672b3b4 | Fix compiling error on .net451 | unvell/ReoGrid,unvell/ReoGrid | ReoGrid/Print/WPFPrinter.cs | ReoGrid/Print/WPFPrinter.cs | /*****************************************************************************
*
* ReoGrid - .NET Spreadsheet Control
*
* https://reogrid.net/
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* Author: Jing Lu <jingwood at unvell.com>
*
* Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com>
* Copyright (c) 2012-2016 unvell.com, all rights reserved.
*
****************************************************************************/
#if PRINT
#if WPF
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using unvell.ReoGrid.Print;
namespace unvell.ReoGrid.Print
{
partial class PrintSession
{
internal void Init() { }
public void Dispose() { }
/// <summary>
/// Start output document to printer.
/// </summary>
public void Print()
{
throw new NotImplementedException("WPF Print is not implemented yet. Try use Windows Form version to print document as XPS file.");
}
}
}
namespace unvell.ReoGrid
{
partial class Worksheet
{
}
}
#endif // WPF
#endif // PRINT | /*****************************************************************************
*
* ReoGrid - .NET Spreadsheet Control
*
* https://reogrid.net/
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
* PURPOSE.
*
* Author: Jing Lu <jingwood at unvell.com>
*
* Copyright (c) 2012-2021 Jing Lu <jingwood at unvell.com>
* Copyright (c) 2012-2016 unvell.com, all rights reserved.
*
****************************************************************************/
#if PRINT
#if WPF
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using unvell.ReoGrid.Print;
namespace unvell.ReoGrid.Print
{
partial class PrintSession
{
internal void Init() { }
public void Dispose() { }
/// <summary>
/// Start output document to printer.
/// </summary>
public void Print()
{
throw new NotImplementedException("WPF Print is not implemented yet. Try use Windows Form version to print document as XPS file.");
}
}
}
namespace unvell.ReoGrid
{
partial class Worksheet
{
}
}
#endif // WPF
#endif // PRINT | mit | C# |
67668f2517eba1dd497ce932b0c172572fc126e4 | Make public property | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Core2D.Avalonia/Editor/Tools/MoveTool.cs | src/Core2D.Avalonia/Editor/Tools/MoveTool.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Core2D.Editor.Tools
{
public class MoveTool : ToolBase
{
public PathTool PathTool { get; set; }
public override string Title => "Move";
public MoveToolSettings Settings { get; set; }
public MoveTool(PathTool pathTool)
{
PathTool = pathTool;
}
public override void LeftDown(IToolContext context, double x, double y, Modifier modifier)
{
base.LeftDown(context, x, y, modifier);
PathTool.Move();
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Core2D.Editor.Tools
{
public class MoveTool : ToolBase
{
private readonly PathTool _pathTool;
public override string Title => "Move";
public MoveToolSettings Settings { get; set; }
public MoveTool(PathTool pathTool)
{
_pathTool = pathTool;
}
public override void LeftDown(IToolContext context, double x, double y, Modifier modifier)
{
base.LeftDown(context, x, y, modifier);
_pathTool.Move();
}
}
}
| mit | C# |
8ab180eab8d257bb639b4c5df95772399f1e56f5 | Fix bad unique ids in Spatialite, was losing the whole number :/ | Smartrak/TileSharp,Smartrak/TileSharp | TileSharp.Data.Spatialite/SpatialiteDataSource.cs | TileSharp.Data.Spatialite/SpatialiteDataSource.cs | using System;
using System.Collections.Generic;
using System.Data.SQLite;
using GeoAPI.Geometries;
using NetTopologySuite.Features;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
namespace TileSharp.Data.Spatialite
{
public class SpatialiteDataSource : DataSource, IDisposable
{
private readonly string _baseSql;
private readonly GaiaGeoReader _geoReader;
private readonly string _geometryColumn;
private readonly string[] _attributeColumns;
private SQLiteConnection _conn;
public SpatialiteDataSource(string connectionString, string tableName, string geometryColumn, string[] attributeColumns = null)
{
_conn = new SQLiteConnection(connectionString);
_conn.Open();
SpatialiteSharp.SpatialiteLoader.Load(_conn);
_geoReader = new GaiaGeoReader();
_geometryColumn = geometryColumn;
_attributeColumns = attributeColumns ?? new string[0];
_baseSql = string.Format(
"SELECT {0}, (ROWID + {1}) as __featureid {2} " +
"FROM {3} " +
"WHERE ROWID IN (SELECT ROWID FROM SpatialIndex WHERE f_table_name='{3}' AND search_frame=ST_GeomFromText(:envelope))", geometryColumn, ((long)DataSourceId << 32), attributeColumns == null ? "" : ", " + string.Join(", ", attributeColumns), tableName);
}
public override List<Feature> Fetch(Envelope envelope)
{
var res = new List<Feature>();
using (var comm = _conn.CreateCommand())
{
comm.CommandText = _baseSql;
var polygon = new Polygon(new LinearRing(new[]
{
new Coordinate(envelope.MinX, envelope.MinY),
new Coordinate(envelope.MaxX, envelope.MinY),
new Coordinate(envelope.MaxX, envelope.MaxY),
new Coordinate(envelope.MinX, envelope.MaxY),
new Coordinate(envelope.MinX, envelope.MinY)
}));
comm.Parameters.AddWithValue("envelope", polygon);
using (var reader = comm.ExecuteReader())
{
while (reader.Read())
{
var feature = new Feature(_geoReader.Read((byte[])reader[_geometryColumn]), new AttributesTable());
res.Add(feature);
foreach (var attr in _attributeColumns)
feature.Attributes.AddAttribute(attr, reader[attr]);
feature.Attributes.AddAttribute("__featureid", reader["__featureid"]);
}
}
}
return res;
}
public void Dispose()
{
if (_conn != null)
{
_conn.Dispose();
_conn = null;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.SQLite;
using GeoAPI.Geometries;
using NetTopologySuite.Features;
using NetTopologySuite.Geometries;
using NetTopologySuite.IO;
namespace TileSharp.Data.Spatialite
{
public class SpatialiteDataSource : DataSource, IDisposable
{
private readonly string _baseSql;
private readonly GaiaGeoReader _geoReader;
private readonly string _geometryColumn;
private readonly string[] _attributeColumns;
private SQLiteConnection _conn;
public SpatialiteDataSource(string connectionString, string tableName, string geometryColumn, string[] attributeColumns = null)
{
_conn = new SQLiteConnection(connectionString);
_conn.Open();
SpatialiteSharp.SpatialiteLoader.Load(_conn);
_geoReader = new GaiaGeoReader();
_geometryColumn = geometryColumn;
_attributeColumns = attributeColumns ?? new string[0];
_baseSql = string.Format(
"SELECT {0}, (ROWID + {1}) as __featureid {2} " +
"FROM {3} " +
"WHERE ROWID IN (SELECT ROWID FROM SpatialIndex WHERE f_table_name='{3}' AND search_frame=ST_GeomFromText(:envelope))", geometryColumn, (DataSourceId << 32), attributeColumns == null ? "" : ", " + string.Join(", ", attributeColumns), tableName);
}
public override List<Feature> Fetch(Envelope envelope)
{
var res = new List<Feature>();
using (var comm = _conn.CreateCommand())
{
comm.CommandText = _baseSql;
var polygon = new Polygon(new LinearRing(new[]
{
new Coordinate(envelope.MinX, envelope.MinY),
new Coordinate(envelope.MaxX, envelope.MinY),
new Coordinate(envelope.MaxX, envelope.MaxY),
new Coordinate(envelope.MinX, envelope.MaxY),
new Coordinate(envelope.MinX, envelope.MinY)
}));
comm.Parameters.AddWithValue("envelope", polygon);
using (var reader = comm.ExecuteReader())
{
while (reader.Read())
{
var feature = new Feature(_geoReader.Read((byte[])reader[_geometryColumn]), new AttributesTable());
res.Add(feature);
foreach (var attr in _attributeColumns)
feature.Attributes.AddAttribute(attr, reader[attr]);
feature.Attributes.AddAttribute("__featureid", reader["__featureid"]);
}
}
}
return res;
}
public void Dispose()
{
if (_conn != null)
{
_conn.Dispose();
_conn = null;
}
}
}
}
| bsd-2-clause | C# |
357fd844d7230f82c9f2af98ccf46dac7343386b | Fix TopicFilterComparer | chkr1011/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet,JTrotta/MQTTnet,chkr1011/MQTTnet,JTrotta/MQTTnet | Frameworks/MQTTnet.NetStandard/Server/MqttTopicFilterComparer.cs | Frameworks/MQTTnet.NetStandard/Server/MqttTopicFilterComparer.cs | using System;
namespace MQTTnet.Server
{
public static class MqttTopicFilterComparer
{
private static readonly char[] TopicLevelSeparator = { '/' };
public static bool IsMatch(string topic, string filter)
{
if (topic == null) throw new ArgumentNullException(nameof(topic));
if (filter == null) throw new ArgumentNullException(nameof(filter));
if (string.Equals(topic, filter, StringComparison.Ordinal))
{
return true;
}
var fragmentsTopic = topic.Split(TopicLevelSeparator, StringSplitOptions.None);
var fragmentsFilter = filter.Split(TopicLevelSeparator, StringSplitOptions.None);
// # > In either case it MUST be the last character specified in the Topic Filter [MQTT-4.7.1-2].
for (var i = 0; i < fragmentsFilter.Length; i++)
{
if (fragmentsFilter[i] == "+")
{
continue;
}
if (fragmentsFilter[i] == "#")
{
return true;
}
if (i >= fragmentsTopic.Length)
{
return false;
}
if (!string.Equals(fragmentsFilter[i], fragmentsTopic[i], StringComparison.Ordinal))
{
return false;
}
}
return fragmentsTopic.Length == fragmentsFilter.Length;
}
}
}
| using System;
namespace MQTTnet.Server
{
public static class MqttTopicFilterComparer
{
private static readonly char[] TopicLevelSeparator = { '/' };
public static bool IsMatch(string topic, string filter)
{
if (topic == null) throw new ArgumentNullException(nameof(topic));
if (filter == null) throw new ArgumentNullException(nameof(filter));
if (string.Equals(topic, filter, StringComparison.Ordinal))
{
return true;
}
var fragmentsTopic = topic.Split(TopicLevelSeparator, StringSplitOptions.None);
var fragmentsFilter = filter.Split(TopicLevelSeparator, StringSplitOptions.None);
for (var i = 0; i < fragmentsFilter.Length; i++)
{
switch (fragmentsFilter[i])
{
case "+": continue;
case "#" when i == fragmentsFilter.Length - 1: return true;
}
if (i >= fragmentsTopic.Length)
{
return false;
}
if (!string.Equals(fragmentsFilter[i], fragmentsTopic[i], StringComparison.Ordinal))
{
return false;
}
}
return fragmentsTopic.Length <= fragmentsFilter.Length;
}
}
}
| mit | C# |
272bd1fd102ccfe314e2b6b556b26341d91ac741 | Use a remote server | ravendb/ravendb.contrib | src/Raven.Client.Contrib.Tests/ServerStatusExtensionsTests.cs | src/Raven.Client.Contrib.Tests/ServerStatusExtensionsTests.cs | using System.Diagnostics;
using Raven.Abstractions.Data;
using Raven.Tests.Helpers;
using Xunit;
namespace Raven.Client.Contrib.Tests
{
public class ServerStatusExtensionsTests : RavenTestBase
{
[Fact]
public void Can_Get_Server_Build_Number()
{
using (var store = NewRemoteDocumentStore())
{
BuildNumber buildNumber;
var ok = store.TryGetServerVersion(out buildNumber);
Assert.True(ok);
Debug.WriteLine(buildNumber.ProductVersion);
Debug.WriteLine(buildNumber.BuildVersion);
}
}
[Fact]
public void Can_Get_Server_Online_Status()
{
using (var store = NewRemoteDocumentStore())
{
Assert.True(store.IsServerOnline());
}
}
}
}
| using System.Diagnostics;
using Raven.Abstractions.Data;
using Raven.Tests.Helpers;
using Xunit;
namespace Raven.Client.Contrib.Tests
{
public class ServerStatusExtensionsTests : RavenTestBase
{
[Fact]
public void Can_Get_Server_Build_Number()
{
using (var store = NewDocumentStore())
{
BuildNumber buildNumber;
var ok = store.TryGetServerVersion(out buildNumber);
Assert.True(ok);
Debug.WriteLine(buildNumber.ProductVersion);
Debug.WriteLine(buildNumber.BuildVersion);
}
}
[Fact]
public void Can_Get_Server_Online_Status()
{
using (var store = NewDocumentStore())
{
Assert.True(store.IsServerOnline());
}
}
}
}
| mit | C# |
ca2ad851cd03462d755a9a9348a70ec17b7d0305 | Check can get all the fields (except Layout and Tracking) #46 | sergeyshushlyapin/Sitecore.FakeDb,hermanussen/Sitecore.FakeDb,pveller/Sitecore.FakeDb | src/Sitecore.FakeDb.Tests/Data/Fields/FieldTypeManagerTest.cs | src/Sitecore.FakeDb.Tests/Data/Fields/FieldTypeManagerTest.cs | namespace Sitecore.FakeDb.Tests.Data.Fields
{
using FluentAssertions;
using Sitecore.Data.Fields;
using Xunit;
public class FieldTypeManagerTest
{
// TODO: Implement Layout and Tracking fields.
[Theory]
[InlineData("Checkbox")]
[InlineData("Date")]
[InlineData("Datetime")]
[InlineData("File")]
[InlineData("Image")]
[InlineData("Rich Text")]
[InlineData("Single-Line Text")]
[InlineData("Word Document")]
[InlineData("Multi-Line Text")]
[InlineData("Checklist")]
[InlineData("Droplist")]
[InlineData("Grouped Droplink")]
[InlineData("Grouped Droplist")]
[InlineData("Multilist")]
[InlineData("Multilist with Search")]
[InlineData("Name Value List")]
[InlineData("Treelist")]
[InlineData("Treelist with Search")]
[InlineData("TreelistEx")]
[InlineData("Droplink")]
[InlineData("Droptree")]
[InlineData("General Link")]
[InlineData("General Link with Search")]
[InlineData("Version Link")]
[InlineData("Frame")]
[InlineData("Rules")]
// [InlineData("Tracking")]
[InlineData("Datasource")]
[InlineData("Custom")]
[InlineData("Internal Link")]
// [InlineData("Layout")]
[InlineData("Template Field Source")]
[InlineData("File Drop Area")]
[InlineData("Page Preview")]
[InlineData("Rendering Datasource")]
[InlineData("Thumbnail")]
[InlineData("Security")]
[InlineData("UserList")]
[InlineData("html")]
[InlineData("link")]
[InlineData("lookup")]
[InlineData("reference")]
[InlineData("text")]
[InlineData("memo")]
[InlineData("tree")]
[InlineData("tree list")]
[InlineData("valuelookup")]
public void ShouldGetField(string fieldType)
{
// arrange
using (var db = new Db
{
new DbItem("home") { new DbField("field") { Type = fieldType } }
})
{
var home = db.GetItem("/sitecore/content/home");
// act & assert
FieldTypeManager.GetField(home.Fields["field"]).Should().NotBeNull();
}
}
}
} | namespace Sitecore.FakeDb.Tests.Data.Fields
{
using FluentAssertions;
using Sitecore.Data.Fields;
using Xunit;
public class FieldTypeManagerTest
{
[Fact]
public void ShouldGetField()
{
// arrange
using (var db = new Db
{
new DbItem("home")
{
new DbField("Is Active") { Type = "Checkbox", Value = "1" }
}
})
{
var home = db.GetItem("/sitecore/content/home");
// act
var customField = FieldTypeManager.GetField(home.Fields["Is Active"]);
// assert
customField.Should().NotBeNull();
customField.Value.Should().Be("1");
}
}
}
} | mit | C# |
3c9fbf51d24b247a26ca94548ed19b5d844d7731 | Fix var name | lupidan/Tetris | Assets/Scripts/ComponentPool.cs | Assets/Scripts/ComponentPool.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComponentPool<T> where T : MonoBehaviour
{
private Func<T> _instantiateAction;
private Action<T> _getComponentAction;
private Action<T> _returnComponentAction;
private Stack<T> _pooledObjects;
private int _lastInstantiatedAmount;
public ComponentPool(int initialPoolSize, Func<T> instantiateFunction, Action<T> getComponentAction = null, Action<T> returnComponentAction = null)
{
this._instantiateAction = instantiateFunction;
this._getComponentAction = getComponentAction;
this._returnComponentAction = returnComponentAction;
this._pooledObjects = new Stack<T>();
InstantiateComponentsIntoPool(initialPoolSize);
}
public T Get()
{
if (_pooledObjects.Count == 0)
InstantiateComponentsIntoPool((_lastInstantiatedAmount * 2) + 1);
T component = _pooledObjects.Pop();
if (_getComponentAction != null)
_getComponentAction(component);
return _pooledObjects.Pop();
}
public void Return(T component)
{
_pooledObjects.Push(component);
if (_returnComponentAction != null)
_returnComponentAction(component);
}
private void InstantiateComponentsIntoPool(int nComponents)
{
for (int i = 0; i < nComponents; i++)
{
var pooledObject = _instantiateAction();
_pooledObjects.Push(pooledObject);
}
_lastInstantiatedAmount = _pooledObjects.Count;
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ComponentPool<T> where T : MonoBehaviour
{
private Func<T> _instantiateAction;
private Action<T> _getComponentAction;
private Action<T> _returnComponentAction;
private Stack<T> _pooledObjects;
private int lastInstantiatedAmount;
public ComponentPool(int initialPoolSize, Func<T> instantiateFunction, Action<T> getComponentAction = null, Action<T> returnComponentAction = null)
{
this._instantiateAction = instantiateFunction;
this._getComponentAction = getComponentAction;
this._returnComponentAction = returnComponentAction;
this._pooledObjects = new Stack<T>();
InstantiateComponentsIntoPool(initialPoolSize);
}
public T Get()
{
if (this._pooledObjects.Count == 0)
InstantiateComponentsIntoPool((lastInstantiatedAmount * 2) + 1);
T component = _pooledObjects.Pop();
if (_getComponentAction != null)
_getComponentAction(component);
return _pooledObjects.Pop();
}
public void Return(T component)
{
_pooledObjects.Push(component);
if (_returnComponentAction != null)
_returnComponentAction(component);
}
private void InstantiateComponentsIntoPool(int nComponents)
{
for (int i = 0; i < nComponents; i++)
{
var pooledObject = this._instantiateAction();
_pooledObjects.Push(pooledObject);
}
lastInstantiatedAmount = _pooledObjects.Count;
}
}
| mit | C# |
fabc076fcd1a4d92285be4c09e202d16fcc2f451 | Make the `DynamicBuilder<T>` constructor public. | fffej/BobTheBuilder,alastairs/BobTheBuilder | BobTheBuilder/DynamicBuilder.cs | BobTheBuilder/DynamicBuilder.cs | using System;
using System.Dynamic;
using BobTheBuilder.ArgumentStore;
namespace BobTheBuilder
{
public class DynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class
{
private readonly IArgumentStore argumentStore;
public DynamicBuilder(IArgumentStore argumentStore)
{
if (argumentStore == null)
{
throw new ArgumentNullException("argumentStore");
}
this.argumentStore = argumentStore;
}
public virtual bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result)
{
result = this;
return true;
}
public T Build()
{
var instance = CreateInstanceOfType();
PopulatePublicSettableProperties(instance);
return instance;
}
private static T CreateInstanceOfType()
{
var instance = Activator.CreateInstance<T>();
return instance;
}
private void PopulatePublicSettableProperties(T instance)
{
var knownMembers = argumentStore.GetAllStoredMembers();
foreach (var member in knownMembers)
{
var property = typeof (T).GetProperty(member.Name);
property.SetValue(instance, member.Value);
}
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
return InvokeBuilderMethod(binder, args, out result);
}
public static implicit operator T(DynamicBuilder<T> builder)
{
return builder.Build();
}
}
} | using System;
using System.Dynamic;
using BobTheBuilder.ArgumentStore;
namespace BobTheBuilder
{
public class DynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class
{
private readonly IArgumentStore argumentStore;
protected DynamicBuilder(IArgumentStore argumentStore)
{
if (argumentStore == null)
{
throw new ArgumentNullException("argumentStore");
}
this.argumentStore = argumentStore;
}
public virtual bool InvokeBuilderMethod(InvokeMemberBinder binder, object[] args, out object result)
{
result = this;
return true;
}
public T Build()
{
var instance = CreateInstanceOfType();
PopulatePublicSettableProperties(instance);
return instance;
}
private static T CreateInstanceOfType()
{
var instance = Activator.CreateInstance<T>();
return instance;
}
private void PopulatePublicSettableProperties(T instance)
{
var knownMembers = argumentStore.GetAllStoredMembers();
foreach (var member in knownMembers)
{
var property = typeof (T).GetProperty(member.Name);
property.SetValue(instance, member.Value);
}
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
return InvokeBuilderMethod(binder, args, out result);
}
public static implicit operator T(DynamicBuilder<T> builder)
{
return builder.Build();
}
}
} | apache-2.0 | C# |
c3cbec2858824c46f79ca91f4846f6d5f9d51d68 | Implement struct DisplayMode | alesliehughes/monoDX,alesliehughes/monoDX | Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DisplayMode.cs | Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/DisplayMode.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;
namespace Microsoft.DirectX.Direct3D
{
public struct DisplayMode
{
private int height;
private int width;
private int refresh;
private Format format;
public int Height {
get {
return this.height;
}
set {
this.height = value;
}
}
public int Width {
get {
return this.width;
}
set {
this.width = value;
}
}
public int RefreshRate {
get {
return this.refresh;
}
set {
this.refresh = value;
}
}
public Format Format {
get {
return this.format;
}
set {
this.format = value;
}
}
public override string ToString ()
{
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;
namespace Microsoft.DirectX.Direct3D
{
public struct DisplayMode
{
public int Height {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
public int Width {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
public int RefreshRate {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
public Format Format {
get {
throw new NotImplementedException ();
}
set {
throw new NotImplementedException ();
}
}
public override string ToString ()
{
throw new NotImplementedException ();
}
}
} | mit | C# |
62a4fe33310420c74ac3f49ea2c9eb0bf32f2027 | IMprove unit tests | DaveSenn/Extend | PortableExtensions.Testing/System.Int64/Int64.PercentageOf.Test.cs | PortableExtensions.Testing/System.Int64/Int64.PercentageOf.Test.cs | #region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class Int64ExTest
{
[Test]
public void PercentageOfTestCase()
{
const Int64 number = 1000;
const Int32 expected = 500;
var actual = number.PercentageOf((Int64)50);
Assert.AreEqual(expected, actual);
}
[Test]
[ExpectedException(typeof(DivideByZeroException))]
public void PercentageOfTestCaseDivideByZeroException()
{
const Int64 number = 0;
number.PercentageOf((Int64)50);
}
[Test]
public void PercentageOfTestCase1()
{
const Int64 number = 1000;
const Int32 expected = 500;
var actual = number.PercentageOf((Double)50);
Assert.AreEqual(expected, actual);
}
[Test]
[ExpectedException(typeof(DivideByZeroException))]
public void PercentageOfTestCase1DivideByZeroException()
{
const Int64 number = 0;
number.PercentageOf((Double)50);
}
[Test]
public void PercentageOfTestCase2()
{
const Int64 number = 1000;
const Int32 expected = 500;
var actual = number.PercentageOf((Int64)50);
Assert.AreEqual(expected, actual);
}
[Test]
[ExpectedException(typeof(DivideByZeroException))]
public void PercentageOfTestCase2DivideByZeroException()
{
const Int64 number = 0;
number.PercentageOf((Int64)50);
}
[Test]
public void PercentageOfTestCase3()
{
const Int64 number = 1000;
const Int32 expected = 500;
var actual = number.PercentageOf(new Decimal(50));
Assert.AreEqual(expected, actual);
}
[Test]
[ExpectedException(typeof(DivideByZeroException))]
public void PercentageOfTestCase3DivideByZeroException()
{
const Int64 number = 0;
number.PercentageOf(new Decimal(50));
}
[Test]
public void PercentageOfTestCase4()
{
const Int64 number = 1000;
const Int32 expected = 500;
var actual = number.PercentageOf(50);
Assert.AreEqual(expected, actual);
}
[Test]
[ExpectedException(typeof(DivideByZeroException))]
public void PercentageOfTestCase4DivideByZeroException()
{
const Int64 number = 0;
number.PercentageOf(50);
}
}
} | #region Using
using System;
using NUnit.Framework;
#endregion
namespace PortableExtensions.Testing
{
[TestFixture]
public partial class Int64ExTest
{
[Test]
public void PercentageOfTestCase()
{
Int64 number = 1000;
var expected = 500;
var actual = number.PercentageOf( (Int64) 50 );
Assert.AreEqual( expected, actual );
}
[Test]
public void PercentageOfTestCase1()
{
Int64 number = 1000;
var expected = 500;
var actual = number.PercentageOf( (Double) 50 );
Assert.AreEqual( expected, actual );
}
[Test]
public void PercentageOfTestCase2()
{
Int64 number = 1000;
var expected = 500;
var actual = number.PercentageOf( (Int64) 50 );
Assert.AreEqual( expected, actual );
}
[Test]
public void PercentageOfTestCase3()
{
Int64 number = 1000;
var expected = 500;
var actual = number.PercentageOf( new Decimal( 50 ) );
Assert.AreEqual( expected, actual );
}
}
} | mit | C# |
e7331305cfb472a768f188e2d91e3287a86f385d | Complete a bit of necessary but forgotten code cleanup. | stacybird/CS510CouchDB,stacybird/CS510CouchDB,stacybird/CS510CouchDB | CouchTrafficClient/QueryBase.cs | CouchTrafficClient/QueryBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Dynamic;
namespace CouchTrafficClient
{
class QueryException : Exception
{
}
class QueryBase
{
public const string QueryNullResult = "null";
public string Run()
{
return "Query Client Not Implemented";
}
public string Server { get { return "http://52.10.252.48:5984/traffic/"; } }
public Dictionary<object, object> Query(string designDocumentName, string viewName, IList<object> keys = null)
{
dynamic queryResult = InternalQuery(designDocumentName, viewName, keys);
IList<object> a = queryResult.rows;
var result = new Dictionary<object, object>();
foreach (dynamic data in a)
{
result.Add(data.key ?? QueryNullResult, data.value);
}
return result;
}
private ExpandoObject InternalQuery(string designDocumentName, string viewName, IList<object> keys = null)
{
try
{
var keyString = "";
if (keys != null)
{
keyString = string.Format("?keys={0}", Uri.EscapeDataString(JsonConvert.SerializeObject(keys)));
}
var url = Server + "_design/" + designDocumentName + "/_view/" + viewName + keyString;
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
string str = wc.DownloadString(url);
return JsonConvert.DeserializeObject<ExpandoObject>(str);
}
}
catch (Exception e)
{
MessageBox.Show("Error in WebClient: " + e.ToString());
throw new QueryException();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Windows.Forms;
using System.Dynamic;
namespace CouchTrafficClient
{
class QueryException : Exception
{
}
class QueryBase
{
public const string QueryNullResult = "null";
public string Run()
{
return "Query Client Not Implemented";
}
public string Server { get { return "http://52.10.252.48:5984/traffic/"; } }
public Dictionary<object, object> Query(string designDocumentName, string viewName, IList<object> keys = null)
{
dynamic queryResult = InternalQuery("querya", "querya");
var s = JsonConvert.SerializeObject(queryResult);
IList<object> a = queryResult.rows;
var result = new Dictionary<object, object>();
foreach (dynamic data in a)
{
result.Add(data.key ?? QueryNullResult, data.value);
}
return result;
}
private ExpandoObject InternalQuery(string designDocumentName, string viewName, IList<object> keys = null)
{
try
{
var keyString = "";
if (keys != null)
{
keyString = string.Format("?keys={0}", Uri.EscapeDataString(JsonConvert.SerializeObject(keys)));
}
var url = Server + "_design/" + designDocumentName + "/_view/" + viewName + keyString;
using (WebClient wc = new WebClient())
{
wc.Encoding = System.Text.Encoding.UTF8;
wc.Headers["User-Agent"] = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
string str = wc.DownloadString(url);
return JsonConvert.DeserializeObject<ExpandoObject>(str);
}
}
catch (Exception e)
{
MessageBox.Show("Error in WebClient: " + e.ToString());
throw new QueryException();
}
}
}
}
| apache-2.0 | C# |
a58f4f368edf8ce42a38af2ef3c66e7d3bd4e548 | Increment version to 2.1.0 | Coding-Enthusiast/Watch-Only-Bitcoin-Wallet | WatchOnlyBitcoinWallet/Properties/AssemblyInfo.cs | WatchOnlyBitcoinWallet/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
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("WatchOnlyBitcoinWallet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coding Enthusiast Coders")]
[assembly: AssemblyProduct("WatchOnlyBitcoinWallet")]
[assembly: AssemblyCopyright("Copyright © C.E. 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)]
//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("2.1.0.*")]
[assembly: AssemblyFileVersion("2.1.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
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("WatchOnlyBitcoinWallet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Coding Enthusiast Coders")]
[assembly: AssemblyProduct("WatchOnlyBitcoinWallet")]
[assembly: AssemblyCopyright("Copyright © C.E. 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)]
//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("2.0.0.*")]
[assembly: AssemblyFileVersion("2.0.0.0")]
| mit | C# |
3b465af516eb8494de7cac5b79c9ca494eca4051 | Add comment | ASP-NET-MVC-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates | Source/ApiTemplate/Source/ApiTemplate/CustomJsonSerializerContext.cs | Source/ApiTemplate/Source/ApiTemplate/CustomJsonSerializerContext.cs | namespace ApiTemplate
{
using System.Text.Json.Serialization;
using ApiTemplate.ViewModels;
/// <summary>
/// Enables faster serialization and de-serialization with fewer allocations by generating source code.
/// </summary>
[JsonSerializable(typeof(Car[]))]
[JsonSerializable(typeof(Connection<Car>[]))]
[JsonSerializable(typeof(SaveCar[]))]
public partial class CustomJsonSerializerContext : JsonSerializerContext
{
}
}
| namespace ApiTemplate
{
using System.Text.Json.Serialization;
using ApiTemplate.ViewModels;
[JsonSerializable(typeof(Car[]))]
[JsonSerializable(typeof(Connection<Car>[]))]
[JsonSerializable(typeof(SaveCar[]))]
public partial class CustomJsonSerializerContext : JsonSerializerContext
{
}
}
| mit | C# |
78e929fef78857c7019703daf3fb43cdbe022b06 | Add push/pop matrix | JeremyAnsel/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit,helix-toolkit/helix-toolkit,Iluvatar82/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX/Model/Elements2D/Abstract/Model2D.cs | Source/HelixToolkit.Wpf.SharpDX/Model/Elements2D/Abstract/Model2D.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Media = System.Windows.Media;
using System.Windows;
using SharpDX;
namespace HelixToolkit.Wpf.SharpDX.Elements2D
{
using Core2D;
public abstract class Model2D : Element2D, ITransformable2D
{
public static readonly DependencyProperty TransformProperty =
DependencyProperty.Register("Transform", typeof(Media.Transform), typeof(Model2D), new AffectsRenderPropertyMetadata(Media.Transform.Identity, (d, e) =>
{
(d as Model2D).transformMatrix = e.NewValue == null ? Matrix3x2.Identity : ((Media.Transform)e.NewValue).Value.ToMatrix3x2();
}));
/// <summary>
/// Render transform
/// </summary>
public Media.Transform Transform
{
get
{
return (Media.Transform)GetValue(TransformProperty);
}
set
{
SetValue(TransformProperty, value);
}
}
protected Matrix3x2 transformMatrix { private set; get; } = Matrix3x2.Identity;
private readonly Stack<Matrix3x2> matrixStack = new Stack<Matrix3x2>();
public Matrix3x2 TransformMatrix
{
get { return this.transformMatrix; }
}
public void PushMatrix(Matrix3x2 matrix)
{
matrixStack.Push(this.transformMatrix);
this.transformMatrix = this.transformMatrix * matrix;
}
public void PopMatrix(Matrix3x2 matrix)
{
this.transformMatrix = matrixStack.Pop();
}
protected override void PreRender(RenderContext context)
{
base.PreRender(context);
renderCore.Transform = TransformMatrix;
}
protected override bool OnHitTest(ref Vector2 mousePoint, out HitTest2DResult hitResult)
{
if (renderCore.Rect.Contains(mousePoint))
{
hitResult = new HitTest2DResult(this);
return true;
}
else
{
hitResult = null;
return false;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Media = System.Windows.Media;
using System.Windows;
using SharpDX;
namespace HelixToolkit.Wpf.SharpDX.Elements2D
{
using Core2D;
public abstract class Model2D : Element2D, ITransformable2D
{
public static readonly DependencyProperty TransformProperty =
DependencyProperty.Register("Transform", typeof(Media.Transform), typeof(Model2D), new AffectsRenderPropertyMetadata(Media.Transform.Identity, (d, e) =>
{
(d as Model2D).transformMatrix = e.NewValue == null ? Matrix3x2.Identity : ((Media.Transform)e.NewValue).Value.ToMatrix3x2();
}));
/// <summary>
/// Render transform
/// </summary>
public Media.Transform Transform
{
get
{
return (Media.Transform)GetValue(TransformProperty);
}
set
{
SetValue(TransformProperty, value);
}
}
protected Matrix3x2 transformMatrix { private set; get; } = Matrix3x2.Identity;
protected override void PreRender(RenderContext context)
{
base.PreRender(context);
renderCore.Transform = transformMatrix;
}
protected override bool OnHitTest(ref Vector2 mousePoint, out HitTest2DResult hitResult)
{
if (renderCore.Rect.Contains(mousePoint))
{
hitResult = new HitTest2DResult(this);
return true;
}
else
{
hitResult = null;
return false;
}
}
}
}
| mit | C# |
ff071cb7a09e6906c6612437eb23c93e1905b96e | Test failed on integration. Trying to debug | os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos | Tests.Integration.Presentation.Web/Security/ApiAccessibilityTests.cs | Tests.Integration.Presentation.Web/Security/ApiAccessibilityTests.cs | using System;
using System.Net;
using System.Threading.Tasks;
using Core.DomainModel.Organization;
using Tests.Integration.Presentation.Web.Tools;
using Tests.Integration.Presentation.Web.Tools.Model;
using Xunit;
namespace Tests.Integration.Presentation.Web.Security
{
public class ApiAccessibilityTests : WithAutoFixture
{
private readonly KitosCredentials _globalAdmin;
public ApiAccessibilityTests()
{
_globalAdmin = TestEnvironment.GetCredentials(OrganizationRole.GlobalAdmin);
}
[Fact]
public async Task Can_Access_PublicApi_Endpoint()
{
var role = _globalAdmin.Role;
var tokenResponse = await HttpApi.GetTokenAsync(role);
var requestResponse = await HttpApi.GetAsyncWithToken(TestEnvironment.CreateUrl("api/ItSystem/"), tokenResponse.Token);
Assert.NotNull(requestResponse);
Assert.Equal(HttpStatusCode.OK, requestResponse.StatusCode);
}
[Fact]
public async Task Can_Not_Access_InternalApi_Endpoint()
{
var role = _globalAdmin.Role;
var tokenResponse = await HttpApi.GetTokenAsync(role);
var requestResponse = await HttpApi.GetAsyncWithToken(TestEnvironment.CreateUrl("api/organization/"), tokenResponse.Token);
var contentAsString = await requestResponse.Content.ReadAsStringAsync();
Assert.NotNull(requestResponse);
Assert.Equal(HttpStatusCode.Forbidden, requestResponse.StatusCode);
//Assert.Equal("Det er ikke tilladt at benytte dette endpoint", contentAsString);
}
[Fact]
public async Task Can_Not_Access_Odata_Endpoint()
{
var role = _globalAdmin.Role;
var tokenResponse = await HttpApi.GetTokenAsync(role);
var requestResponse = await HttpApi.GetAsyncWithToken(TestEnvironment.CreateUrl("odata/Organizations(1)/"), tokenResponse.Token);
var contentAsString = await requestResponse.Content.ReadAsStringAsync();
Assert.NotNull(requestResponse);
Assert.Equal(HttpStatusCode.Forbidden, requestResponse.StatusCode);
//Assert.Equal("Det er ikke tilladt at kalde odata endpoints", contentAsString);
}
}
}
| using System;
using System.Net;
using System.Threading.Tasks;
using Core.DomainModel.Organization;
using Tests.Integration.Presentation.Web.Tools;
using Tests.Integration.Presentation.Web.Tools.Model;
using Xunit;
namespace Tests.Integration.Presentation.Web.Security
{
public class ApiAccessibilityTests : WithAutoFixture
{
private readonly KitosCredentials _globalAdmin;
public ApiAccessibilityTests()
{
_globalAdmin = TestEnvironment.GetCredentials(OrganizationRole.GlobalAdmin);
}
[Fact]
public async Task Can_Access_PublicApi_Endpoint()
{
var role = _globalAdmin.Role;
var tokenResponse = await HttpApi.GetTokenAsync(role);
var requestResponse = await HttpApi.GetAsyncWithToken(TestEnvironment.CreateUrl("api/ItSystem/"), tokenResponse.Token);
Assert.NotNull(requestResponse);
Assert.Equal(HttpStatusCode.OK, requestResponse.StatusCode);
}
[Fact]
public async Task Can_Not_Access_InternalApi_Endpoint()
{
var role = _globalAdmin.Role;
var tokenResponse = await HttpApi.GetTokenAsync(role);
var requestResponse = await HttpApi.GetAsyncWithToken(TestEnvironment.CreateUrl("api/organization/"), tokenResponse.Token);
var contentAsString = await requestResponse.Content.ReadAsStringAsync();
Assert.NotNull(requestResponse);
Assert.Equal(HttpStatusCode.Forbidden, requestResponse.StatusCode);
Assert.Equal("Det er ikke tilladt at benytte dette endpoint", contentAsString);
}
[Fact]
public async Task Can_Not_Access_Odata_Endpoint()
{
var role = _globalAdmin.Role;
var tokenResponse = await HttpApi.GetTokenAsync(role);
var requestResponse = await HttpApi.GetAsyncWithToken(TestEnvironment.CreateUrl("odata/Organizations(1)/"), tokenResponse.Token);
var contentAsString = await requestResponse.Content.ReadAsStringAsync();
Assert.NotNull(requestResponse);
Assert.Equal(HttpStatusCode.Forbidden, requestResponse.StatusCode);
Assert.Equal("Det er ikke tilladt at kalde odata endpoints", contentAsString);
}
}
}
| mpl-2.0 | C# |
49077b0f69c4aa1651d65db6537385f5f1587fc5 | Add documentation for show airs. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Get/Shows/TraktShowAirs.cs | Source/Lib/TraktApiSharp/Objects/Get/Shows/TraktShowAirs.cs | namespace TraktApiSharp.Objects.Get.Shows
{
using Newtonsoft.Json;
/// <summary>The air time of a Trakt show.</summary>
public class TraktShowAirs
{
/// <summary>Gets or sets the day of week on which the show airs.</summary>
[JsonProperty(PropertyName = "day")]
public string Day { get; set; }
/// <summary>Gets or sets the time of day at which the show airs.</summary>
[JsonProperty(PropertyName = "time")]
public string Time { get; set; }
/// <summary>Gets or sets the time zone id (Olson) for the location in which the show airs.</summary>
[JsonProperty(PropertyName = "timezone")]
public string TimeZoneId { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.Shows
{
using Newtonsoft.Json;
/// <summary>
/// The air time of a Trakt show.
/// </summary>
public class TraktShowAirs
{
/// <summary>
/// The day of week on which the show airs.
/// </summary>
[JsonProperty(PropertyName = "day")]
public string Day { get; set; }
/// <summary>
/// The time of day at which the show airs.
/// </summary>
[JsonProperty(PropertyName = "time")]
public string Time { get; set; }
/// <summary>
/// The time zone id (Olson) for the location in which the show airs.
/// </summary>
[JsonProperty(PropertyName = "timezone")]
public string TimeZoneId { get; set; }
}
}
| mit | C# |
9cea63f3679d79afe5c85f54c47e212c9e2ca243 | Remove delay test for CI for now | louthy/language-ext,StefanBertels/language-ext,StanJav/language-ext | LanguageExt.Tests/DelayTests.cs | LanguageExt.Tests/DelayTests.cs | using LanguageExt;
using static LanguageExt.Prelude;
using System;
using System.Reactive.Linq;
using System.Threading;
using Xunit;
namespace LanguageExtTests
{
public class DelayTests
{
#if !CI
[Fact]
public void DelayTest1()
{
var span = TimeSpan.FromMilliseconds(500);
var till = DateTime.Now.Add(span);
var v = 0;
delay(() => 1, span).Subscribe(x => v = x);
while( DateTime.Now < till )
{
Assert.True(v == 0);
Thread.Sleep(1);
}
while (DateTime.Now < till.AddMilliseconds(100))
{
Thread.Sleep(1);
}
Assert.True(v == 1);
}
#endif
}
}
| using LanguageExt;
using static LanguageExt.Prelude;
using System;
using System.Reactive.Linq;
using System.Threading;
using Xunit;
namespace LanguageExtTests
{
public class DelayTests
{
[Fact]
public void DelayTest1()
{
var span = TimeSpan.FromMilliseconds(500);
var till = DateTime.Now.Add(span);
var v = 0;
delay(() => 1, span).Subscribe(x => v = x);
while( DateTime.Now < till.AddMilliseconds(20) )
{
Assert.True(v == 0);
Thread.Sleep(1);
}
while (DateTime.Now < till.AddMilliseconds(100))
{
Thread.Sleep(1);
}
Assert.True(v == 1);
}
}
}
| mit | C# |
c321ba5f787ff6743ab22fb8e75d6f0c37d06c42 | Test to have json overall anser | xtremboy/studies | MicroServicesHelloWorld/CurrentDateTimeModule.cs | MicroServicesHelloWorld/CurrentDateTimeModule.cs | using System;
using Nancy;
namespace MicroServicesHelloWorld{
public class CurrentDateTimeModule: NancyModule
{
public CurrentDateTimeModule()
{
Get("/", _ => {
var response = (Response)("\""+DateTime.UtcNow.ToString()+"\"");
response.ContentType = "application/json";
return response;
});
}
}
} | using System;
using Nancy;
namespace MicroServicesHelloWorld{
public class CurrentDateTimeModule: NancyModule
{
public CurrentDateTimeModule()
{
Get("/", _ => DateTime.UtcNow);
}
}
} | mit | C# |
ab38f9106f074d1d3a1e7438beb9013c18684130 | Fix typo in the CbxBundle refactoring causing the bytecode to not get copied to exported projects. | blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon | Compiler/Wax/CbxBundleView.cs | Compiler/Wax/CbxBundleView.cs | using System.Collections.Generic;
namespace Wax
{
public class CbxBundleView : JsonBasedObject
{
public string ByteCode { get { return this.GetString("byteCode"); } set { this.SetString("byteCode", value); } }
public ResourceDatabase ResourceDB { get { return this.GetObject("resources") as ResourceDatabase; } set { this.SetObject("resources", value); } }
public CbxBundleView(Dictionary<string, object> data) : base(data) { }
public CbxBundleView(string byteCode, ResourceDatabase resDb)
{
this.ByteCode = byteCode;
this.ResourceDB = resDb;
}
}
}
| using System.Collections.Generic;
namespace Wax
{
public class CbxBundleView : JsonBasedObject
{
public string ByteCode { get { return this.GetString("byteCode"); } set { this.SetString("byteCode", value); } }
public ResourceDatabase ResourceDB { get { return this.GetObject("resources") as ResourceDatabase; } set { this.SetObject("resources", value); } }
public CbxBundleView(Dictionary<string, object> data) : base(data) { }
public CbxBundleView(string byteCode, ResourceDatabase resDb)
{
this.ByteCode = ByteCode;
this.ResourceDB = resDb;
}
}
}
| mit | C# |
90e29450f49ad19da53cf5c15233d03f2006988b | fix the test case no longer applying to the latest version of the Optional serializer | uwx/DSharpPlus,uwx/DSharpPlus | DSharpPlus.MSTest/TestJson.cs | DSharpPlus.MSTest/TestJson.cs | using DSharpPlus.Entities;
using DSharpPlus.Net.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace DSharpPlus.Test
{
[TestClass]
public class TestJson
{
[TestMethod]
public void TestOptionalSerialization()
{
// ulong
Assert.AreEqual("[0]", DiscordJson.SerializeObject(new[] { new Optional<ulong?>(0UL) }));
Assert.AreEqual("[]" , DiscordJson.SerializeObject(new[] { new Optional<ulong?>() }));
// bool?
Assert.AreEqual("[true]" , DiscordJson.SerializeObject(new[] { new Optional<bool?>(true) }));
Assert.AreEqual("[false]", DiscordJson.SerializeObject(new[] { new Optional<bool?>(false) }));
Assert.AreEqual("[]" , DiscordJson.SerializeObject(new[] { new Optional<bool?>() }));
// bool
Assert.AreEqual("[true]" , DiscordJson.SerializeObject(new[] { new Optional<bool>(true) }));
Assert.AreEqual("[false]", DiscordJson.SerializeObject(new[] { new Optional<bool>(false) }));
Assert.AreEqual("[]" , DiscordJson.SerializeObject(new[] { new Optional<bool>() }));
}
}
} | using DSharpPlus.Entities;
using DSharpPlus.Net.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
namespace DSharpPlus.Test
{
[TestClass]
public class TestJson
{
[TestMethod]
public void TestOptionalSerialization()
{
// ulong
Assert.AreEqual("[0]", DiscordJson.SerializeObject(new[] { new Optional<ulong?>(0UL) }));
Assert.AreEqual("[]" , DiscordJson.SerializeObject(new[] { new Optional<ulong?>() }));
// bool
Assert.AreEqual("[true]" , DiscordJson.SerializeObject(new[] { new Optional<bool?>(true) }));
Assert.AreEqual("[false]", DiscordJson.SerializeObject(new[] { new Optional<bool?>(false) }));
Assert.AreEqual("[]" , DiscordJson.SerializeObject(new[] { new Optional<bool?>() }));
Assert.AreEqual(@"[{""HasValue"":true,""Value"":0}]", DiscordJson.SerializeObject(new[] { new Optional<ulong>(0UL) }));
// `System.InvalidOperationException: Value is not set.` wrapped in JsonSerializationException
Assert.ThrowsException<JsonSerializationException>(() =>
{
DiscordJson.SerializeObject(new[] {new Optional<ulong>()});
});
}
}
} | mit | C# |
452f0517e72918cf541fb68bb0842adfc0bd38af | Improve the error message when GetValueFromEnumMember is unable to find the enum element | Jericho/CakeMail.RestClient | CakeMail.RestClient/Utilities/ExtensionMethods.cs | CakeMail.RestClient/Utilities/ExtensionMethods.cs | using System;
using System.Linq;
using System.Runtime.Serialization;
namespace CakeMail.RestClient.Utilities
{
/// <summary>
/// Various extension methods
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Convert a DateTime into a string that can be accepted by the CakeMail API.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToCakeMailString(this DateTime value)
{
if (value == DateTime.MinValue) return Constants.EMPTY_CAKEMAIL_DATE;
return value.ToString(Constants.CAKEMAIL_DATE_FORMAT);
}
/// <summary>
/// Get the value of the 'EnumMember' attribute associated with the value.
/// </summary>
/// <param name="value">The enum value</param>
/// <returns>The string value of the 'EnumMember' attribute associated with the value</returns>
public static string GetEnumMemberValue(this Enum value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
var attrib = type.GetField(name)
.GetCustomAttributes(false)
.OfType<EnumMemberAttribute>()
.SingleOrDefault();
return (attrib == null ? "" : attrib.Value);
}
/// <summary>
/// Get the enum value associated with the 'EnumMember' attribute string value
/// </summary>
/// <typeparam name="T">The Enum type</typeparam>
/// <param name="enumMember">The value of the 'EnumMember' attribute</param>
/// <returns>The Enum value associated with the 'EnumMember' attribute</returns>
public static T GetValueFromEnumMember<T>(this string enumMember) where T : struct, IConvertible
{
var type = typeof(T);
if (!type.IsEnum) throw new NotSupportedException("Type given must be an Enum");
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute;
if (attribute != null)
{
if (attribute.Value == enumMember) return (T)field.GetValue(null);
}
else
{
if (field.Name == enumMember) return (T)field.GetValue(null);
}
}
throw new ArgumentException(string.Format("{0} does not have an element with value {1}", typeof(T), enumMember));
}
}
} | using System;
using System.Linq;
using System.Runtime.Serialization;
namespace CakeMail.RestClient.Utilities
{
/// <summary>
/// Various extension methods
/// </summary>
public static class ExtensionMethods
{
/// <summary>
/// Convert a DateTime into a string that can be accepted by the CakeMail API.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToCakeMailString(this DateTime value)
{
if (value == DateTime.MinValue) return Constants.EMPTY_CAKEMAIL_DATE;
return value.ToString(Constants.CAKEMAIL_DATE_FORMAT);
}
/// <summary>
/// Get the value of the 'EnumMember' attribute associated with the value.
/// </summary>
/// <param name="value">The enum value</param>
/// <returns>The string value of the 'EnumMember' attribute associated with the value</returns>
public static string GetEnumMemberValue(this Enum value)
{
var type = value.GetType();
var name = Enum.GetName(type, value);
var attrib = type.GetField(name)
.GetCustomAttributes(false)
.OfType<EnumMemberAttribute>()
.SingleOrDefault();
return (attrib == null ? "" : attrib.Value);
}
/// <summary>
/// Get the enum value associated with the 'EnumMember' attribite string value
/// </summary>
/// <typeparam name="T">The Enum type</typeparam>
/// <param name="enumMember">The value of the 'EnumMember' attribute</param>
/// <returns>The Enum value associated with the 'EnumMember' attribute</returns>
public static T GetValueFromEnumMember<T>(this string enumMember) where T : struct, IConvertible
{
var type = typeof(T);
if (!type.IsEnum) throw new NotSupportedException("Type given must be an Enum");
foreach (var field in type.GetFields())
{
var attribute = Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) as EnumMemberAttribute;
if (attribute != null)
{
if (attribute.Value == enumMember) return (T)field.GetValue(null);
}
else
{
if (field.Name == enumMember) return (T)field.GetValue(null);
}
}
throw new ArgumentException("Not found.", "description");
}
}
} | mit | C# |
e0beff4f4bf42430b17fd7a6c8a4e29b360038e2 | Fix a style error. | alldne/school,alldne/school | School/Lexer.cs | School/Lexer.cs | using System;
using System.IO;
namespace School
{
public class LexerException : Exception
{
public LexerException(string message) : base(message) { }
}
public abstract class Lexer
{
public const char EOF = '\x1a'; // represent end of file char
public const int EOF_TYPE = 1; // represent EOF token type
private readonly StreamReader reader;
protected char LookAhead
{
get
{
int c = reader.Peek();
if (c != -1)
return (char)c;
else
return EOF;
}
}
public Lexer(StreamReader reader)
{
this.reader = reader;
}
public void Consume()
{
reader.Read();
}
public void Match(char x)
{
if (LookAhead == x)
Consume();
else
throw new LexerException("expecting " + x + "; found " + LookAhead);
}
public abstract Token NextToken();
public abstract String GetTokenName(int tokenType);
}
}
| using System;
using System.IO;
namespace School
{
public class LexerException : Exception
{
public LexerException(string message) : base(message) { }
}
public abstract class Lexer
{
public const char EOF = '\x1a'; // represent end of file char
public const int EOF_TYPE = 1; // represent EOF token type
private readonly StreamReader reader;
protected char LookAhead
{
get
{
int c = reader.Peek();
if (c != -1)
return (char)c;
else
return EOF;
}
}
public Lexer(StreamReader reader)
{
this.reader = reader;
}
public void Consume() {
reader.Read();
}
public void Match(char x)
{
if (LookAhead == x)
Consume();
else
throw new LexerException("expecting " + x + "; found " + LookAhead);
}
public abstract Token NextToken();
public abstract String GetTokenName(int tokenType);
}
}
| apache-2.0 | C# |
87792a862630ffe397e2ccbd2c98b000eb1a9a3b | Fix Extra GC Alloc | NewbieGameCoder/WaitForSecondsCache | WaitForSecondsCache.cs | WaitForSecondsCache.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WaitForSecondsCache
{
const int unitSize = 8;
const int cacheSize = 64;
const int fractionalPartMultiplicand = 100;
static LinkedList<int> cacheQueue = new LinkedList<int>();
static Dictionary<int, WaitForSeconds> cache = new Dictionary<int, WaitForSeconds>(cacheSize);
public static WaitForSeconds Wait(float waitingTime)
{
WaitForSeconds unit = null;
int clippedNumber = (int)(fractionalPartMultiplicand * waitingTime);
cache.TryGetValue(clippedNumber, out unit);
if (unit == null)
{
if (cache.Count >= cacheSize)
{
cache.Remove(cacheQueue.Last.Value);
cacheQueue.RemoveLast();
}
unit = new WaitForSeconds(waitingTime);
cache.Add(clippedNumber, unit);
}
if (cacheQueue.Count == 0) cacheQueue.AddFirst(clippedNumber);
else MoveToTop(clippedNumber);
return unit;
}
#if UNITY_5_4_OR_NEWER
static LinkedList<int> realTimeCacheQueue = new LinkedList<int>();
static Dictionary<int, WaitForSecondsRealtime> realTimeCache = new Dictionary<int, WaitForSecondsRealtime>(cacheSize);
public static WaitForSecondsRealtime WaitForRealTime(float waitingTime)
{
WaitForSecondsRealtime unit = null;
int clippedNumber = (int)(fractionalPartMultiplicand * waitingTime);
realTimeCache.TryGetValue(clippedNumber, out unit);
if (unit == null)
{
if (realTimeCache.Count >= cacheSize)
{
realTimeCache.Remove(realTimeCacheQueue.Last.Value);
realTimeCacheQueue.RemoveLast();
}
unit = new WaitForSecondsRealtime(waitingTime);
realTimeCache.Add(clippedNumber, unit);
}
if (realTimeCacheQueue.Count == 0) realTimeCacheQueue.AddFirst(clippedNumber);
else MoveToTop(clippedNumber);
return unit;
}
#endif
static void MoveToTop(int elementValue)
{
LinkedListNode<int> existElement = null;
existElement = cacheQueue.First;
do
{
if (existElement.Value == elementValue)
break;
existElement = existElement.Next;
}
while (existElement != null);
if (existElement != null)
{
cacheQueue.Remove(existElement);
cacheQueue.AddFirst(existElement);
}
else cacheQueue.AddFirst(elementValue);
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class WaitForSecondsCache
{
const int unitSize = 8;
const int cacheSize = 64;
const int fractionalPartMultiplicand = 100;
static LinkedList<int> cacheQueue = new LinkedList<int>();
static Dictionary<int, Stack<WaitForSeconds>> cache = new Dictionary<int, Stack<WaitForSeconds>>(cacheSize);
public static IEnumerator Wait(float waitingTime)
{
WaitForSeconds unit = null;
Stack<WaitForSeconds> unitList = null;
int clippedNumber = (int)(fractionalPartMultiplicand * waitingTime);
cache.TryGetValue(clippedNumber, out unitList);
if (unitList == null)
{
if (cache.Count >= cacheSize)
{
cache.TryGetValue(cacheQueue.Last.Value, out unitList);
cache.Remove(cacheQueue.Last.Value);
cacheQueue.RemoveLast();
unitList.Clear();
}
else unitList = new Stack<WaitForSeconds>(unitSize);
cache.Add(clippedNumber, unitList);
}
if (unitList.Count == 0) unit = new WaitForSeconds(waitingTime);
else unit = unitList.Pop();
if (cacheQueue.Count == 0) cacheQueue.AddFirst(clippedNumber);
else MoveToTop(clippedNumber);
yield return unit;
cache.TryGetValue(clippedNumber, out unitList);
if (unitList != null && unitList.Count < unitSize) unitList.Push(unit);
}
static void MoveToTop(int elementValue)
{
var existElement = cacheQueue.Find(elementValue);
if (existElement != null)
{
cacheQueue.Remove(existElement);
cacheQueue.AddFirst(existElement);
}
else cacheQueue.AddFirst(elementValue);
}
}
| mit | C# |
1d972ac6e0793dc24d91bddcd32c59efc5b4a0b5 | Comment out failing tests | schlos/denver-schedules-api,schlos/denver-schedules-api,codeforamerica/denver-schedules-api,codeforamerica/denver-schedules-api | Schedules.API.Tests/Modules/ReminderTypesTests.cs | Schedules.API.Tests/Modules/ReminderTypesTests.cs | using NUnit.Framework;
using System;
using Nancy.Testing;
using Schedules.API.Models;
using System.Collections.Generic;
namespace Schedules.API.Tests.Modules
{
[TestFixture()]
public class ReminderTypesTests
{
Browser browser;
[SetUp]
public void SetUp()
{
browser = new Browser(new CustomBootstrapper());
}
// [Test ()]
// public void GetShouldAllowAllOrigins()
// {
// var response = browser.Get("/reminderTypes", with => with.HttpRequest());
// Assert.That(response.Headers["Access-Control-Allow-Origin"], Is.EqualTo("*"));
// }
//
// [Test ()]
// public void GetShouldReturnOK()
// {
// var response = browser.Get("/reminderTypes", with => with.HttpRequest());
// Assert.AreEqual(Nancy.HttpStatusCode.OK, response.StatusCode);
// }
//
// [Test ()]
// public void GetShouldReturnJson()
// {
// var response = browser.Get("/reminderTypes", with => with.HttpRequest());
// Assert.AreEqual ("application/json; charset=utf-8", response.ContentType);
// }
//
// [Test()]
// public void GetShouldReturnAllTypes()
// {// If adding a new reminder type breaks the API, we should have a test that reminds us of that
// var response = browser.Get("/reminderTypes", with => with.HttpRequest());
// var reminderTypes = response.Context.JsonBody<List<ReminderType>>();
// Assert.That (reminderTypes.Count, Is.EqualTo(3));
// }
}
}
| using NUnit.Framework;
using System;
using Nancy.Testing;
using Schedules.API.Models;
using System.Collections.Generic;
namespace Schedules.API.Tests.Modules
{
[TestFixture()]
public class ReminderTypesTests
{
Browser browser;
[SetUp]
public void SetUp()
{
browser = new Browser(new CustomBootstrapper());
}
[Test ()]
public void GetShouldAllowAllOrigins()
{
var response = browser.Get("/reminderTypes", with => with.HttpRequest());
Assert.That(response.Headers["Access-Control-Allow-Origin"], Is.EqualTo("*"));
}
[Test ()]
public void GetShouldReturnOK()
{
var response = browser.Get("/reminderTypes", with => with.HttpRequest());
Assert.AreEqual(Nancy.HttpStatusCode.OK, response.StatusCode);
}
[Test ()]
public void GetShouldReturnJson()
{
var response = browser.Get("/reminderTypes", with => with.HttpRequest());
Assert.AreEqual ("application/json; charset=utf-8", response.ContentType);
}
[Test()]
public void GetShouldReturnAllTypes()
{// If adding a new reminder type breaks the API, we should have a test that reminds us of that
var response = browser.Get("/reminderTypes", with => with.HttpRequest());
var reminderTypes = response.Context.JsonBody<List<ReminderType>>();
Assert.That (reminderTypes.Count, Is.EqualTo(3));
}
}
}
| mit | C# |
85bf9709157571d985222543d2ad95baf61f59b8 | Make watermark darker | Dziemborowicz/Hourglass | Hourglass/WatermarkAdorner.cs | Hourglass/WatermarkAdorner.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace Hourglass
{
public class WatermarkAdorner : Adorner
{
private readonly ContentPresenter contentPresenter;
public WatermarkAdorner(UIElement adornedElement, object watermark)
: base(adornedElement)
{
this.contentPresenter = new ContentPresenter();
this.contentPresenter.Content = watermark;
this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
this.contentPresenter.Opacity = 0.5;
this.IsHitTestVisible = false;
}
protected override Size ArrangeOverride(Size finalSize)
{
contentPresenter.Arrange(new Rect(finalSize));
TextBox textBox = AdornedElement as TextBox;
if (textBox != null)
{
TextElement.SetFontFamily(contentPresenter, textBox.FontFamily);
TextElement.SetFontSize(contentPresenter, textBox.FontSize);
}
ComboBox comboBox = AdornedElement as ComboBox;
if (comboBox != null)
{
TextElement.SetFontFamily(contentPresenter, comboBox.FontFamily);
TextElement.SetFontSize(contentPresenter, comboBox.FontSize);
}
return finalSize;
}
protected override Visual GetVisualChild(int index)
{
return contentPresenter;
}
protected override Size MeasureOverride(Size constraint)
{
contentPresenter.Measure(((Control)AdornedElement).RenderSize);
return ((Control)AdornedElement).RenderSize;
}
protected override int VisualChildrenCount
{
get { return 1; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace Hourglass
{
public class WatermarkAdorner : Adorner
{
private readonly ContentPresenter contentPresenter;
public WatermarkAdorner(UIElement adornedElement, object watermark)
: base(adornedElement)
{
this.contentPresenter = new ContentPresenter();
this.contentPresenter.Content = watermark;
this.contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
this.contentPresenter.Opacity = 0.25;
this.IsHitTestVisible = false;
}
protected override Size ArrangeOverride(Size finalSize)
{
contentPresenter.Arrange(new Rect(finalSize));
TextBox textBox = AdornedElement as TextBox;
if (textBox != null)
{
TextElement.SetFontFamily(contentPresenter, textBox.FontFamily);
TextElement.SetFontSize(contentPresenter, textBox.FontSize);
}
ComboBox comboBox = AdornedElement as ComboBox;
if (comboBox != null)
{
TextElement.SetFontFamily(contentPresenter, comboBox.FontFamily);
TextElement.SetFontSize(contentPresenter, comboBox.FontSize);
}
return finalSize;
}
protected override Visual GetVisualChild(int index)
{
return contentPresenter;
}
protected override Size MeasureOverride(Size constraint)
{
contentPresenter.Measure(((Control)AdornedElement).RenderSize);
return ((Control)AdornedElement).RenderSize;
}
protected override int VisualChildrenCount
{
get { return 1; }
}
}
}
| mit | C# |
db52eec58f1eb9482632f0bced98410a371c66a8 | Update CreatingSubtotals.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Data/Processing/CreatingSubtotals.cs | Examples/CSharp/Data/Processing/CreatingSubtotals.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Data.Processing
{
public class CreatingSubtotals
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a new workbook
//Open the template file
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Get the Cells collection in the first worksheet
Cells cells = workbook.Worksheets[0].Cells;
//Create a cellarea i.e.., B3:C19
CellArea ca = new CellArea();
ca.StartRow = 2;
ca.StartColumn = 1;
ca.EndRow = 18;
ca.EndColumn = 2;
//Apply subtotal, the consolidation function is Sum and it will applied to
//Second column (C) in the list
cells.Subtotal(ca, 0, ConsolidationFunction.Sum, new int[] { 1 });
//Save the excel file
workbook.Save(dataDir + "output.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Data.Processing
{
public class CreatingSubtotals
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a new workbook
//Open the template file
Workbook workbook = new Workbook(dataDir + "book1.xls");
//Get the Cells collection in the first worksheet
Cells cells = workbook.Worksheets[0].Cells;
//Create a cellarea i.e.., B3:C19
CellArea ca = new CellArea();
ca.StartRow = 2;
ca.StartColumn = 1;
ca.EndRow = 18;
ca.EndColumn = 2;
//Apply subtotal, the consolidation function is Sum and it will applied to
//Second column (C) in the list
cells.Subtotal(ca, 0, ConsolidationFunction.Sum, new int[] { 1 });
//Save the excel file
workbook.Save(dataDir + "output.out.xls");
}
}
} | mit | C# |
0dcc0330608364f59ed2e8e9cd538d691b9840ec | Refactor Instruction.WriteTo | jonathanvdc/cs-wasm,jonathanvdc/cs-wasm | libwasm/Instructions/Instruction.cs | libwasm/Instructions/Instruction.cs | using System.IO;
using System.Text;
using Wasm.Binary;
namespace Wasm.Instructions
{
/// <summary>
/// Describes a WebAssembly stack machine instruction.
/// </summary>
public abstract class Instruction
{
/// <summary>
/// Gets the operator for this instruction.
/// </summary>
/// <returns>The instruction's operator.</returns>
public abstract IOperator Operator { get; }
/// <summary>
/// Writes this instruction's immediates (but not its opcode)
/// to the given WebAssembly file writer.
/// </summary>
/// <param name="Writer">The writer to write this instruction's immediates to.</param>
public abstract void WriteImmediatesTo(BinaryWasmWriter Writer);
/// <summary>
/// Writes this instruction's opcode and immediates to the given
/// WebAssembly file writer.
/// </summary>
/// <param name="Writer">The writer to write this instruction to.</param>
public void WriteTo(BinaryWasmWriter Writer)
{
Writer.Writer.Write(Operator.OpCode);
WriteImmediatesTo(Writer);
}
/// <summary>
/// Writes a string representation of this instruction to the given text writer.
/// </summary>
/// <param name="Writer">
/// The writer to which a representation of this instruction is written.
/// </param>
public virtual void Dump(TextWriter Writer)
{
Writer.WriteLine(Operator.Mnemonic);
}
/// <summary>
/// Creates a string representation of this instruction.
/// </summary>
/// <returns>The instruction's string representation.</returns>
public override string ToString()
{
var builder = new StringBuilder();
Dump(new StringWriter(builder));
return builder.ToString();
}
}
} | using System.IO;
using System.Text;
using Wasm.Binary;
namespace Wasm.Instructions
{
/// <summary>
/// Describes a WebAssembly stack machine instruction.
/// </summary>
public abstract class Instruction
{
/// <summary>
/// Gets the operator for this instruction.
/// </summary>
/// <returns>The instruction's operator.</returns>
public abstract IOperator Operator { get; }
/// <summary>
/// Writes this instruction's data to the given WebAssembly file writer.
/// </summary>
/// <param name="Writer">The writer to write this instruction to.</param>
public abstract void WriteTo(BinaryWasmWriter Writer);
/// <summary>
/// Writes a string representation of this instruction to the given text writer.
/// </summary>
/// <param name="Writer">
/// The writer to which a representation of this instruction is written.
/// </param>
public virtual void Dump(TextWriter Writer)
{
Writer.WriteLine(Operator.Mnemonic);
}
/// <summary>
/// Creates a string representation of this instruction.
/// </summary>
/// <returns>The instruction's string representation.</returns>
public override string ToString()
{
var builder = new StringBuilder();
Dump(new StringWriter(builder));
return builder.ToString();
}
}
} | mit | C# |
d269bcc0ac0ed97add2b159f109b1544d103eae1 | Add a DebuggerDisplay attr | modulexcite/dnlib,Arthur2e5/dnlib,kiootic/dnlib,0xd4d/dnlib,ilkerhalil/dnlib,picrap/dnlib,jorik041/dnlib,ZixiangBoy/dnlib,yck1509/dnlib | src/DotNet/SimpleLazyList.cs | src/DotNet/SimpleLazyList.cs | using System.Diagnostics;
namespace dot10.DotNet {
/// <summary>
/// A readonly list that gets initialized lazily
/// </summary>
/// <typeparam name="T">A <see cref="ICodedToken"/> type</typeparam>
[DebuggerDisplay("Count = {Length}")]
class SimpleLazyList<T> where T : class, IMDTokenProvider {
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
T[] elements;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool[] initialized;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
readonly MFunc<uint, T> readElementByRID;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
readonly uint length;
/// <summary>
/// Gets the length of this list
/// </summary>
public uint Length {
get { return length; }
}
/// <summary>
/// Access the list
/// </summary>
/// <param name="index">Index</param>
/// <returns>The element or null if <paramref name="index"/> is invalid</returns>
public T this[uint index] {
get {
if (elements == null) {
elements = new T[length];
initialized = new bool[length];
}
if (index >= length)
return null;
if (!initialized[index]) {
elements[index] = readElementByRID(index + 1);
initialized[index] = true;
}
return elements[index];
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Length of the list</param>
/// <param name="readElementByRID">Delegate instance that lazily reads an element</param>
public SimpleLazyList(uint length, MFunc<uint, T> readElementByRID) {
this.length = length;
this.readElementByRID = readElementByRID;
}
}
}
| namespace dot10.DotNet {
/// <summary>
/// A readonly list that gets initialized lazily
/// </summary>
/// <typeparam name="T">A <see cref="ICodedToken"/> type</typeparam>
class SimpleLazyList<T> where T : class, IMDTokenProvider {
T[] elements;
bool[] initialized;
readonly MFunc<uint, T> readElementByRID;
readonly uint length;
/// <summary>
/// Gets the length of this list
/// </summary>
public uint Length {
get { return length; }
}
/// <summary>
/// Access the list
/// </summary>
/// <param name="index">Index</param>
/// <returns>The element or null if <paramref name="index"/> is invalid</returns>
public T this[uint index] {
get {
if (elements == null) {
elements = new T[length];
initialized = new bool[length];
}
if (index >= length)
return null;
if (!initialized[index]) {
elements[index] = readElementByRID(index + 1);
initialized[index] = true;
}
return elements[index];
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Length of the list</param>
/// <param name="readElementByRID">Delegate instance that lazily reads an element</param>
public SimpleLazyList(uint length, MFunc<uint, T> readElementByRID) {
this.length = length;
this.readElementByRID = readElementByRID;
}
}
}
| mit | C# |
c0a18312414f12d021e019a24f9d2f2e1f87d014 | Update SkillController.cs | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.WebApp/Controllers/SkillsController.cs | NinjaHive.WebApp/Controllers/SkillsController.cs | using System;
using System.Web.Mvc;
using NinjaHive.Contract.Commands;
using NinjaHive.Contract.DTOs;
using NinjaHive.Contract.Queries;
using NinjaHive.Core;
using NinjaHive.WebApp.Services;
namespace NinjaHive.WebApp.Controllers
{
public class SkillsController : Controller
{
private readonly IQueryProcessor queryProcessor;
private readonly ICommandHandler<EditSkillCommand> editSkillCommandHandler;
private readonly ICommandHandler<DeleteSkillCommand> deleteSkillCommandHandler;
public SkillsController(
IQueryProcessor queryProcessor,
ICommandHandler<EditSkillCommand> editSkillCommandHandler,
ICommandHandler<DeleteSkillCommand> deleteSkillCommandHandler)
{
this.queryProcessor = queryProcessor;
this.editSkillCommandHandler = editSkillCommandHandler;
this.deleteSkillCommandHandler = deleteSkillCommandHandler;
}
// GET: Skills
public ActionResult Index()
{
var skills = this.queryProcessor.Execute(new GetAllSkillsQuery());
return View(skills);
}
public ActionResult Edit(Guid skillId)
{
var skill = this.queryProcessor.Execute(new GetEntityByIdQuery<Skill>(skillId));
return View(skill);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Skill skill)
{
skill.Id = Guid.NewGuid();
var command = new EditSkillCommand(skill, createNew: true);
this.editSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
public ActionResult Delete(Skill skill)
{
var command = new DeleteSkillCommand()
{
Skill = skill
};
deleteSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
}
} | using System;
using System.Web.Mvc;
using NinjaHive.Contract.Commands;
using NinjaHive.Contract.DTOs;
using NinjaHive.Contract.Queries;
using NinjaHive.Core;
using NinjaHive.WebApp.Services;
namespace NinjaHive.WebApp.Controllers
{
public class SkillsController : Controller
{
private readonly IQueryProcessor queryProcessor;
private readonly ICommandHandler<EditSkillCommand> editSkillCommandHandler;
private readonly ICommandHandler<DeleteSkillCommand> deleteSkillCommandHandler;
public SkillsController(
IQueryProcessor queryProcessor,
ICommandHandler<EditSkillCommand> editSkillCommandHandler,
ICommandHandler<DeleteSkillCommand> deleteSkillCommandHandler)
{
this.queryProcessor = queryProcessor;
this.editSkillCommandHandler = editSkillCommandHandler;
this.deleteSkillCommandHandler = deleteSkillCommandHandler;
}
// GET: Skills
public ActionResult Index()
{
var skills = this.queryProcessor.Execute(new GetAllSkillsQuery());
return View(skills);
}
public ActionResult Create()
{
return View();
}
public ActionResult Edit(Guid skillId)
{
var skill = this.queryProcessor.Execute(new GetEntityByIdQuery<Skill>(skillId));
return View(skill);
}
[HttpPost]
public ActionResult Create(Skill skill)
{
skill.Id = Guid.NewGuid();
var command = new EditSkillCommand(skill, createNew: true);
this.editSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
public ActionResult Delete(Skill skill)
{
var command = new DeleteSkillCommand()
{
Skill = skill
};
deleteSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
}
} | apache-2.0 | C# |
257209b78de2cdde91212e1604126021bdc752e4 | add assert to add test to empty tree | kusl/Tree | VisualTree/TreeLibraryTests/BinarySearchTreeTests.cs | VisualTree/TreeLibraryTests/BinarySearchTreeTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using TreeLibrary;
namespace TreeLibraryTests
{
[TestClass]
public class BinarySearchTreeTests
{
[TestMethod]
public void CreateNullTree()
{
BinarySearchTree bst = new BinarySearchTree();
Assert.IsNull(bst.Root);
}
[TestMethod]
public void TestIsEmptyForEmptyTree()
{
BinarySearchTree bst = new BinarySearchTree();
Assert.IsNull(bst.Root);
Assert.IsTrue(bst.IsEmpty());
}
[TestMethod]
public void TestIsEmptyTreeNonEmpty()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
Assert.IsFalse(bst.IsEmpty());
}
[TestMethod]
public void AddNodeToNullTree()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
Assert.AreEqual(5, bst.Root.Value);
Assert.AreEqual(1, bst.Count);
}
[TestMethod]
public void RemoveRootWithNoChildren()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
bst.Remove(5);
Assert.IsNull(bst.Root);
}
[TestMethod]
public void SearchEmptyTree()
{
BinarySearchTree bst = new BinarySearchTree();
Assert.IsFalse(bst.Contains(5));
}
[TestMethod]
public void SearchTreeWithJustRootNode()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
Assert.IsTrue(bst.Contains(5));
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using TreeLibrary;
namespace TreeLibraryTests
{
[TestClass]
public class BinarySearchTreeTests
{
[TestMethod]
public void CreateNullTree()
{
BinarySearchTree bst = new BinarySearchTree();
Assert.IsNull(bst.Root);
}
[TestMethod]
public void TestIsEmptyForEmptyTree()
{
BinarySearchTree bst = new BinarySearchTree();
Assert.IsNull(bst.Root);
Assert.IsTrue(bst.IsEmpty());
}
[TestMethod]
public void TestIsEmptyTreeNonEmpty()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
Assert.IsFalse(bst.IsEmpty());
}
[TestMethod]
public void AddNodeToNullTree()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
Assert.AreEqual(5, bst.Root.Value);
}
[TestMethod]
public void RemoveRootWithNoChildren()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
bst.Remove(5);
Assert.IsNull(bst.Root);
}
[TestMethod]
public void SearchEmptyTree()
{
BinarySearchTree bst = new BinarySearchTree();
Assert.IsFalse(bst.Contains(5));
}
[TestMethod]
public void SearchTreeWithJustRootNode()
{
BinarySearchTree bst = new BinarySearchTree();
bst.Add(5);
Assert.IsTrue(bst.Contains(5));
}
}
}
| agpl-3.0 | C# |
01b47c1a7cec43cf23285cd68579a03143ebf063 | Update BrowserTool.cs | wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/UI/Avalonia/Dock/Tools/BrowserTool.cs | src/Core2D/UI/Avalonia/Dock/Tools/BrowserTool.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DMC = Dock.Model.Controls;
namespace Core2D.UI.Avalonia.Dock.Tools
{
/// <summary>
/// Browser view.
/// </summary>
public class BrowserTool : DMC.Tool
{
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using DMC=Dock.Model.Controls;
namespace Core2D.UI.Avalonia.Dock.Tools
{
/// <summary>
/// Browser view.
/// </summary>
public class BrowserTool : DMC.Tool
{
}
}
| mit | C# |
2bdd2d9d0dd273623246a8cef099cb0079bec364 | add const helloworld | kuroblog/Helloworld | SourceCode/Helloworld/Helloworld.Basic/Program.cs | SourceCode/Helloworld/Helloworld.Basic/Program.cs |
namespace Helloworld.Basic
{
using System;
class Program
{
private const string Helloworld = nameof(Helloworld);
static void Main(string[] args)
{
Console.WriteLine(Helloworld);
Console.ReadKey();
}
}
}
|
namespace Helloworld.Basic
{
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Helloworld!");
Console.ReadKey();
}
}
}
| mit | C# |
346da57c108fdaa400de7647707b5cd6342f80c4 | Add OnDelete and OnUpdate to the ForeignKey Clone method | modulexcite/fluentmigrator,DefiSolutions/fluentmigrator,daniellee/fluentmigrator,daniellee/fluentmigrator,lahma/fluentmigrator,tohagan/fluentmigrator,igitur/fluentmigrator,lahma/fluentmigrator,akema-fr/fluentmigrator,eloekset/fluentmigrator,KaraokeStu/fluentmigrator,bluefalcon/fluentmigrator,stsrki/fluentmigrator,IRlyDontKnow/fluentmigrator,igitur/fluentmigrator,schambers/fluentmigrator,itn3000/fluentmigrator,DefiSolutions/fluentmigrator,FabioNascimento/fluentmigrator,fluentmigrator/fluentmigrator,wolfascu/fluentmigrator,lcharlebois/fluentmigrator,vgrigoriu/fluentmigrator,eloekset/fluentmigrator,jogibear9988/fluentmigrator,istaheev/fluentmigrator,IRlyDontKnow/fluentmigrator,barser/fluentmigrator,vgrigoriu/fluentmigrator,dealproc/fluentmigrator,tohagan/fluentmigrator,mstancombe/fluentmig,mstancombe/fluentmig,fluentmigrator/fluentmigrator,schambers/fluentmigrator,amroel/fluentmigrator,ManfredLange/fluentmigrator,wolfascu/fluentmigrator,MetSystem/fluentmigrator,lcharlebois/fluentmigrator,drmohundro/fluentmigrator,drmohundro/fluentmigrator,KaraokeStu/fluentmigrator,bluefalcon/fluentmigrator,spaccabit/fluentmigrator,swalters/fluentmigrator,ManfredLange/fluentmigrator,mstancombe/fluentmigrator,dealproc/fluentmigrator,stsrki/fluentmigrator,jogibear9988/fluentmigrator,MetSystem/fluentmigrator,tommarien/fluentmigrator,modulexcite/fluentmigrator,ManfredLange/fluentmigrator,alphamc/fluentmigrator,tohagan/fluentmigrator,DefiSolutions/fluentmigrator,istaheev/fluentmigrator,spaccabit/fluentmigrator,alphamc/fluentmigrator,barser/fluentmigrator,mstancombe/fluentmigrator,istaheev/fluentmigrator,mstancombe/fluentmig,daniellee/fluentmigrator,swalters/fluentmigrator,lahma/fluentmigrator,FabioNascimento/fluentmigrator,itn3000/fluentmigrator,amroel/fluentmigrator,tommarien/fluentmigrator,akema-fr/fluentmigrator | src/FluentMigrator/Model/ForeignKeyDefinition.cs | src/FluentMigrator/Model/ForeignKeyDefinition.cs | #region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Infrastructure;
namespace FluentMigrator.Model
{
public class ForeignKeyDefinition : ICloneable, ICanBeConventional, ICanBeValidated
{
public virtual string Name { get; set; }
public virtual string ForeignTable { get; set; }
public virtual string ForeignTableSchema { get; set; }
public virtual string PrimaryTable { get; set; }
public virtual string PrimaryTableSchema { get; set; }
public virtual Rule OnDelete { get; set; }
public virtual Rule OnUpdate { get; set; }
public virtual ICollection<string> ForeignColumns { get; set; }
public virtual ICollection<string> PrimaryColumns { get; set; }
public ForeignKeyDefinition()
{
ForeignColumns = new List<string>();
PrimaryColumns = new List<string>();
}
public void ApplyConventions(IMigrationConventions conventions)
{
if (String.IsNullOrEmpty(Name))
Name = conventions.GetForeignKeyName(this);
}
public virtual void CollectValidationErrors(ICollection<string> errors)
{
if (String.IsNullOrEmpty(Name))
errors.Add(ErrorMessages.ForeignKeyNameCannotBeNullOrEmpty);
if (String.IsNullOrEmpty(ForeignTable))
errors.Add(ErrorMessages.ForeignTableNameCannotBeNullOrEmpty);
if (String.IsNullOrEmpty(PrimaryTable))
errors.Add(ErrorMessages.PrimaryTableNameCannotBeNullOrEmpty);
if (!String.IsNullOrEmpty(ForeignTable) && !String.IsNullOrEmpty(PrimaryTable) && ForeignTable.Equals(PrimaryTable))
errors.Add(ErrorMessages.ForeignKeyCannotBeSelfReferential);
if (ForeignColumns.Count == 0)
errors.Add(ErrorMessages.ForeignKeyMustHaveOneOrMoreForeignColumns);
if (PrimaryColumns.Count == 0)
errors.Add(ErrorMessages.ForeignKeyMustHaveOneOrMorePrimaryColumns);
}
public object Clone()
{
return new ForeignKeyDefinition
{
Name = Name,
ForeignTableSchema = ForeignTableSchema,
ForeignTable = ForeignTable,
PrimaryTableSchema = PrimaryTableSchema,
PrimaryTable = PrimaryTable,
ForeignColumns = new List<string>(ForeignColumns),
PrimaryColumns = new List<string>(PrimaryColumns),
OnDelete = OnDelete,
OnUpdate = OnUpdate
};
}
}
} | #region License
//
// Copyright (c) 2007-2009, Sean Chambers <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Data;
using FluentMigrator.Infrastructure;
namespace FluentMigrator.Model
{
public class ForeignKeyDefinition : ICloneable, ICanBeConventional, ICanBeValidated
{
public virtual string Name { get; set; }
public virtual string ForeignTable { get; set; }
public virtual string ForeignTableSchema { get; set; }
public virtual string PrimaryTable { get; set; }
public virtual string PrimaryTableSchema { get; set; }
public virtual Rule OnDelete { get; set; }
public virtual Rule OnUpdate { get; set; }
public virtual ICollection<string> ForeignColumns { get; set; }
public virtual ICollection<string> PrimaryColumns { get; set; }
public ForeignKeyDefinition()
{
ForeignColumns = new List<string>();
PrimaryColumns = new List<string>();
}
public void ApplyConventions(IMigrationConventions conventions)
{
if (String.IsNullOrEmpty(Name))
Name = conventions.GetForeignKeyName(this);
}
public virtual void CollectValidationErrors(ICollection<string> errors)
{
if (String.IsNullOrEmpty(Name))
errors.Add(ErrorMessages.ForeignKeyNameCannotBeNullOrEmpty);
if (String.IsNullOrEmpty(ForeignTable))
errors.Add(ErrorMessages.ForeignTableNameCannotBeNullOrEmpty);
if (String.IsNullOrEmpty(PrimaryTable))
errors.Add(ErrorMessages.PrimaryTableNameCannotBeNullOrEmpty);
if (!String.IsNullOrEmpty(ForeignTable) && !String.IsNullOrEmpty(PrimaryTable) && ForeignTable.Equals(PrimaryTable))
errors.Add(ErrorMessages.ForeignKeyCannotBeSelfReferential);
if (ForeignColumns.Count == 0)
errors.Add(ErrorMessages.ForeignKeyMustHaveOneOrMoreForeignColumns);
if (PrimaryColumns.Count == 0)
errors.Add(ErrorMessages.ForeignKeyMustHaveOneOrMorePrimaryColumns);
}
public object Clone()
{
return new ForeignKeyDefinition
{
Name = Name,
ForeignTableSchema = ForeignTableSchema,
ForeignTable = ForeignTable,
PrimaryTableSchema = PrimaryTableSchema,
PrimaryTable = PrimaryTable,
ForeignColumns = new List<string>(ForeignColumns),
PrimaryColumns = new List<string>(PrimaryColumns)
};
}
}
} | apache-2.0 | C# |
84bcca8920d0e472da6a385749f1e8def6aab523 | Add Custom Error Page and Routing | tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS | Portal.CMS.Web/Global.asax.cs | Portal.CMS.Web/Global.asax.cs | using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Portal.CMS.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_Error()
{
Response.Redirect("~/Home/Error");
}
}
} | using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Portal.CMS.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_Error()
{
//Response.Redirect("~/Home/Error");
}
}
} | mit | C# |
6d0cc1f7706d3a720bda383e4071581ea51fc6ea | Remove GC debug setting | UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,ZLima12/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,UselessToucan/osu,2yangk23/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu | osu.Game/Overlays/Settings/Sections/Debug/GCSettings.cs | osu.Game/Overlays/Settings/Sections/Debug/GCSettings.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GCSettings : SettingsSubsection
{
protected override string Header => "Garbage Collector";
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config)
{
Children = new Drawable[]
{
new SettingsButton
{
Text = "Force garbage collection",
Action = GC.Collect
},
};
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Runtime;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Configuration;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings.Sections.Debug
{
public class GCSettings : SettingsSubsection
{
protected override string Header => "Garbage Collector";
private readonly Bindable<LatencyMode> latencyMode = new Bindable<LatencyMode>();
private Bindable<GCLatencyMode> configLatencyMode;
[BackgroundDependencyLoader]
private void load(FrameworkDebugConfigManager config)
{
Children = new Drawable[]
{
new SettingsEnumDropdown<LatencyMode>
{
LabelText = "Active mode",
Bindable = latencyMode
},
new SettingsButton
{
Text = "Force garbage collection",
Action = GC.Collect
},
};
configLatencyMode = config.GetBindable<GCLatencyMode>(DebugSetting.ActiveGCMode);
configLatencyMode.BindValueChanged(mode => latencyMode.Value = (LatencyMode)mode.NewValue, true);
latencyMode.BindValueChanged(mode => configLatencyMode.Value = (GCLatencyMode)mode.NewValue);
}
private enum LatencyMode
{
Batch = GCLatencyMode.Batch,
Interactive = GCLatencyMode.Interactive,
LowLatency = GCLatencyMode.LowLatency,
SustainedLowLatency = GCLatencyMode.SustainedLowLatency
}
}
}
| mit | C# |
595ff1db5965b3f57f0a3cb30d571a0fcbda9f76 | add other sandbox params to form parser | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Parsers/FormBuilderTagParser.cs | src/StockportWebapp/Parsers/FormBuilderTagParser.cs | using System.Text.RegularExpressions;
namespace StockportWebapp.Parsers
{
public class FormBuilderTagParser : ISimpleTagParser
{
private readonly TagReplacer _tagReplacer;
protected Regex TagRegex => new("{{FORM:(.*)}}", RegexOptions.Compiled);
public string GenerateHtml(string tagData)
{
tagData.Replace("{{FORM:", string.Empty);
tagData.Replace("}}", string.Empty);
var ValidUrl = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
var splitTagData = tagData.Split(";");
if (!ValidUrl.IsMatch(splitTagData[0]))
return null;
var iFrameTitle = string.Empty;
if (splitTagData.Length > 1)
iFrameTitle = $"title=\"{splitTagData[1]}\"";
return $"<iframe sandbox='allow-forms allow-scripts allow-top-navigation-by-user-activation allow-same-origin' {iFrameTitle} class='mapframe' allowfullscreen src='{splitTagData[0]}'></iframe>";
}
public FormBuilderTagParser()
{
_tagReplacer = new TagReplacer(GenerateHtml, TagRegex);
}
public string Parse(string body, string title = null)
{
return _tagReplacer.ReplaceAllTags(body);
}
}
} | using System.Text.RegularExpressions;
namespace StockportWebapp.Parsers
{
public class FormBuilderTagParser : ISimpleTagParser
{
private readonly TagReplacer _tagReplacer;
protected Regex TagRegex => new("{{FORM:(.*)}}", RegexOptions.Compiled);
public string GenerateHtml(string tagData)
{
tagData.Replace("{{FORM:", string.Empty);
tagData.Replace("}}", string.Empty);
var ValidUrl = new Regex(@"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$");
var splitTagData = tagData.Split(";");
if (!ValidUrl.IsMatch(splitTagData[0]))
return null;
var iFrameTitle = string.Empty;
if (splitTagData.Length > 1)
iFrameTitle = $"title=\"{splitTagData[1]}\"";
return $"<iframe sandbox='allow-scripts allow-forms' {iFrameTitle} class='mapframe' allowfullscreen src='{splitTagData[0]}'></iframe>";
}
public FormBuilderTagParser()
{
_tagReplacer = new TagReplacer(GenerateHtml, TagRegex);
}
public string Parse(string body, string title = null)
{
return _tagReplacer.ReplaceAllTags(body);
}
}
} | mit | C# |
b5e3cc53888ccb9d71db0b9ee61b2f4b3c78b4a2 | Remove logging of line start positions. | mrward/typescript-addin,chrisber/typescript-addin,chrisber/typescript-addin,mrward/typescript-addin | src/TypeScriptBinding/Hosting/ScriptSnapshotShim.cs | src/TypeScriptBinding/Hosting/ScriptSnapshotShim.cs | // Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using Newtonsoft.Json;
namespace ICSharpCode.TypeScriptBinding.Hosting
{
public class ScriptSnapshotShim : IScriptSnapshotShim
{
ILogger logger;
Script script;
public ScriptSnapshotShim(ILogger logger, Script script)
{
this.logger = logger;
this.script = script;
}
public string getText(int start, int end)
{
return script.Source.Substring(start, end - start);
}
public int getLength()
{
return script.Source.Length;
}
public string getLineStartPositions()
{
Log("ScriptSnapshotShim.getLineStartPositions");
int[] positions = script.GetLineStartPositions();
string json = JsonConvert.SerializeObject(positions);
//Log("ScriptSnapshotShim.getLineStartPositions: {0}", json);
return json;
}
public string getTextChangeRangeSinceVersion(int scriptVersion)
{
Log("ScriptSnapshotShim.getTextChangeRangeSinceVersion: version={0}", scriptVersion);
if (script.Version == scriptVersion)
return null;
TextChangeRange textChangeRange = script.GetTextChangeRangeSinceVersion(scriptVersion);
string json = JsonConvert.SerializeObject(textChangeRange);
Log("ScriptSnapshotShim.getTextChangeRangeSinceVersion: json: {0}", json);
return json;
}
void Log(string format, params object[] args)
{
logger.log(String.Format(format, args));
}
}
}
| // Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using Newtonsoft.Json;
namespace ICSharpCode.TypeScriptBinding.Hosting
{
public class ScriptSnapshotShim : IScriptSnapshotShim
{
ILogger logger;
Script script;
public ScriptSnapshotShim(ILogger logger, Script script)
{
this.logger = logger;
this.script = script;
}
public string getText(int start, int end)
{
return script.Source.Substring(start, end - start);
}
public int getLength()
{
return script.Source.Length;
}
public string getLineStartPositions()
{
Log("ScriptSnapshotShim.getLineStartPositions");
int[] positions = script.GetLineStartPositions();
string json = JsonConvert.SerializeObject(positions);
Log("ScriptSnapshotShim.getLineStartPositions: {0}", json);
return json;
}
public string getTextChangeRangeSinceVersion(int scriptVersion)
{
Log("ScriptSnapshotShim.getTextChangeRangeSinceVersion: version={0}", scriptVersion);
if (script.Version == scriptVersion)
return null;
TextChangeRange textChangeRange = script.GetTextChangeRangeSinceVersion(scriptVersion);
string json = JsonConvert.SerializeObject(textChangeRange);
Log("ScriptSnapshotShim.getTextChangeRangeSinceVersion: json: {0}", json);
return json;
}
void Log(string format, params object[] args)
{
logger.log(String.Format(format, args));
}
}
}
| mit | C# |
289839b47cca49fae0b9a8c65184345c31c556d7 | hide next btn when no more pages | samilokan/csstemplatesforfree.com,victorantos/csstemplatesforfree.com,samilokan/csstemplatesforfree.com,victorantos/csstemplatesforfree.com | Views/App/CssTemplates.cshtml | Views/App/CssTemplates.cshtml |
<h3>css templates (page 1 of 31 )</h3>
<nav>
<ul class="pager">
<li class="previous">
<a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page-1): '')}}" ng-show="page > 1"><span aria-hidden="true">←</span> Previous</a>
</li>
<li class="next">
<a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page+1): '')}}" ng-show="page< pageCount()">Next <span aria-hidden="true">→</span></a>
</li>
</ul>
</nav>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 home-template" ng-repeat="line in templates">
<div class="img-thumbnail">
<a href="#!/csstemplate/preview/{{line.name}}" title="{{line.name}} - bootstrap template">
<img ng-src='{{line.imageFile}}' class="img-responsive" alt="Preview of "edgy" CSS Template">
</a>
<dl class="dl-horizontal">
<dt>Bootstrap template: </dt>
<dd>{{line.name}}</dd>
<dt>Description: </dt>
<dd>{{line.description}}</dd>
<dt>Free: </dt>
<dd><a href="#!/csstemplate/preview/{{line.name}}" id="previewCssTemplate" title="Live preview of "edgy" css template">Css template</a> | <a href="zipHandler.ashx?csstemplateName=edgy" id="downloadCssTemplateLink" title="Download "edgy" css template for free">Download</a></dd>
</dl>
</div>
</div>
</div>
<nav ng-show="pageCount() > 1">
<ul class="pagination">
<li ng-show="page > 1">
<a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page-1): '')}}" aria-label="Previous"><span aria-hidden="true">«</span></a>
</li>
@*<li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>*@
<li ng-repeat="item in pages()"><a href="/#!/csstemplates/page={{item}}">{{item}}</a></li>
<li><a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page+1): '')}}" ng-show="page< pageCount()" aria-label="Next"><span aria-hidden="true">»</span></a></li>
</ul>
</nav>
|
<h3>css templates (page 1 of 31 )</h3>
<nav>
<ul class="pager">
<li class="previous">
<a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page-1): '')}}" ng-show="page > 1"><span aria-hidden="true">←</span> Previous</a>
</li>
<li class="next">
<a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page+1): '')}}">Next <span aria-hidden="true">→</span></a>
</li>
</ul>
</nav>
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 home-template" ng-repeat="line in templates">
<div class="img-thumbnail">
<a href="#!/csstemplate/preview/{{line.name}}" title="{{line.name}} - bootstrap template">
<img ng-src='{{line.imageFile}}' class="img-responsive" alt="Preview of "edgy" CSS Template">
</a>
<dl class="dl-horizontal">
<dt>Bootstrap template: </dt>
<dd>{{line.name}}</dd>
<dt>Description: </dt>
<dd>{{line.description}}</dd>
<dt>Free: </dt>
<dd><a href="#!/csstemplate/preview/{{line.name}}" id="previewCssTemplate" title="Live preview of "edgy" css template">Css template</a> | <a href="zipHandler.ashx?csstemplateName=edgy" id="downloadCssTemplateLink" title="Download "edgy" css template for free">Download</a></dd>
</dl>
</div>
</div>
</div>
<nav ng-show="pageCount() > 1">
<ul class="pagination">
<li ng-show="page > 1">
<a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page-1): '')}}" aria-label="Previous"><span aria-hidden="true">«</span></a>
</li>
@*<li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>*@
<li ng-repeat="item in pages()"><a href="/#!/csstemplates/page={{item}}">{{item}}</a></li>
<li><a href="/#!/csstemplates/{{(page > 0 ? 'page='+ (page+1): '')}}" aria-label="Next"><span aria-hidden="true">»</span></a></li>
</ul>
</nav>
| bsd-2-clause | C# |
b5b078e813888fcb0d476c530f188bccf0e04256 | Add missing NumericEncoding.cs file. | eylvisaker/AgateLib | AgateLib/Serialization/Xle/NumericEncoding.cs | AgateLib/Serialization/Xle/NumericEncoding.cs | // The contents of this file are subject to the Mozilla Public License
// Version 1.1 (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.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
// License for the specific language governing rights and limitations
// under the License.
//
// The Original Code is AgateLib.
//
// The Initial Developer of the Original Code is Erik Ylvisaker.
// Portions created by Erik Ylvisaker are Copyright (C) 2006-2011.
// All Rights Reserved.
//
// Contributor(s): Erik Ylvisaker
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AgateLib.Serialization.Xle
{
public enum NumericEncoding
{
/// <summary>
/// Encode as a Base64 stream.
/// </summary>
Base64,
/// <summary>
/// Encode as comma separated values.
/// </summary>
Csv,
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AgateLib.Serialization.Xle
{
public enum NumericEncoding
{
Base64,
Csv,
}
}
| mit | C# |
5beec19a4bdddb3c1e12bd4bb6ee18d3796e2730 | Fix link name | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Units/List.cshtml | Battery-Commander.Web/Views/Units/List.cshtml | @model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default btn-xs" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id }, new { @class = "btn btn-default btn-xs" })
@Html.ActionLink("Vehicles", "Index", "Vehicles", new { Units = new int[] { unit.Id } }, new { @class = "btn btn-default btn-xs" })
@Html.ActionLink("Edit", "Edit", new { unit.Id }, new { @class = "btn btn-default btn-xs" })
@Html.ActionLink("Reports", "Index", "Reports", new { unit.Id }, new { @class = "btn btn-default btn-xs" })
</td>
</tr>
}
</tbody>
</table>
| @model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default btn-xs" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id }, new { @class = "btn btn-default btn-xs" })
@Html.ActionLink("Vehicles", "Index", "Vehicles", new { Units = new int[] { unit.Id } }, new { @class = "btn btn-default btn-xs" })
@Html.ActionLink("Edit", "Edit", new { unit.Id }, new { @class = "btn btn-default btn-xs" })
@Html.ActionLink("Index", "Reports", new { unit.Id }, new { @class = "btn btn-default btn-xs" })
</td>
</tr>
}
</tbody>
</table>
| mit | C# |
3ed53c9b28c5abdbc5d0de070d0d7bf337ebb7f5 | Update storage assembly | AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,devigned/azure-powershell | src/Storage/Commands.Storage/Properties/AssemblyInfo.cs | src/Storage/Commands.Storage/Properties/AssemblyInfo.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.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("Microsoft Azure Powershell")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// 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("a102cbe8-8a50-43b1-821d-72b42b9831a4")]
// 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("4.1.1")]
[assembly: AssemblyFileVersion("4.1.1")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test")]
#endif
[assembly: CLSCompliant(false)]
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.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("Microsoft Azure Powershell")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// 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("a102cbe8-8a50-43b1-821d-72b42b9831a4")]
// 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("4.1.0")]
[assembly: AssemblyFileVersion("4.1.0")]
#if SIGN
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Commands.Storage.Test")]
#endif
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
1ffd16961e740be86be0ffa66ad9e3ba54f17efd | Fix typo. | congysu/WebApi,scz2011/WebApi,abkmr/WebApi,scz2011/WebApi,yonglehou/WebApi,abkmr/WebApi,lungisam/WebApi,yonglehou/WebApi,chimpinano/WebApi,lewischeng-ms/WebApi,lungisam/WebApi,LianwMS/WebApi,congysu/WebApi,lewischeng-ms/WebApi,LianwMS/WebApi,chimpinano/WebApi | src/System.Web.Http.Owin/HostAuthenticationAttribute.cs | src/System.Web.Http.Owin/HostAuthenticationAttribute.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
namespace System.Web.Http
{
/// <summary>Represents an authentication attribute that authenticates via OWIN middleware.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class HostAuthenticationAttribute : Attribute, IAuthenticationFilter
{
private readonly IAuthenticationFilter _innerFilter;
private readonly string _authenticationType;
/// <summary>Initializes a new instance of the <see cref="HostAuthenticationAttribute"/> class.</summary>
/// <param name="authenticationType">The authentication type of the OWIN middleware to use.</param>
public HostAuthenticationAttribute(string authenticationType)
: this(new HostAuthenticationFilter(authenticationType))
{
_authenticationType = authenticationType;
}
internal HostAuthenticationAttribute(IAuthenticationFilter innerFilter)
{
if (innerFilter == null)
{
throw new ArgumentNullException("innerFilter");
}
_innerFilter = innerFilter;
}
/// <inheritdoc />
public bool AllowMultiple
{
get { return true; }
}
/// <summary>Gets the authentication type of the OWIN middleware to use.</summary>
public string AuthenticationType
{
get { return _authenticationType; }
}
internal IAuthenticationFilter InnerFilter
{
get
{
return _innerFilter;
}
}
/// <inheritdoc />
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
return _innerFilter.AuthenticateAsync(context, cancellationToken);
}
/// <inheritdoc />
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return _innerFilter.ChallengeAsync(context, cancellationToken);
}
}
}
| // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
namespace System.Web.Http
{
/// <summary>Represents an authentication attribute that authenticates via OWIN middleware.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class HostAuthenticationAttribute : Attribute, IAuthenticationFilter
{
private readonly IAuthenticationFilter _innerFilter;
private readonly string _authenticaitonType;
/// <summary>Initializes a new instance of the <see cref="HostAuthenticationAttribute"/> class.</summary>
/// <param name="authenticationType">The authentication type of the OWIN middleware to use.</param>
public HostAuthenticationAttribute(string authenticationType)
: this(new HostAuthenticationFilter(authenticationType))
{
_authenticaitonType = authenticationType;
}
internal HostAuthenticationAttribute(IAuthenticationFilter innerFilter)
{
if (innerFilter == null)
{
throw new ArgumentNullException("innerFilter");
}
_innerFilter = innerFilter;
}
/// <inheritdoc />
public bool AllowMultiple
{
get { return true; }
}
/// <summary>Gets the authentication type of the OWIN middleware to use.</summary>
public string AuthenticationType
{
get { return _authenticaitonType; }
}
internal IAuthenticationFilter InnerFilter
{
get
{
return _innerFilter;
}
}
/// <inheritdoc />
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
return _innerFilter.AuthenticateAsync(context, cancellationToken);
}
/// <inheritdoc />
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return _innerFilter.ChallengeAsync(context, cancellationToken);
}
}
}
| mit | C# |
889b48ad2e575b24b64e8ad876a81ffc7267289f | Remove whitespace to test how well Subversion works via GitHub. | smartfile/client-csharp | AssemblyInfo.cs | AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("SmartFileAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("SmartFileAPI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.*")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| bsd-3-clause | C# |
cf3ba5fefbd71048b6200b9eb6201463ed7cc69a | fix null test for Player | MediaComplete/MediaComplete,MediaComplete/MediaComplete | MSOE.MediaComplete.Test/PlayerTest.cs | MSOE.MediaComplete.Test/PlayerTest.cs | using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MSOE.MediaComplete.Lib;
using NAudio.Wave;
namespace MSOE.MediaComplete.Test
{
[TestClass]
public class PlayerTest
{
private readonly Player _player = Player.Instance;
[TestInitialize]
public void Before()
{
_player.Stop();
}
[TestMethod]
public void Play_NullFileInfo_ReturnWithoutPlaying()
{
_player.Play(null);
Assert.AreEqual(PlaybackState.Stopped, _player.PlaybackState);
}
[TestMethod]
public void Play_Mp3File_ReturnAndContinuePlaying()
{
var player = Player.Instance;
player.Play(new FileInfo("someMp3.mp3"));//TODO: put an actual file here
Assert.AreEqual(PlaybackState.Playing, _player.PlaybackState);
}
[TestMethod]
public void Play_WmaFile_ReturnAndContinuePlaying()
{
var player = Player.Instance;
player.Play(new FileInfo("someWma.wma"));//TODO: put an actual file here
Assert.AreEqual(PlaybackState.Playing, _player.PlaybackState);
}
[TestMethod]
public void Play_WavFile_ReturnAndContinuePlaying()
{
var player = Player.Instance;
player.Play(new FileInfo("someWav.wav"));//TODO: put an actual file here
Assert.AreEqual(PlaybackState.Playing, _player.PlaybackState);
}
}
}
| using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MSOE.MediaComplete.Lib;
using NAudio.Wave;
namespace MSOE.MediaComplete.Test
{
[TestClass]
public class PlayerTest
{
private readonly Player _player = Player.Instance;
[TestInitialize]
public void Before()
{
_player.Stop();
}
[TestMethod]
public void Play_NullFileInfo_ReturnWithoutPlaying()
{
_player.Play(new FileInfo(null));
Assert.AreEqual(PlaybackState.Stopped, _player.PlaybackState);
}
[TestMethod]
public void Play_Mp3File_ReturnAndContinuePlaying()
{
var player = Player.Instance;
player.Play(new FileInfo("someMp3.mp3"));//TODO: put an actual file here
Assert.AreEqual(PlaybackState.Playing, _player.PlaybackState);
}
[TestMethod]
public void Play_WmaFile_ReturnAndContinuePlaying()
{
var player = Player.Instance;
player.Play(new FileInfo("someWma.wma"));//TODO: put an actual file here
Assert.AreEqual(PlaybackState.Playing, _player.PlaybackState);
}
[TestMethod]
public void Play_WavFile_ReturnAndContinuePlaying()
{
var player = Player.Instance;
player.Play(new FileInfo("someWav.wav"));//TODO: put an actual file here
Assert.AreEqual(PlaybackState.Playing, _player.PlaybackState);
}
}
}
| mit | C# |
b18af75db847872936567e25007e96f0691e3093 | Revert areas | MSPSpain/Website,pablovargan/Website,diegomrtnzg/Website,CodingFree/Website,CodingFree/Website,pablovargan/Website,MSPSpain/Website,MSPSpain/Website,pablovargan/Website,MSPSpain/Website,arcadiogarcia/Website,diegomrtnzg/Website,diegomrtnzg/Website,arcadiogarcia/Website,arcadiogarcia/Website,arcadiogarcia/Website,CodingFree/Website,diegomrtnzg/Website,CodingFree/Website,pablovargan/Website | MSPSpain.Web/App_Start/RouteConfig.cs | MSPSpain.Web/App_Start/RouteConfig.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MSPSpain.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MSPSpain.Web
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{area}/{controller}/{action}/{id}",
defaults: new { area = "MSPSpain.Web", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| mit | C# |
946cfb1cca5d6526f9386efab1c8744224b890d3 | Update CreateTransparentImage.cs | asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Articles/CreateTransparentImage.cs | Examples/CSharp/Articles/CreateTransparentImage.cs | using System.IO;
using Aspose.Cells;
using Aspose.Cells.Rendering;
using System.Drawing.Imaging;
namespace Aspose.Cells.Examples.Articles
{
public class CreateTransparentImage
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Create workbook object from source file
Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx");
//Apply different image or print options
var imgOption = new ImageOrPrintOptions();
imgOption.ImageFormat = ImageFormat.Png;
imgOption.HorizontalResolution = 200;
imgOption.VerticalResolution = 200;
imgOption.OnePagePerSheet = true;
//Apply transparency to the output image
imgOption.Transparent = true;
//Create image after apply image or print options
var sr = new SheetRender(wb.Worksheets[0], imgOption);
sr.ToImage(0, dataDir+ "output.out.png");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using Aspose.Cells.Rendering;
using System.Drawing.Imaging;
namespace Aspose.Cells.Examples.Articles
{
public class CreateTransparentImage
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Create workbook object from source file
Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx");
//Apply different image or print options
var imgOption = new ImageOrPrintOptions();
imgOption.ImageFormat = ImageFormat.Png;
imgOption.HorizontalResolution = 200;
imgOption.VerticalResolution = 200;
imgOption.OnePagePerSheet = true;
//Apply transparency to the output image
imgOption.Transparent = true;
//Create image after apply image or print options
var sr = new SheetRender(wb.Worksheets[0], imgOption);
sr.ToImage(0, dataDir+ "output.out.png");
}
}
} | mit | C# |
19cc6a5e1dedca28c3b34cfee93dfe0237de780e | Update Credentials.cs | Developer-Autodesk/view.and.data-simplest-aspnet | FirstViewerWebApp/FirstViewerWebApp/Credentials.cs | FirstViewerWebApp/FirstViewerWebApp/Credentials.cs | namespace FirstViewerWebApp
{
public class Credentials
{
//replace your consumer key and secret key
public static string CONSUMER_KEY = "please request your consumer key at http://developer.autodesk.com";
public static string CONSUMER_SECRET = "not set";
public static string BASE_URL = "https://developer.api.autodesk.com";
}
}
| namespace FirstViewerWebApp
{
public class Credentials
{
//replace your consumer key and secret key
public static string CONSUMER_KEY = "Cxv0RgtyfH2J1sJrnrKcwSBRXRmhagY6";//"please request your consumer key at http://developer.autodesk.com";
public static string CONSUMER_SECRET = "F5c49994f13e843e";//"not set";
public static string BASE_URL = "https://developer.api.autodesk.com";
}
} | mit | C# |
50247ceea71fc6afa4ac86ef14f2f4c9a8467266 | Fix build | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Server/Web/Structures/CurrentState.cs | Server/Web/Structures/CurrentState.cs | using Server.Context;
using Server.System;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Server.Web.Structures
{
public class CurrentState
{
public DateTime StartTime { get; set; }
public List<string> CurrentPlayers { get; } = new List<string>();
public List<VesselInfo> CurrentVessels { get; } = new List<VesselInfo>();
public List<Subspace> Subspaces { get; } = new List<Subspace>();
public long BytesUsed { get; set; }
public void Refresh()
{
CurrentPlayers.Clear();
CurrentVessels.Clear();
Subspaces.Clear();
StartTime = TimeContext.StartTime;
CurrentPlayers.AddRange(ServerContext.Clients.Values.Select(v => v.PlayerName));
CurrentVessels.AddRange(VesselStoreSystem.CurrentVessels.Values.Select(v => new VesselInfo(v)));
Subspaces.AddRange(WarpContext.Subspaces.Values);
BytesUsed = Environment.WorkingSet;
}
}
}
| using Server.Context;
using Server.System;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Server.Web.Structures
{
public class CurrentState
{
public DateTime StartTime { get; set; }
public List<string> CurrentPlayers { get; } = new List<string>();
public List<VesselInfo> CurrentVessels { get; } = new List<VesselInfo>();
public List<Subspace> Subspaces { get; } = new List<Subspace>();
public int MemBytesUsed { get; }
public void Refresh()
{
CurrentPlayers.Clear();
CurrentVessels.Clear();
Subspaces.Clear();
StartTime = TimeContext.StartTime;
CurrentPlayers.AddRange(ServerContext.Clients.Values.Select(v => v.PlayerName));
CurrentVessels.AddRange(VesselStoreSystem.CurrentVessels.Values.Select(v => new VesselInfo(v)));
Subspaces.AddRange(WarpContext.Subspaces.Values);
BytesUsed = Environment.WorkingSet;
}
}
}
| mit | C# |
e161fb062f954deed5d413e3863aa924c70f48f4 | Add Diana Prince (Wonder Woman) | jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | ZirMed.TrainingSandbox/Views/Home/Contact.cshtml | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br />
<strong>Marketing:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Pat:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Dustin:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Nicolas:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Dustin2:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Travis:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Travis2:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Stephanie:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Bruce Wayne:</strong>
<strong>Larry Briggs:</strong>
<strong>Clark Kent:</strong> <a href="mailto:superman.com">superman.com</a>
<strong>Peter Parker:</strong> <a href="mailto:spider-man.com">spider-man.com</a>
<strong>Oliver Queen:</strong>
<strong>Barry Allen:</strong>
<strong>Bob: </strong>
<strong>Bruce Banner:</strong> <a href="#">Hulk.com</a>
<strong>Wade Winston Wilson:</strong> <a href="#">Deadpool.com</a>
<strong>Diana Prince:</strong> <a href="#">WonderWoman.com</a>
</address> | @{
ViewBag.Title = "Contact";
}
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>
<address>
<strong>Support:</strong> <a href="mailto:[email protected]">[email protected]</a><br />
<strong>Marketing:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Pat:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Dustin:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Nicolas:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Dustin2:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Travis:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Travis2:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Stephanie:</strong> <a href="mailto:[email protected]">[email protected]</a>
<strong>Bruce Wayne:</strong>
<strong>Larry Briggs:</strong>
<strong>Clark Kent:</strong> <a href="mailto:superman.com">superman.com</a>
<strong>Peter Parker:</strong> <a href="mailto:spider-man.com">spider-man.com</a>
<strong>Oliver Queen:</strong>
<strong>Barry Allen:</strong>
<strong>Bob: </strong>
<strong>Bruce Banner:</strong> <a href="#">Hulk.com</a>
<strong>Wade Winston Wilson:</strong> <a href="#">Deadpool.com</a>
</address> | mit | C# |
22daafe1a635c817f1eef83c6d49d029113b98aa | Format InvalidationBatch | carbon/Amazon | src/Amazon.CloudFront/Models/InvalidationBatch.cs | src/Amazon.CloudFront/Models/InvalidationBatch.cs | using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace Amazon.CloudFront
{
public sealed class InvalidationBatch
{
public InvalidationBatch(IList<string> paths)
{
if (paths is null)
throw new ArgumentNullException(nameof(paths));
if (paths.Count == 0)
throw new ArgumentException("May not be empty", "paths");
Paths = paths;
}
public IList<string> Paths { get; }
public string CallerReference { get; set; }
public XElement ToXml()
{
var root = new XElement("InvalidationBatch");
foreach (var path in Paths)
{
root.Add(new XElement("Path", path));
}
root.Add(new XElement("CallerReference", CallerReference));
return root;
}
}
}
/*
<InvalidationBatch>
<Path>/image1.jpg</Path>
<Path>/image2.jpg</Path>
<Path>/videos/movie.flv</Path>
<Path>/sound%20track.mp3</Path>
<CallerReference>my-batch</CallerReference>
</InvalidationBatch>
*/ | using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace Amazon.CloudFront
{
public class InvalidationBatch
{
public InvalidationBatch(IList<string> paths)
{
if (paths == null) throw new ArgumentNullException(nameof(paths));
if (paths.Count == 0) throw new ArgumentException("May not be empty", "paths");
Paths = paths;
}
public IList<string> Paths { get; }
public string CallerReference { get; set; }
public XElement ToXml()
{
var root = new XElement("InvalidationBatch");
foreach (var path in Paths)
{
root.Add(new XElement("Path", path));
}
root.Add(new XElement("CallerReference", CallerReference));
return root;
}
}
}
/*
<InvalidationBatch>
<Path>/image1.jpg</Path>
<Path>/image2.jpg</Path>
<Path>/videos/movie.flv</Path>
<Path>/sound%20track.mp3</Path>
<CallerReference>my-batch</CallerReference>
</InvalidationBatch>
*/ | mit | C# |
3873dbf54a1bfba15e6d3231f627f415c2c13f95 | Hide some of the controller links that aren't finished | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | BatteryCommander.Web/Views/Shared/_Layout.cshtml | BatteryCommander.Web/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Battery Commander</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Battery Commander", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Soldiers", "List", "Soldier")</li>
<!--<li>@Html.ActionLink("Groups", "List", "Group")</li>-->
<li>@Html.ActionLink("Qualifications", "List", "Qualification")</li>
<!--<li>@Html.ActionLink("Alerts", "List", "Alert")</li>-->
<!--<li>@Html.ActionLink("Work Items", "List", "WorkItem")</li>-->
<li>@Html.ActionLink("Users", "List", "User")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - MattGWagner</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html> | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Battery Commander</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Battery Commander", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("Soldiers", "List", "Soldier")</li>
<li>@Html.ActionLink("Groups", "List", "Group")</li>
<li>@Html.ActionLink("Qualifications", "List", "Qualification")</li>
<li>@Html.ActionLink("Alerts", "List", "Alert")</li>
<li>@Html.ActionLink("Work Items", "List", "WorkItem")</li>
<li>@Html.ActionLink("Users", "List", "User")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - MattGWagner</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html> | mit | C# |
0dac63856ef86d1e76bb86932b1802967c70acc8 | reorder handlers for cors failed auth attempts | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/App_Start/HandlerConfig.cs | WebAPI.API/App_Start/HandlerConfig.cs | using System.Collections.ObjectModel;
using System.Net.Http;
using Ninject;
using WebAPI.API.App_Start;
using WebAPI.API.Handlers.Delegating;
namespace WebAPI.API
{
public static class HandlerConfig
{
/// <summary>
/// Registers the handlers in the order they appear.
/// </summary>
/// <param name="messageHandlers">The message handlers.</param>
public static void RegisterHandlers(Collection<DelegatingHandler> messageHandlers)
{
messageHandlers.Add(new SuppressStatusCodeHandler());
messageHandlers.Add(new ElapsedTimeMessageHandler());
messageHandlers.Add(new CorsHandler());
messageHandlers.Add(App.Kernel.Get<AuthorizeRequestHandler>());
messageHandlers.Add(new GeometryFormatHandler());
messageHandlers.Add(App.Kernel.Get<EsriJsonHandler>());
messageHandlers.Add(App.Kernel.Get<GeoJsonHandler>());
messageHandlers.Add(App.Kernel.Get<ApiLoggingHandler>());
}
}
} | using System.Collections.ObjectModel;
using System.Net.Http;
using Ninject;
using WebAPI.API.App_Start;
using WebAPI.API.Handlers.Delegating;
namespace WebAPI.API
{
public static class HandlerConfig
{
/// <summary>
/// Registers the handlers in the order they appear.
/// </summary>
/// <param name="messageHandlers">The message handlers.</param>
public static void RegisterHandlers(Collection<DelegatingHandler> messageHandlers)
{
messageHandlers.Add(new SuppressStatusCodeHandler());
messageHandlers.Add(new ElapsedTimeMessageHandler());
messageHandlers.Add(App.Kernel.Get<AuthorizeRequestHandler>());
messageHandlers.Add(new GeometryFormatHandler());
messageHandlers.Add(App.Kernel.Get<EsriJsonHandler>());
messageHandlers.Add(App.Kernel.Get<GeoJsonHandler>());
messageHandlers.Add(new CorsHandler());
messageHandlers.Add(App.Kernel.Get<ApiLoggingHandler>());
}
}
} | mit | C# |
53f01e7562fa0770b4a2d67ded326dc6dd9e743b | Add ContentType.Clean(doc) to remove empty Content Types | Squirrel/Squirrel.Windows,JonMartinTx/AS400Report,GeertvanHorrik/Squirrel.Windows,bowencode/Squirrel.Windows,Squirrel/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,jochenvangasse/Squirrel.Windows,JonMartinTx/AS400Report,NeilSorensen/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,BloomBooks/Squirrel.Windows,NeilSorensen/Squirrel.Windows,NeilSorensen/Squirrel.Windows,jbeshir/Squirrel.Windows,kenbailey/Squirrel.Windows,BloomBooks/Squirrel.Windows,bowencode/Squirrel.Windows,kenbailey/Squirrel.Windows,sickboy/Squirrel.Windows,JonMartinTx/AS400Report,jbeshir/Squirrel.Windows,sickboy/Squirrel.Windows,punker76/Squirrel.Windows,sickboy/Squirrel.Windows,Squirrel/Squirrel.Windows,jochenvangasse/Squirrel.Windows,jochenvangasse/Squirrel.Windows,punker76/Squirrel.Windows,punker76/Squirrel.Windows,BloomBooks/Squirrel.Windows,bowencode/Squirrel.Windows,jbeshir/Squirrel.Windows,kenbailey/Squirrel.Windows | src/Squirrel/ContentType.cs | src/Squirrel/ContentType.cs | using System;
using System.Linq;
using System.Xml;
namespace Squirrel
{
internal static class ContentType
{
public static void Clean(XmlDocument doc)
{
var typesElement = doc.FirstChild.NextSibling;
if (typesElement.Name.ToLowerInvariant() != "types") {
throw new Exception("Invalid ContentTypes file, expected root node should be 'Types'");
}
var children = typesElement.ChildNodes.OfType<XmlElement>();
for (var child in children)
{
if (child.GetAttribute("Extension") == "")
{
typesElement.RemoveChild(child);
}
}
}
public static void Merge(XmlDocument doc)
{
var elements = new [] {
Tuple.Create("Default", "diff", "application/octet" ),
Tuple.Create("Default", "bsdiff", "application/octet" ),
Tuple.Create("Default", "exe", "application/octet" ),
Tuple.Create("Default", "dll", "application/octet" ),
Tuple.Create("Default", "shasum", "text/plain" ),
};
var typesElement = doc.FirstChild.NextSibling;
if (typesElement.Name.ToLowerInvariant() != "types") {
throw new Exception("Invalid ContentTypes file, expected root node should be 'Types'");
}
var existingTypes = typesElement.ChildNodes.OfType<XmlElement>()
.Select(k => Tuple.Create(k.Name,
k.GetAttribute("Extension").ToLowerInvariant(),
k.GetAttribute("ContentType").ToLowerInvariant()));
var toAdd = elements
.Where(x => existingTypes.All(t => t.Item2 != x.Item2.ToLowerInvariant()))
.Select(element => {
var ret = doc.CreateElement(element.Item1, typesElement.NamespaceURI);
var ext = doc.CreateAttribute("Extension"); ext.Value = element.Item2;
var ct = doc.CreateAttribute("ContentType"); ct.Value = element.Item3;
ret.Attributes.Append(ext);
ret.Attributes.Append(ct);
return ret;
});
foreach (var v in toAdd) typesElement.AppendChild(v);
}
}
}
| using System;
using System.Linq;
using System.Xml;
namespace Squirrel
{
internal static class ContentType
{
public static void Merge(XmlDocument doc)
{
var elements = new [] {
Tuple.Create("Default", "diff", "application/octet" ),
Tuple.Create("Default", "bsdiff", "application/octet" ),
Tuple.Create("Default", "exe", "application/octet" ),
Tuple.Create("Default", "dll", "application/octet" ),
Tuple.Create("Default", "shasum", "text/plain" ),
};
var typesElement = doc.FirstChild.NextSibling;
if (typesElement.Name.ToLowerInvariant() != "types") {
throw new Exception("Invalid ContentTypes file, expected root node should be 'Types'");
}
var existingTypes = typesElement.ChildNodes.OfType<XmlElement>()
.Select(k => Tuple.Create(k.Name,
k.GetAttribute("Extension").ToLowerInvariant(),
k.GetAttribute("ContentType").ToLowerInvariant()));
var toAdd = elements
.Where(x => existingTypes.All(t => t.Item2 != x.Item2.ToLowerInvariant()))
.Select(element => {
var ret = doc.CreateElement(element.Item1, typesElement.NamespaceURI);
var ext = doc.CreateAttribute("Extension"); ext.Value = element.Item2;
var ct = doc.CreateAttribute("ContentType"); ct.Value = element.Item3;
ret.Attributes.Append(ext);
ret.Attributes.Append(ct);
return ret;
});
foreach (var v in toAdd) typesElement.AppendChild(v);
}
}
}
| mit | C# |
f4bc0973232b9a159390a85300788a78637dbe00 | Remove unused field (win) | codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop,codeman38/toggldesktop | src/ui/windows/TogglDesktop/TogglDesktop/AboutWindowController.cs | src/ui/windows/TogglDesktop/TogglDesktop/AboutWindowController.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace TogglDesktop
{
public partial class AboutWindowController : TogglForm
{
s public AboutWindowController()
{
InitializeComponent();
labelVersion.Text = TogglDesktop.Program.Version();
bool updateCheckDisabled = Toggl.IsUpdateCheckDisabled();
comboBoxChannel.Visible = !updateCheckDisabled;
labelReleaseChannel.Visible = !updateCheckDisabled;
}
private void AboutWindowController_FormClosing(object sender, FormClosingEventArgs e)
{
Hide();
e.Cancel = true;
}
private void comboBoxChannel_SelectedIndexChanged(object sender, EventArgs e)
{
Toggl.SetUpdateChannel(comboBoxChannel.Text);
}
private void linkLabelGithub_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(linkLabelGithub.Text);
}
public void ShowUpdates()
{
Show();
if (comboBoxChannel.Visible)
{
string channel = Toggl.UpdateChannel();
comboBoxChannel.SelectedIndex = comboBoxChannel.Items.IndexOf(channel);
}
}
internal void initAndCheck()
{
string channel = Toggl.UpdateChannel();
comboBoxChannel.SelectedIndex = comboBoxChannel.Items.IndexOf(channel);
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
namespace TogglDesktop
{
public partial class AboutWindowController : TogglForm
{
private bool loaded = false;
public AboutWindowController()
{
InitializeComponent();
labelVersion.Text = TogglDesktop.Program.Version();
bool updateCheckDisabled = Toggl.IsUpdateCheckDisabled();
comboBoxChannel.Visible = !updateCheckDisabled;
labelReleaseChannel.Visible = !updateCheckDisabled;
}
private void AboutWindowController_FormClosing(object sender, FormClosingEventArgs e)
{
Hide();
e.Cancel = true;
}
private void comboBoxChannel_SelectedIndexChanged(object sender, EventArgs e)
{
Toggl.SetUpdateChannel(comboBoxChannel.Text);
loaded = true;
}
private void linkLabelGithub_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(linkLabelGithub.Text);
}
public void ShowUpdates()
{
Show();
if (comboBoxChannel.Visible)
{
string channel = Toggl.UpdateChannel();
comboBoxChannel.SelectedIndex = comboBoxChannel.Items.IndexOf(channel);
}
}
internal void initAndCheck()
{
string channel = Toggl.UpdateChannel();
comboBoxChannel.SelectedIndex = comboBoxChannel.Items.IndexOf(channel);
}
}
}
| bsd-3-clause | C# |
821556e392c8bf735e4aceab4a6c40af70e96f32 | Fix Sample | yamachu/Mastodot | example/Program.cs | example/Program.cs | using System;
using Mastodot;
using Mastodot.Enums;
using Mastodot.Utils;
using Mastodot.Entities;
using System.Reactive.Linq;
namespace example
{
class Program
{
static void Main(string[] args)
{
var main = new Program();
/* Create and get AccessToken to connect Mastodon Instance */
main.CreateAppAndAuth();
/* Toot! */
//main.LetsToot("Hello World! From Mastodot");
/* Subscribe timeline */
//main.SubscribePublicstream();
}
private void LetsToot(string content)
{
var client = new MastodonClient("Mastodon Instance Url that your app registered"
, "AccessToken");
client.PostNewStatus(status: content).Wait();
}
private void CreateAppAndAuth(string host = "mastodon.cloud", string appName = "MastodotSampleClient")
{
var app = ApplicationManager.RegistApp(host, appName, Scope.Read | Scope.Write | Scope.Follow).Result;
var url = ApplicationManager.GetOAuthUrl(app);
Console.WriteLine(url);
var code = Console.ReadLine();
var tokens = ApplicationManager.GetAccessTokenByCode(app, code).Result;
Console.WriteLine(tokens.AccessToken);
Console.ReadKey();
Console.WriteLine("Finish");
Console.ReadKey();
}
private void SubscribePublicstream()
{
var client = new MastodonClient("Mastodon Instance Url that your app registered"
, "AccessToken");
var statusDs = client.GetObservablePublicTimeline()
.OfType<Status>()
.Subscribe(x => Console.WriteLine($"{x.Account.FullUserName} Tooted: {x.Content}"));
Console.WriteLine("Press Key then Finish");
Console.ReadKey();
statusDs.Dispose();
Console.WriteLine("Finish");
}
}
}
| using System;
using Mastodot;
using Mastodot.Enums;
using Mastodot.Utils;
using Mastodot.Entities;
using System.Reactive.Linq;
namespace example
{
class Program
{
static void Main(string[] args)
{
var main = new Program();
/* Create and get AccessToken to connect Mastodon Instance */
main.CreateAppAndAuth();
/* Toot! */
//main.LetsToot("Hello World! From Mastodot");
/* Subscribe timeline */
//main.SubscribePublicstream();
}
private void LetsToot(string content)
{
var client = new MastodonClient("Mastodon Instance Url that your app registered"
, "AccessToken");
client.PostNewStatus(status: content).Wait();
}
private void CreateAppAndAuth(string host = "mastodon.cloud", string appName = "MastodotSampleClient")
{
var app = ApplicaionManager.RegistApp(host, appName, Scope.Read | Scope.Write | Scope.Follow).Result;
var url = ApplicaionManager.GetOAuthUrl(app);
Console.WriteLine(url);
var code = Console.ReadLine();
var tokens = ApplicaionManager.GetAccessTokenByCode(app, code).Result;
Console.WriteLine(tokens.AccessToken);
Console.ReadKey();
Console.WriteLine("Finish");
Console.ReadKey();
}
private void SubscribePublicstream()
{
var client = new MastodonClient("Mastodon Instance Url that your app registered"
, "AccessToken");
var statusDs = client.GetObservablePublicTimeline()
.OfType<Status>()
.Subscribe(x => Console.WriteLine($"{x.Account.FullUserName} Tooted: {x.Content}"));
Console.WriteLine("Press Key then Finish");
Console.ReadKey();
statusDs.Dispose();
Console.WriteLine("Finish");
}
}
}
| mit | C# |
9ad09395189497a660e243f90f01751f1c1d2d80 | Update EmotibleViewModel to Update fields in proper order. | runewake2/LetsMakeAnApp | Emotible/Emotible/ViewModels/EmotibleViewModel.cs | Emotible/Emotible/ViewModels/EmotibleViewModel.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Emotible.Layout;
using Emotible.Model;
namespace Emotible.ViewModels
{
public class EmotibleViewModel : BaseViewModel
{
private LayoutController controller = new LayoutController();
private ObservableCollection<IEmoteViewModel> _emotes = new ObservableCollection<IEmoteViewModel>();
public ObservableCollection<IEmoteViewModel> Emotes
{
get { return _emotes; }
set
{
if (_emotes != value)
{
_emotes = value;
NotifyPropertyChanged();
}
}
}
private int _columns;
public int Columns
{
get { return _columns; }
set {
if (_columns != value)
{
_columns = value;
NotifyPropertyChanged();
UpdateEmotesAsync();
}
}
}
private double _width;
public double Width
{
get { return _width; }
set
{
if (_width != value)
{
_width = value;
var gridSize = (double)App.Current.Resources["GridSize"];
Columns = (int)Math.Floor(_width / gridSize);
NotifyPropertyChanged();
}
}
}
public void UpdateEmotesAsync()
{
var updatedLayout = controller.BuildCollection();
Emotes = updatedLayout;
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Core;
using Emotible.Layout;
using Emotible.Model;
namespace Emotible.ViewModels
{
public class EmotibleViewModel : BaseViewModel
{
private LayoutController controller = new LayoutController();
private ObservableCollection<IEmoteViewModel> _emotes = new ObservableCollection<IEmoteViewModel>();
public ObservableCollection<IEmoteViewModel> Emotes
{
get { return _emotes; }
set
{
if (_emotes != value)
{
_emotes = value;
NotifyPropertyChanged();
}
}
}
private int _columns;
public int Columns
{
get { return _columns; }
set {
if (_columns != value)
{
_columns = value;
UpdateEmotesAsync();
NotifyPropertyChanged();
}
}
}
private double _width;
public double Width
{
get { return _width; }
set
{
if (_width != value)
{
_width = value;
var gridSize = (double)App.Current.Resources["GridSize"];
Columns = (int)Math.Floor(_width / gridSize);
NotifyPropertyChanged();
}
}
}
public void UpdateEmotesAsync()
{
var updatedLayout = controller.BuildCollection();
Emotes = updatedLayout;
}
}
} | mit | C# |
bf12ec8bacf4d0b75c19a1ae096c0e17054cf334 | improve the EnumerateTestCommands method. | jwChung/Experimentalism,jwChung/Experimentalism | src/Experiment/NaiveFirstClassTheoremAttribute.cs | src/Experiment/NaiveFirstClassTheoremAttribute.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
using Xunit.Sdk;
namespace Jwc.Experiment
{
/// <summary>
/// A test attribute used to adorn methods that creates first-class
/// executable test cases.
/// </summary>
public class NaiveFirstClassTheoremAttribute : FactAttribute
{
/// <summary>
/// Enumerates the test commands represented by this test method.
/// Derived classes should override this method to return instances of
/// <see cref="ITestCommand" />, one per execution of a test method.
/// </summary>
/// <param name="method">The test method</param>
/// <returns>
/// The test commands which will execute the test runs for the given method
/// </returns>
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method)
{
return CreateTestCases(method).Select(tc => tc.ConvertToTestCommand(method));
}
private static IEnumerable<ITestCase> CreateTestCases(IMethodInfo method)
{
var methodInfo = method.MethodInfo;
return (IEnumerable<ITestCase>)methodInfo.Invoke(CreateDeclaringObject(methodInfo), null);
}
private static object CreateDeclaringObject(MethodInfo methodInfo)
{
return IsStatic(methodInfo.DeclaringType)
? null
: Activator.CreateInstance(methodInfo.DeclaringType);
}
private static bool IsStatic(Type type)
{
return type.IsAbstract && type.IsSealed;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Sdk;
namespace Jwc.Experiment
{
/// <summary>
/// A test attribute used to adorn methods that creates first-class
/// executable test cases.
/// </summary>
public class NaiveFirstClassTheoremAttribute : FactAttribute
{
/// <summary>
/// Enumerates the test commands represented by this test method.
/// Derived classes should override this method to return instances of
/// <see cref="ITestCommand" />, one per execution of a test method.
/// </summary>
/// <param name="method">The test method</param>
/// <returns>
/// The test commands which will execute the test runs for the given method
/// </returns>
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method)
{
var methodInfo = method.MethodInfo;
var declaringObject = IsStatic(methodInfo.DeclaringType)
? null
: Activator.CreateInstance(methodInfo.DeclaringType);
var testCases = (IEnumerable<ITestCase>)methodInfo.Invoke(declaringObject, null);
return testCases.Select(tc => tc.ConvertToTestCommand(method));
}
private static bool IsStatic(Type type)
{
return type.IsAbstract && type.IsSealed;
}
}
} | mit | C# |
f3a83fe13a87c35effe0b64f8adec183ef1f7205 | Fix bad merge | grenade/NuGetGallery_download-count-patch,ScottShingler/NuGetGallery,projectkudu/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,KuduApps/NuGetGallery,KuduApps/NuGetGallery,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,mtian/SiteExtensionGallery,mtian/SiteExtensionGallery,mtian/SiteExtensionGallery,ScottShingler/NuGetGallery,skbkontur/NuGetGallery,projectkudu/SiteExtensionGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,JetBrains/ReSharperGallery,grenade/NuGetGallery_download-count-patch,KuduApps/NuGetGallery,ScottShingler/NuGetGallery | Website/Services/TestableStorageClientException.cs | Website/Services/TestableStorageClientException.cs | using System;
using Microsoft.WindowsAzure.Storage;
namespace NuGetGallery
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification = "This is for unit tests only.")]
public class TestableStorageClientException : Exception
{
public TestableStorageClientException()
{
}
public TestableStorageClientException(StorageException ex)
{
ErrorCode = ex.RequestInformation.ExtendedErrorInformation.ErrorCode;
}
public string ErrorCode { get; set; }
}
} | using System;
using System.Net;
using Microsoft.WindowsAzure.Storage;
namespace NuGetGallery
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2237:MarkISerializableTypesWithSerializable", Justification="This is for unit tests only.")]
public class TestableStorageClientException : Exception
{
public TestableStorageClientException()
{
}
public TestableStorageClientException(StorageException ex)
{
if (ex.RequestInformation != null)
{
HttpStatusCode = (HttpStatusCode)ex.RequestInformation.HttpStatusCode;
}
}
public HttpStatusCode? HttpStatusCode { get; set; }
}
} | apache-2.0 | C# |
9423164f8b44e13390b2ce78d8e69b1501bc2bb4 | Fix syntax error. | fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game | game/client/ui/shell/shell.cs | game/client/ui/shell/shell.cs | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - shell.cs
// Code for Revenge Of The Cats' Shell
//------------------------------------------------------------------------------
if(isObject(DefaultCursor))
{
DefaultCursor.delete();
new GuiCursor(DefaultCursor)
{
hotSpot = "6 6";
bitmapName = "./pixmaps/mg_arrow6";
};
}
function addWindow(%control, %inactive)
{
%oldparent = %control.getParent();
%parent = Shell;
if(Canvas.getContent() != Shell.getId())
%parent = ShellDlg;
if(%control.getParent().getId() != %parent.getId())
{
%parent.add(%control);
%parent.pushToBack(%control);
if(%control.getParent() != %oldParent)
%control.onAddedAsWindow();
}
if(!%inactive)
windowSelected(%control);
Canvas.repaint();
}
function removeWindow(%control)
{
%control.getParent().remove(%control);
%control.onRemovedAsWindow();
Canvas.repaint();
}
function Shell::onWake(%this)
{
ShellVersionString.setText("client version:" SPC $GameVersionString);
windowSelected(RootMenuWindow);
}
function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount)
{
//
// display the root menu...
//
if( Shell.isMember(RootMenu) )
removeWindow(RootMenu);
else
{
RootMenu.position = %coord;
//addWindow(RootMenu);
//Canvas.repaint();
}
}
function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount)
{
//
}
function windowChangeProfile(%ctrl, %profile)
{
%ctrl.profile = %profile;
%parent = %ctrl.getParent();
%parent.remove(%ctrl);
%parent.add(%ctrl);
}
function windowSelected(%ctrl)
{
if(%ctrl.getId() == $SelectedWindow.getId())
return;
if($SelectedWindow !$= "")
windowChangeProfile($SelectedWindow, GuiInactiveWindowProfile);
windowChangeProfile(%ctrl, GuiWindowProfile);
%ctrl.makeFirstResponder(true);
$SelectedWindow = %ctrl;
}
function GuiCanvas::onCanvasMouseDown(%this, %ctrl)
{
%win = "";
while(isObject(%ctrl))
{
if(%ctrl.getClassName() $= "GuiWindowCtrl")
{
%win = %ctrl;
break;
}
%ctrl = %ctrl.getParent();
}
if(isObject(%win))
windowSelected(%win);
}
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Revenge Of The Cats - shell.cs
// Code for Revenge Of The Cats' Shell
//------------------------------------------------------------------------------
if(isObject(DefaultCursor))
{
DefaultCursor.delete();
new GuiCursor(DefaultCursor)
{
hotSpot = "6 6";
bitmapName = "./pixmaps/mg_arrow6";
};
}
function addWindow(%control, %inactive)
{
%oldparent = %control.getParent();
%parent = Shell;
if(Canvas.getContent() != Shell.getId())
%parent = ShellDlg;
if(%control.getParent().getId() != %parent.getId())
{
%parent.add(%control);
%parent.pushToBack(%control);
if(%control.getParent() != %oldParent)
%control.onAddedAsWindow();
}
if(!%inactive)
windowSelected(%control);
Canvas.repaint();
}
function removeWindow(%control)
{
%control.getParent().remove(%control);
%control.onRemovedAsWindow();
Canvas.repaint();
}
function Shell::onWake(%this)
{
ShellVersionString.setText("client version: $GameVersionString);
windowSelected(RootMenuWindow);
}
function ShellRoot::onMouseDown(%this,%modifier,%coord,%clickCount)
{
//
// display the root menu...
//
if( Shell.isMember(RootMenu) )
removeWindow(RootMenu);
else
{
RootMenu.position = %coord;
//addWindow(RootMenu);
//Canvas.repaint();
}
}
function ShellRoot::onMouseEnter(%this,%modifier,%coord,%clickCount)
{
//
}
function windowChangeProfile(%ctrl, %profile)
{
%ctrl.profile = %profile;
%parent = %ctrl.getParent();
%parent.remove(%ctrl);
%parent.add(%ctrl);
}
function windowSelected(%ctrl)
{
if(%ctrl.getId() == $SelectedWindow.getId())
return;
if($SelectedWindow !$= "")
windowChangeProfile($SelectedWindow, GuiInactiveWindowProfile);
windowChangeProfile(%ctrl, GuiWindowProfile);
%ctrl.makeFirstResponder(true);
$SelectedWindow = %ctrl;
}
function GuiCanvas::onCanvasMouseDown(%this, %ctrl)
{
%win = "";
while(isObject(%ctrl))
{
if(%ctrl.getClassName() $= "GuiWindowCtrl")
{
%win = %ctrl;
break;
}
%ctrl = %ctrl.getParent();
}
if(isObject(%win))
windowSelected(%win);
}
| lgpl-2.1 | C# |
b9bc86b43a0d31f7f4d437b1de45b1e85c868c6c | Add disposal tracking for TempRoot | DustinCampbell/roslyn,gafter/roslyn,genlu/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,xasx/roslyn,tmeschter/roslyn,aelij/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,OmarTawfik/roslyn,diryboy/roslyn,physhi/roslyn,orthoxerox/roslyn,aelij/roslyn,Hosch250/roslyn,bkoelman/roslyn,jmarolf/roslyn,tmat/roslyn,cston/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,Hosch250/roslyn,agocke/roslyn,physhi/roslyn,DustinCampbell/roslyn,KevinRansom/roslyn,jcouv/roslyn,eriawan/roslyn,mgoertz-msft/roslyn,orthoxerox/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,dpoeschl/roslyn,eriawan/roslyn,tannergooding/roslyn,bkoelman/roslyn,tmeschter/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,jmarolf/roslyn,lorcanmooney/roslyn,wvdd007/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,brettfo/roslyn,paulvanbrenk/roslyn,bartdesmet/roslyn,swaroop-sridhar/roslyn,khyperia/roslyn,jamesqo/roslyn,dotnet/roslyn,abock/roslyn,Giftednewt/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,dotnet/roslyn,reaction1989/roslyn,weltkante/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,weltkante/roslyn,weltkante/roslyn,mavasani/roslyn,khyperia/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,cston/roslyn,dpoeschl/roslyn,genlu/roslyn,xasx/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,Giftednewt/roslyn,Hosch250/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,DustinCampbell/roslyn,jamesqo/roslyn,aelij/roslyn,AmadeusW/roslyn,jcouv/roslyn,jcouv/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,lorcanmooney/roslyn,abock/roslyn,agocke/roslyn,ErikSchierboom/roslyn,Giftednewt/roslyn,eriawan/roslyn,dpoeschl/roslyn,mattscheffer/roslyn,AlekseyTs/roslyn,mavasani/roslyn,abock/roslyn,heejaechang/roslyn,OmarTawfik/roslyn,swaroop-sridhar/roslyn,heejaechang/roslyn,sharwell/roslyn,lorcanmooney/roslyn,stephentoub/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,gafter/roslyn,tannergooding/roslyn,xasx/roslyn,wvdd007/roslyn,diryboy/roslyn,jamesqo/roslyn,CyrusNajmabadi/roslyn,khyperia/roslyn,brettfo/roslyn,cston/roslyn,AmadeusW/roslyn,physhi/roslyn,panopticoncentral/roslyn,nguerrera/roslyn,VSadov/roslyn,tmat/roslyn,bkoelman/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,agocke/roslyn,panopticoncentral/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,paulvanbrenk/roslyn,mattscheffer/roslyn,orthoxerox/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,swaroop-sridhar/roslyn,genlu/roslyn,VSadov/roslyn,wvdd007/roslyn,sharwell/roslyn,KevinRansom/roslyn,mattscheffer/roslyn,davkean/roslyn | src/Test/Utilities/Portable/TempFiles/TempRoot.cs | src/Test/Utilities/Portable/TempFiles/TempRoot.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class TempRoot : IDisposable
{
private readonly ConcurrentBag<IDisposable> _temps = new ConcurrentBag<IDisposable>();
public static readonly string Root;
private bool _disposed;
static TempRoot()
{
Root = Path.Combine(Path.GetTempPath(), "RoslynTests");
Directory.CreateDirectory(Root);
}
public void Dispose()
{
_disposed = true;
while (_temps.TryTake(out var temp))
{
try
{
if (temp != null)
{
temp.Dispose();
}
}
catch
{
// ignore
}
}
}
private void CheckDisposed()
{
if (this._disposed)
{
throw new ObjectDisposedException(nameof(TempRoot));
}
}
public TempDirectory CreateDirectory()
{
CheckDisposed();
var dir = new DisposableDirectory(this);
_temps.Add(dir);
return dir;
}
public TempFile CreateFile(string prefix = null, string extension = null, string directory = null, [CallerFilePath]string callerSourcePath = null, [CallerLineNumber]int callerLineNumber = 0)
{
CheckDisposed();
return AddFile(new DisposableFile(prefix, extension, directory, callerSourcePath, callerLineNumber));
}
public DisposableFile AddFile(DisposableFile file)
{
CheckDisposed();
_temps.Add(file);
return file;
}
internal static void CreateStream(string fullPath)
{
using (var file = new FileStream(fullPath, FileMode.CreateNew)) { }
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Runtime.CompilerServices;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public sealed class TempRoot : IDisposable
{
private readonly ConcurrentBag<IDisposable> _temps = new ConcurrentBag<IDisposable>();
public static readonly string Root;
static TempRoot()
{
Root = Path.Combine(Path.GetTempPath(), "RoslynTests");
Directory.CreateDirectory(Root);
}
public void Dispose()
{
while (_temps.TryTake(out var temp))
{
try
{
if (temp != null)
{
temp.Dispose();
}
}
catch
{
// ignore
}
}
}
public TempDirectory CreateDirectory()
{
var dir = new DisposableDirectory(this);
_temps.Add(dir);
return dir;
}
public TempFile CreateFile(string prefix = null, string extension = null, string directory = null, [CallerFilePath]string callerSourcePath = null, [CallerLineNumber]int callerLineNumber = 0)
{
return AddFile(new DisposableFile(prefix, extension, directory, callerSourcePath, callerLineNumber));
}
public DisposableFile AddFile(DisposableFile file)
{
_temps.Add(file);
return file;
}
internal static void CreateStream(string fullPath)
{
using (var file = new FileStream(fullPath, FileMode.CreateNew)) { }
}
}
}
| mit | C# |
1bd9273a9568d36f13914a24945690afd3ef144d | Throw better exception for invalid interfaces | krytarowski/corert,sandreenko/corert,yizhang82/corert,krytarowski/corert,gregkalapos/corert,krytarowski/corert,botaberg/corert,tijoytom/corert,tijoytom/corert,shrah/corert,sandreenko/corert,shrah/corert,shrah/corert,botaberg/corert,yizhang82/corert,sandreenko/corert,botaberg/corert,gregkalapos/corert,tijoytom/corert,botaberg/corert,yizhang82/corert,tijoytom/corert,shrah/corert,yizhang82/corert,gregkalapos/corert,sandreenko/corert,gregkalapos/corert,krytarowski/corert | src/Common/src/TypeSystem/Ecma/EcmaType.Interfaces.cs | src/Common/src/TypeSystem/Ecma/EcmaType.Interfaces.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 System.Reflection.Metadata;
using System.Threading;
using Debug = System.Diagnostics.Debug;
using Internal.TypeSystem;
namespace Internal.TypeSystem.Ecma
{
// This file has implementations of the .Interfaces.cs logic from its base type.
public sealed partial class EcmaType : MetadataType
{
private DefType[] _implementedInterfaces;
public override DefType[] ExplicitlyImplementedInterfaces
{
get
{
if (_implementedInterfaces == null)
return InitializeImplementedInterfaces();
return _implementedInterfaces;
}
}
private DefType[] InitializeImplementedInterfaces()
{
var interfaceHandles = _typeDefinition.GetInterfaceImplementations();
int count = interfaceHandles.Count;
if (count == 0)
return (_implementedInterfaces = Array.Empty<DefType>());
DefType[] implementedInterfaces = new DefType[count];
int i = 0;
foreach (var interfaceHandle in interfaceHandles)
{
var interfaceImplementation = this.MetadataReader.GetInterfaceImplementation(interfaceHandle);
DefType interfaceType = _module.GetType(interfaceImplementation.Interface) as DefType;
if (interfaceType == null)
throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadBadFormat, this);
implementedInterfaces[i++] = interfaceType;
}
return (_implementedInterfaces = implementedInterfaces);
}
}
}
| // 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 System.Reflection.Metadata;
using System.Threading;
using Debug = System.Diagnostics.Debug;
using Internal.TypeSystem;
namespace Internal.TypeSystem.Ecma
{
// This file has implementations of the .Interfaces.cs logic from its base type.
public sealed partial class EcmaType : MetadataType
{
private DefType[] _implementedInterfaces;
public override DefType[] ExplicitlyImplementedInterfaces
{
get
{
if (_implementedInterfaces == null)
return InitializeImplementedInterfaces();
return _implementedInterfaces;
}
}
private DefType[] InitializeImplementedInterfaces()
{
var interfaceHandles = _typeDefinition.GetInterfaceImplementations();
int count = interfaceHandles.Count;
if (count == 0)
return (_implementedInterfaces = Array.Empty<DefType>());
DefType[] implementedInterfaces = new DefType[count];
int i = 0;
foreach (var interfaceHandle in interfaceHandles)
{
var interfaceImplementation = this.MetadataReader.GetInterfaceImplementation(interfaceHandle);
implementedInterfaces[i++] = (DefType)_module.GetType(interfaceImplementation.Interface);
}
return (_implementedInterfaces = implementedInterfaces);
}
}
}
| mit | C# |
d674e441052de1e831d8c8dba350241d024ea95f | Add .net workaround | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit/Utilities/TypeCacheUtility.cs | Assets/MixedRealityToolkit/Utilities/TypeCacheUtility.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utility class to store subclasses of particular base class keys
/// Reloads between play mode/edit mode and after re-compile of scripts
/// </summary>
public static class TypeCacheUtility
{
private static Dictionary<Type, List<Type>> cache = new Dictionary<Type, List<Type>>();
/// <summary>
/// Get all subclass types of base class type T
/// Does not work with .NET scripting backend
/// </summary>
/// <typeparam name="T">base class of type T</typeparam>
/// <returns>list of subclass types for base class T</returns>
public static List<Type> GetSubClasses<T>()
{
return GetSubClasses(typeof(T));
}
/// <summary>
/// Get all subclass types of base class type parameter
/// Does not work with .NET scripting backend
/// </summary>
/// <param name="baseClassType">base class type</param>
/// <returns>list of subclass types for base class type parameter</returns>
public static List<Type> GetSubClasses(Type baseClassType)
{
#if !NETFX_CORE
if (baseClassType == null) { return null; }
if (!cache.ContainsKey(baseClassType))
{
cache[baseClassType] = baseClassType.GetAllSubClassesOf();
}
return cache[baseClassType];
#else
return null;
#endif
}
}
} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// Utility class to store subclasses of particular base class keys
/// Reloads between play mode/edit mode and after re-compile of scripts
/// </summary>
public static class TypeCacheUtility
{
private static Dictionary<Type, List<Type>> cache = new Dictionary<Type, List<Type>>();
/// <summary>
/// Get all subclass types of base class type T
/// </summary>
/// <typeparam name="T">base class of type T</typeparam>
/// <returns>list of subclass types for base class T</returns>
public static List<Type> GetSubClasses<T>()
{
return GetSubClasses(typeof(T));
}
/// <summary>
/// Get all subclass types of base class type parameter
/// </summary>
/// <param name="baseClassType">base class type</param>
/// <returns>list of subclass types for base class type parameter</returns>
public static List<Type> GetSubClasses(Type baseClassType)
{
if (baseClassType == null) { return null; }
if (!cache.ContainsKey(baseClassType))
{
cache[baseClassType] = baseClassType.GetAllSubClassesOf();
}
return cache[baseClassType];
}
}
} | mit | C# |
476070a39aebb6a30ff53f9aa48497b36d7bd5f6 | Fix issue where player input didn't respond well to low FPS (slower movement) | futurechris/zombai | Assets/Scripts/Models/Behaviors/PlayerControlBehavior.cs | Assets/Scripts/Models/Behaviors/PlayerControlBehavior.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerControlBehavior : AgentBehavior
{
// Get keyboard/touch input and convert it into a "plan"
public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits)
{
if(_myself.MoveInUse)
{
return false;
}
Action newMoveAction = null;
Action newLookAction = null;
// unlike other behaviors, for responsiveness, this should always clear immediately
this.currentPlans.Clear();
Vector2 lookVector = Vector2.zero;
Vector2 moveVector = Vector2.zero;
if(!_myself.LookInUse)
{
float hLookAxis = Input.GetAxis("LookHorizontal");
float vLookAxis = Input.GetAxis("LookVertical");
if(hLookAxis != 0 || vLookAxis != 0)
{
lookVector = new Vector2(hLookAxis, vLookAxis);
}
}
if(!_myself.MoveInUse)
{
float hAxis = Input.GetAxis("Horizontal");
float vAxis = Input.GetAxis("Vertical");
if(hAxis != 0 || vAxis != 0)
{
moveVector = new Vector2(hAxis*200.0f, vAxis*200.0f);
}
}
if(moveVector != Vector2.zero)
{
newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS);
newMoveAction.TargetPoint = (_myself.Location + moveVector);
this.currentPlans.Add(newMoveAction);
}
else
{
newMoveAction = new Action(Action.ActionType.STAY);
this.currentPlans.Add(newMoveAction);
}
if(lookVector != Vector2.zero)
{
newLookAction = new Action(Action.ActionType.TURN_TO_DEGREES);
Vector2 netVector = lookVector;
float angle = 90.0f - Mathf.Rad2Deg * Mathf.Atan2(netVector.x, netVector.y);
newLookAction.Direction = (angle);
this.currentPlans.Add(newLookAction);
}
else if(moveVector != Vector2.zero)
{
// if no specific look input, turn in the direction we're moving
// should maybe merge this block with the lookVector block above.
newLookAction = new Action(Action.ActionType.TURN_TO_DEGREES);
Vector2 netVector = moveVector;
float angle = 90.0f - Mathf.Rad2Deg * Mathf.Atan2(netVector.x, netVector.y);
newLookAction.Direction = (angle);
this.currentPlans.Add(newLookAction);
}
return (currentPlans.Count > 0);
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerControlBehavior : AgentBehavior
{
// Get keyboard/touch input and convert it into a "plan"
public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits)
{
if(_myself.MoveInUse)
{
return false;
}
Action newMoveAction = null;
Action newLookAction = null;
// unlike other behaviors, for responsiveness, this should always clear immediately
this.currentPlans.Clear();
Vector2 lookVector = Vector2.zero;
Vector2 moveVector = Vector2.zero;
if(!_myself.LookInUse)
{
float hLookAxis = Input.GetAxis("LookHorizontal");
float vLookAxis = Input.GetAxis("LookVertical");
if(hLookAxis != 0 || vLookAxis != 0)
{
lookVector = new Vector2(hLookAxis, vLookAxis);
}
}
if(!_myself.MoveInUse)
{
float hAxis = Input.GetAxis("Horizontal");
float vAxis = Input.GetAxis("Vertical");
if(hAxis != 0 || vAxis != 0)
{
moveVector = new Vector2(hAxis/2.0f, vAxis/2.0f);
}
}
if(moveVector != Vector2.zero)
{
newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS);
newMoveAction.TargetPoint = (_myself.Location + moveVector);
this.currentPlans.Add(newMoveAction);
}
else
{
newMoveAction = new Action(Action.ActionType.STAY);
this.currentPlans.Add(newMoveAction);
}
if(lookVector != Vector2.zero)
{
newLookAction = new Action(Action.ActionType.TURN_TO_DEGREES);
Vector2 netVector = lookVector;
float angle = 90.0f - Mathf.Rad2Deg * Mathf.Atan2(netVector.x, netVector.y);
newLookAction.Direction = (angle);
this.currentPlans.Add(newLookAction);
}
else if(moveVector != Vector2.zero)
{
// if no specific look input, turn in the direction we're moving
newLookAction = new Action(Action.ActionType.TURN_TOWARDS);
newLookAction.TargetPoint = (_myself.Location + moveVector);
this.currentPlans.Add(newLookAction);
}
return (currentPlans.Count > 0);
}
}
| mit | C# |
d2f172974568ab7269575bbc846706e9623b63df | Update AttributeSettingsAttribute.TargetAttributeType to use FirstOrDefault method instead of SingleOrDefault | YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata | src/Atata/Attributes/AttributeSettingsAttribute.cs | src/Atata/Attributes/AttributeSettingsAttribute.cs | using System;
using System.Linq;
namespace Atata
{
/// <summary>
/// Represents the base attribute settings class for other attributes.
/// </summary>
public abstract class AttributeSettingsAttribute : MulticastAttribute
{
/// <summary>
/// Gets or sets the target attribute types.
/// </summary>
public Type[] TargetAttributeTypes { get; set; }
/// <summary>
/// Gets or sets the target attribute type.
/// </summary>
public Type TargetAttributeType
{
get { return TargetAttributeTypes?.FirstOrDefault(); }
set { TargetAttributeTypes = value == null ? null : new[] { value }; }
}
public virtual int? CalculateTargetAttributeRank(Type targetAttributeType)
{
int? depthOfTypeInheritance = GetDepthOfInheritance(TargetAttributeTypes, targetAttributeType);
if (depthOfTypeInheritance == null)
return null;
int rankFactor = 100000;
return depthOfTypeInheritance >= 0
? Math.Max(rankFactor - (depthOfTypeInheritance.Value * 100), 0)
: 0;
}
}
}
| using System;
using System.Linq;
namespace Atata
{
/// <summary>
/// Represents the base attribute settings class for other attributes.
/// </summary>
public abstract class AttributeSettingsAttribute : MulticastAttribute
{
/// <summary>
/// Gets or sets the target attribute types.
/// </summary>
public Type[] TargetAttributeTypes { get; set; }
/// <summary>
/// Gets or sets the target attribute type.
/// </summary>
public Type TargetAttributeType
{
get { return TargetAttributeTypes?.SingleOrDefault(); }
set { TargetAttributeTypes = value == null ? null : new[] { value }; }
}
public virtual int? CalculateTargetAttributeRank(Type targetAttributeType)
{
int? depthOfTypeInheritance = GetDepthOfInheritance(TargetAttributeTypes, targetAttributeType);
if (depthOfTypeInheritance == null)
return null;
int rankFactor = 100000;
return depthOfTypeInheritance >= 0
? Math.Max(rankFactor - (depthOfTypeInheritance.Value * 100), 0)
: 0;
}
}
}
| apache-2.0 | C# |
cd5616f85d2c03878792b74084ff181107c6551c | Remove unnecessary css class | Kentico/Mvc,Kentico/Mvc,Kentico/Mvc | src/DancingGoat/Views/Contacts/_SocialLinks.cshtml | src/DancingGoat/Views/Contacts/_SocialLinks.cshtml | @model IEnumerable<CMS.DocumentEngine.Types.SocialLink>
@foreach (var link in Model)
{
<a class="followus-link" href="@link.Fields.Url" target="_blank">
@Html.AttachmentImage(link.Fields.Icon, link.Fields.Title)
</a>
}
| @model IEnumerable<CMS.DocumentEngine.Types.SocialLink>
@foreach (var link in Model)
{
<a class="followus-link" href="@link.Fields.Url" target="_blank">
@Html.AttachmentImage(link.Fields.Icon, link.Fields.Title, "cafe-image-tile-image")
</a>
}
| mit | C# |
a9447bab38eb112ac76af96b33a21a4427fb20ba | Fix a bug in form options | fredatgithub/WinFormTemplate | WinFormTemplate/FormOptions.cs | WinFormTemplate/FormOptions.cs | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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.Windows.Forms;
namespace WinFormTemplate
{
internal partial class FormOptions : Form
{
internal FormOptions(ConfigurationOptions configurationOptions)
{
if (configurationOptions == null)
{
//throw new ArgumentNullException(nameof(configurationOptions));
ConfigurationOptions = new ConfigurationOptions();
}
InitializeComponent();
ConfigurationOptions = configurationOptions;
checkBoxOption1.Checked = ConfigurationOptions.Option1Name;
checkBoxOption2.Checked = ConfigurationOptions.Option2Name;
}
internal ConfigurationOptions ConfigurationOptions { get; }
private void buttonOptionsOK_Click(object sender, EventArgs e)
{
ConfigurationOptions.Option1Name = checkBoxOption1.Checked;
ConfigurationOptions.Option2Name = checkBoxOption2.Checked;
Close();
}
private void buttonOptionsCancel_Click(object sender, EventArgs e)
{
Close();
}
private void FormOptions_Load(object sender, EventArgs e)
{
// take care of language
//buttonOptionsCancel.Text = _languageDicoEn["Cancel"];
}
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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.Windows.Forms;
namespace WinFormTemplate
{
internal partial class FormOptions : Form
{
internal FormOptions(ConfigurationOptions configurationOptions)
{
if (configurationOptions == null)
{
//throw new ArgumentNullException(nameof(configurationOptions));
configurationOptions = new ConfigurationOptions();
}
InitializeComponent();
ConfigurationOptions = configurationOptions;
checkBoxOption1.Checked = ConfigurationOptions.Option1Name;
checkBoxOption2.Checked = ConfigurationOptions.Option2Name;
}
internal ConfigurationOptions ConfigurationOptions { get; }
private void buttonOptionsOK_Click(object sender, EventArgs e)
{
ConfigurationOptions.Option1Name = checkBoxOption1.Checked;
ConfigurationOptions.Option2Name = checkBoxOption2.Checked;
Close();
}
private void buttonOptionsCancel_Click(object sender, EventArgs e)
{
Close();
}
private void FormOptions_Load(object sender, EventArgs e)
{
// take care of language
//buttonOptionsCancel.Text = _languageDicoEn["Cancel"];
}
}
} | mit | C# |
000ea711a63ccbc3af905c834d9254fa935ec6f9 | Fix indentation | MarcBruins/FSCalendar-Xamarin-iOS | FSCalendar/LinkWith.cs | FSCalendar/LinkWith.cs | using ObjCRuntime;
[assembly: LinkWith("libFSCalendar.a", LinkTarget.Arm64 | LinkTarget.ArmV7 | LinkTarget.Simulator | LinkTarget.Simulator64, Frameworks = "UIKit Foundation CoreGraphics", SmartLink = true, ForceLoad = true, LinkerFlags = "-ObjC -fobjc-arc")] | using ObjCRuntime;
[assembly: LinkWith("libFSCalendar.a",
LinkTarget.Arm64 | LinkTarget.ArmV7 | LinkTarget.Simulator | LinkTarget.Simulator64,
Frameworks = "UIKit Foundation CoreGraphics",
SmartLink = true,
ForceLoad = true,
LinkerFlags = "-ObjC -fobjc-arc")] | mit | C# |
4ad2ce348f379d2bb34c0d7656e7076da98819e0 | Change GetDealershipIdByName to GetDealershipByName in IDealershipService. | transactionCompleteDB/MAutoSS,transactionCompleteDB/MAutoSS | MAutoSS/MAutoSS.Services/Contracts/IDealershipService.cs | MAutoSS/MAutoSS.Services/Contracts/IDealershipService.cs | using System.Collections.Generic;
using MAutoSS.DataModels;
namespace MAutoSS.Services.Contracts
{
public interface IDealershipService
{
IEnumerable<Dealership> GetAllDealerships();
IEnumerable<string> GetAllDealershipsNames();
Dealership GetAllDealershipById(int id);
Dealership GetDealershipByName(string name);
void CreateNewDealership(string dealershipName, string addressText, string cityName, string countryName);
}
}
| using System.Collections.Generic;
using MAutoSS.DataModels;
namespace MAutoSS.Services.Contracts
{
public interface IDealershipService
{
IEnumerable<Dealership> GetAllDealerships();
IEnumerable<string> GetAllDealershipsNames();
Dealership GetDealershipIdByName(string name);
void CreateNewDealership(string dealershipName, string addressText, string cityName, string countryName);
}
}
| mit | C# |
804eb8c4b7dea93f4285473fb32411f78da6f7dd | Use exception filter attribute | GAnatoliy/geochallenger,GAnatoliy/geochallenger | GeoChallenger.Web.Api/Filters/ExceptionFilter.cs | GeoChallenger.Web.Api/Filters/ExceptionFilter.cs | using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
using NLog;
namespace GeoChallenger.Web.Api.Filters
{
public class ExceptionFilter : ExceptionFilterAttribute
{
private readonly ILogger _log = LogManager.GetCurrentClassLogger();
public override void OnException(HttpActionExecutedContext filterContext)
{
_log.Error(filterContext.Exception, "Unhandled exception");
}
}
} | using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
using NLog;
namespace GeoChallenger.Web.Api.Filters
{
public class ExceptionFilter : IExceptionFilter
{
private readonly ILogger _log = LogManager.GetCurrentClassLogger();
public bool AllowMultiple { get; }
public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
{
_log.Fatal(actionExecutedContext.Exception);
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError) {
Content = new ObjectContent(typeof(object), new {
errorDescription = actionExecutedContext.Exception.Message
}, new JsonMediaTypeFormatter())
};
return Task.FromResult(string.Empty);
}
}
} | mit | C# |
a813fae21ab47ffa7774590dbc9852a5eefe43c2 | add events to TccWindow class | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Windows/TccWindow.cs | TCC.Core/Windows/TccWindow.cs | using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace TCC.Windows
{
public class TccWindow : Window
{
public event Action Hidden;
public event Action Showed;
public void HideWindow()
{
var a = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(150));
a.Completed += (s, ev) =>
{
Hide();
if (Settings.Settings.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
Hidden?.Invoke();
};
BeginAnimation(OpacityProperty, a);
}
public void ShowWindow()
{
if (Settings.Settings.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.Default;
Dispatcher.Invoke(() =>
{
Topmost = false; Topmost = true;
Opacity = 0;
Show();
Showed?.Invoke();
BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200)));
});
}
}
} | using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace TCC.Windows
{
public class TccWindow : Window
{
public void HideWindow()
{
var a = new DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(150));
a.Completed += (s, ev) =>
{
Hide();
if (Settings.Settings.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly;
};
BeginAnimation(OpacityProperty, a);
}
public void ShowWindow()
{
if (Settings.Settings.ForceSoftwareRendering) RenderOptions.ProcessRenderMode = RenderMode.Default;
Dispatcher.Invoke(() =>
{
Topmost = false; Topmost = true;
Opacity = 0;
Show();
BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, TimeSpan.FromMilliseconds(200)));
});
}
}
} | mit | C# |
37f0566507a3c082b707ff3a0aa8c451d406fa21 | Switch back to GTK2 for now | illblew/TrueCraft,SirCmpwn/TrueCraft,flibitijibibo/TrueCraft,SirCmpwn/TrueCraft,SirCmpwn/TrueCraft,flibitijibibo/TrueCraft,flibitijibibo/TrueCraft,illblew/TrueCraft,illblew/TrueCraft | TrueCraft.Launcher/Program.cs | TrueCraft.Launcher/Program.cs | using System;
using Xwt;
using System.Threading;
using System.Net;
using TrueCraft.Core;
namespace TrueCraft.Launcher
{
class Program
{
public static LauncherWindow Window { get; set; }
[STAThread]
public static void Main(string[] args)
{
if (RuntimeInfo.IsLinux)
Application.Initialize(ToolkitType.Gtk);
else if (RuntimeInfo.IsMacOSX)
Application.Initialize(ToolkitType.Gtk); // TODO: Cocoa
else if (RuntimeInfo.IsWindows)
Application.Initialize(ToolkitType.Wpf);
UserSettings.Local = new UserSettings();
UserSettings.Local.Load();
var thread = new Thread(KeepSessionAlive);
thread.IsBackground = true;
thread.Priority = ThreadPriority.Lowest;
Window = new LauncherWindow();
thread.Start();
Window.Show();
Window.Closed += (sender, e) => Application.Exit();
Application.Run();
Window.Dispose();
thread.Abort();
}
private static void KeepSessionAlive()
{
while (true)
{
if (!string.IsNullOrEmpty(Window.User.SessionId))
{
var wc = new WebClient();
wc.DownloadString(string.Format(TrueCraftUser.AuthServer + "/session?name={0}&session={1}",
Window.User.Username, Window.User.SessionId));
}
Thread.Sleep(60 * 5 * 1000);
}
}
}
}
| using System;
using Xwt;
using System.Threading;
using System.Net;
using TrueCraft.Core;
namespace TrueCraft.Launcher
{
class Program
{
public static LauncherWindow Window { get; set; }
[STAThread]
public static void Main(string[] args)
{
if (RuntimeInfo.IsLinux)
{
try
{
Application.Initialize(ToolkitType.Gtk3);
}
catch
{
Application.Initialize(ToolkitType.Gtk);
}
}
else if (RuntimeInfo.IsMacOSX)
Application.Initialize(ToolkitType.Gtk); // TODO: Cocoa
else if (RuntimeInfo.IsWindows)
Application.Initialize(ToolkitType.Wpf);
UserSettings.Local = new UserSettings();
UserSettings.Local.Load();
var thread = new Thread(KeepSessionAlive);
thread.IsBackground = true;
thread.Priority = ThreadPriority.Lowest;
Window = new LauncherWindow();
thread.Start();
Window.Show();
Window.Closed += (sender, e) => Application.Exit();
Application.Run();
Window.Dispose();
thread.Abort();
}
private static void KeepSessionAlive()
{
while (true)
{
if (!string.IsNullOrEmpty(Window.User.SessionId))
{
var wc = new WebClient();
wc.DownloadString(string.Format(TrueCraftUser.AuthServer + "/session?name={0}&session={1}",
Window.User.Username, Window.User.SessionId));
}
Thread.Sleep(60 * 5 * 1000);
}
}
}
}
| mit | C# |
f76fa53e6fadfb9e71caf84022b9ceccf148aa5e | Fix after merge | github-for-unity/Unity,mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity | src/UnitTests/Repository/RepositoryManagerTests.cs | src/UnitTests/Repository/RepositoryManagerTests.cs | using System.Threading;
using GitHub.Unity;
using NSubstitute;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
class RepositoryManagerTests
{
[Test, Ignore()]
public void InitialTest()
{
NPathFileSystemProvider.Current = Substitute.For<IFileSystem>();
var cancellationToken = new CancellationToken();
var platform = Substitute.For<IPlatform>();
var repositoryRepositoryPathConfiguration = new RepositoryPathConfiguration(@"c:\Temp");
var gitConfig = Substitute.For<IGitConfig>();
var repositoryWatcher = Substitute.For<IRepositoryWatcher>();
var repositoryProcessRunner = Substitute.For<IRepositoryProcessRunner>();
var repositoryManager = new RepositoryManager(repositoryRepositoryPathConfiguration, platform, gitConfig, repositoryWatcher, repositoryProcessRunner, cancellationToken);
}
}
}
| using System.Threading;
using GitHub.Unity;
using NSubstitute;
using NUnit.Framework;
namespace UnitTests
{
[TestFixture]
class RepositoryManagerTests : TestBase
{
[Test, Ignore()]
public void InitialTest()
{
NPathFileSystemProvider.Current = Substitute.For<IFileSystem>();
var cancellationToken = new CancellationToken();
var platform = Substitute.For<IPlatform>();
var repositoryRepositoryPathConfiguration = new RepositoryPathConfiguration(@"c:\Temp");
var gitConfig = Substitute.For<IGitConfig>();
var repositoryWatcher = Substitute.For<IRepositoryWatcher>();
var repositoryProcessRunner = Substitute.For<IRepositoryProcessRunner>();
var repositoryManager = new RepositoryManager(repositoryRepositoryPathConfiguration, platform, gitConfig, repositoryWatcher, repositoryProcessRunner, cancellationToken);
}
}
}
| mit | C# |
39cc6a8a83edd43f79079da1eaa81a82ea637303 | Add label to the node colour key explaining what it is | willb611/SlimeSimulation | SlimeSimulation/View/WindowComponent/NodeHighlightKey.cs | SlimeSimulation/View/WindowComponent/NodeHighlightKey.cs | using Gtk;
using SlimeSimulation.Controller.WindowComponentController;
namespace SlimeSimulation.View.WindowComponent
{
public class NodeHighlightKey
{
public Widget GetVisualKey()
{
VBox key = new VBox(true, 10);
key.Add(new Label("Node colour key"));
var sourcePart = new HBox(true, 10);
sourcePart.Add(new Label("Source"));
sourcePart.Add(GetBoxColour(FlowResultNodeViewController.SourceColour));
HBox sinkPart = new HBox(true, 10);
sinkPart.Add(new Label("Sink"));
sinkPart.Add(GetBoxColour(FlowResultNodeViewController.SinkColour));
HBox normalPart = new HBox(true, 10);
normalPart.Add(new Label("Normal node"));
normalPart.Add(GetBoxColour(FlowResultNodeViewController.NormalNodeColour));
key.Add(sourcePart);
key.Add(sinkPart);
key.Add(normalPart);
return key;
}
private DrawingArea GetBoxColour(Rgb color)
{
return new ColorArea(color);
}
}
}
| using Gtk;
using SlimeSimulation.Controller.WindowComponentController;
namespace SlimeSimulation.View.WindowComponent
{
public class NodeHighlightKey
{
public Widget GetVisualKey()
{
VBox key = new VBox(true, 10);
HBox sourcePart = new HBox(true, 10);
sourcePart.Add(new Label("Source"));
sourcePart.Add(GetBoxColour(FlowResultNodeViewController.SourceColour));
HBox sinkPart = new HBox(true, 10);
sinkPart.Add(new Label("Sink"));
sinkPart.Add(GetBoxColour(FlowResultNodeViewController.SinkColour));
HBox normalPart = new HBox(true, 10);
normalPart.Add(new Label("Normal node"));
normalPart.Add(GetBoxColour(FlowResultNodeViewController.NormalNodeColour));
key.Add(sourcePart);
key.Add(sinkPart);
key.Add(normalPart);
return key;
}
private DrawingArea GetBoxColour(Rgb color)
{
return new ColorArea(color);
}
}
}
| apache-2.0 | C# |
ef29905f217f4a8c72b2ccab1822bd9f8e08db5a | Remove bad test | ToJans/JabbR,mogulTest1/Project13231109,Createfor1322/jessica0122-1322,kudustress/JabbR,SonOfSam/JabbR,CrankyTRex/JabbRMirror,LookLikeAPro/JabbR,KuduautomationGithubOrganization/JabbrInitialSuccess,huanglitest/JabbRTest2,clarktestkudu1029/test08jabbr,MogulTestOrg/JabbrApp,kudupublic/test0704jabbr,mogulTest1/Project13161127,mogultest2/Project92104,CrankyTRex/JabbRMirror,kudupublic/lizzy0703,mogulTest1/Project13171024,mogulTest1/ProjectfoIssue6,mogulTest1/Project91404,kuduautomation/jabbr,timgranstrom/JabbR,krolson/kkJabbr,mogulTest1/Project13231113,ClarkL/test09jabbr,mogultest2/Project13171210,v-jli/jean0704jabbryamini,mogulTest1/Project13231213,meebey/JabbR,e10/JabbR,Org1106/Project13221106,yadyn/JabbR,mogulTest1/Project13171109,ToJans/JabbR,mogulTest1/Project13231113,mogulTest1/Project13171009,ClarkL/new09,mogulTest1/Project13171106,MogulTestOrg9221/Project92108,mogulTest1/Project13171009,KuduApps/TestDeploy123,mogulTest1/Project13171106,LookLikeAPro/JabbR,MogulTestOrg/JabbrApp,mogultest2/Project92105,mogulTest1/Project90301,kudupublic/lizzy0703,mogulTest1/Project91009,Haacked/JabbR,Haacked/JabbR,pavanaReddy/Testing730,mogulTest1/Project91101,mogulTest1/Project13231212,mogulTest1/ProjectfoIssue6,borisyankov/JabbR,ClarkL/1323on17jabbr-,kudutest/FaizJabbr,clarktestkudu1029/test08jabbr,krolson/kkJabbr,huanglitest/JabbRTest2,mogulTest1/Project13161127,v-jli/jean0704jabbryamini,JabbR/JabbR,test0925/test0925,mogulTest1/ProjectJabbr01,ClarkL/test09jabbr,v-jli/jean0704jabbryamini,mogulTest1/Project13231106,ClarkL/new09,v-jli1/jean1210jabbr,mogultest2/Project13171210,mogultest2/Project92109,fuzeman/vox,M-Zuber/JabbR,MogulTestOrg1008/Project13221008,mogulTest1/Project13171205,mogulTest1/Project13231213,ToJans/JabbR,ClarkL/new1317,borisyankov/JabbR,huanglitest/JabbRTest2,MogulTestOrg9221/Project92108,mogultest2/Project92109,test0925/test0925,KuduautomationGithubOrganization/JabbrInitialSuccess,mogulTest1/MogulVerifyIssue5,fuzeman/vox,meebey/JabbR,kudupublic/lizzy0703,mogulTest1/Project13231106,v-mohua/TestProject91001,AAPT/jean0226case1322,e10/JabbR,MogulTestOrg911/Project91104,mogultest2/Project92105,mogulTest1/Project91101,lukehoban/JabbR,mogultest2/Project13171008,mogulTest1/Project91409,18098924759/JabbR,mogulTest1/Project91105,MogulTestOrg2/JabbrApp,kudupublic/test0704jabbr,v-mohua/TestProject91001,ClarkL/1317on17jabbr,v-jli1/jean1210jabbr,kudupublic/test0704jabbr,mogultest2/Project92104,mogulTest1/Project13171113,mogultest2/Project13171008,mogulTest1/Project91404,GitHubFlora001/jabbrtest0416,yadyn/JabbR,mogulTest1/Project13231109,borisyankov/JabbR,mzdv/JabbR,pavanaReddy/Testing730,mogulTest1/MogulVerifyIssue5,MogulTestOrg914/Project91407,mogulTest1/Project13171024,mogultest2/Project13231008,lukehoban/JabbR,ClarkL/new1317,mogulTest1/Project13171113,timgranstrom/JabbR,ajayanandgit/JabbR,ajayanandgit/JabbR,MogulTestOrg1008/Project13221008,mogultest2/Project13171010,kudustress/JabbR,Createfor1322/jessica0122-1322,mogulTest1/ProjectJabbr01,ClarkL/1317on17jabbr,AAPT/jean0226case1322,KuduApps/TestDeploy123,SonOfSam/JabbR,meebey/JabbR,mogulTest1/Project90301,fuzeman/vox,mogulTest1/Project91409,mogulTest1/Project13171205,mogulTest1/Project91009,yadyn/JabbR,GitHubFlora001/jabbrtest0416,pavanaReddy/Testing730,CrankyTRex/JabbRMirror,MogulTestOrg2/JabbrApp,kuduautomation/jabbr,v-jli1/jean1210jabbr,aapttester/jack12051317,Org1106/Project13221113,mogulTest1/ProjectVerify912,mogultest2/Project13231008,GitHubFlora001/jabbrtest0416,kuduautomation/jabbr,Org1106/Project13221113,ClarkL/1323on17jabbr-,Haacked/JabbR,mogultest2/Project13171010,KuduautomationGithubOrganization/JabbrInitialSuccess,JabbR/JabbR,lukehoban/JabbR,mogulTest1/Project13231205,M-Zuber/JabbR,mogulTest1/Project91105,kudutest/FaizJabbr,mogulTest1/Project13231205,mogulTest1/ProjectVerify912,mzdv/JabbR,krolson/kkJabbr,Org1106/Project13221106,kudustress/JabbR,18098924759/JabbR,mogulTest1/Project13231212,mogulTest1/Project13171109,MogulTestOrg911/Project91104,MogulTestOrg914/Project91407,LookLikeAPro/JabbR,aapttester/jack12051317 | JabbR.Test/ChatTest.cs | JabbR.Test/ChatTest.cs | using System.Security.Principal;
using System.Web;
using JabbR.Models;
using Moq;
using SignalR;
using SignalR.Hubs;
using Xunit;
namespace JabbR.Test
{
public class ChatTest
{
[Fact]
public void JoinReturnsFalseIfNoCookies()
{
var repository = new InMemoryRepository();
var chat = new Chat(repository);
var connection = new Mock<IConnection>();
var prinicipal = new Mock<IPrincipal>();
var clientState = new TrackingDictionary();
string clientId = "test";
chat.Agent = new ClientAgent(connection.Object, "Chat");
chat.Caller = new SignalAgent(connection.Object, clientId, "Chat", clientState);
chat.Context = new HubContext(clientId, new HttpCookieCollection(), prinicipal.Object);
bool result = chat.Join();
string versionString = typeof(Chat).Assembly.GetName().Version.ToString();
Assert.Equal(versionString, clientState["version"]);
Assert.False(result);
}
}
}
| using System.Security.Principal;
using System.Web;
using JabbR.Models;
using Moq;
using SignalR;
using SignalR.Hubs;
using Xunit;
namespace JabbR.Test
{
public class ChatTest
{
[Fact]
public void JoinReturnsFalseIfNoCookies()
{
var repository = new InMemoryRepository();
var chat = new Chat(repository);
var connection = new Mock<IConnection>();
var prinicipal = new Mock<IPrincipal>();
var clientState = new TrackingDictionary();
string clientId = "test";
chat.Agent = new ClientAgent(connection.Object, "Chat");
chat.Caller = new SignalAgent(connection.Object, clientId, "Chat", clientState);
chat.Context = new HubContext(clientId, new HttpCookieCollection(), prinicipal.Object);
bool result = chat.Join();
string versionString = typeof(Chat).Assembly.GetName().Version.ToString();
Assert.Equal(versionString, clientState["version"]);
Assert.False(result);
}
[Fact]
public void JoinCallsAddUserIfValidUserIdInCookieAndUserList()
{
var repository = new InMemoryRepository();
var user = new ChatUser
{
Id = "1234",
Name = "John",
Hash = "Hash"
};
repository.Add(user);
var chat = new Chat(repository);
var connection = new Mock<IConnection>();
var prinicipal = new Mock<IPrincipal>();
var cookies = new HttpCookieCollection();
cookies.Add(new HttpCookie("userid", "1234"));
var clientState = new TrackingDictionary();
string clientId = "20";
chat.Agent = new ClientAgent(connection.Object, "Chat");
chat.Caller = new SignalAgent(connection.Object, clientId, "Chat", clientState);
chat.Context = new HubContext(clientId, cookies, prinicipal.Object);
chat.Join();
Assert.Equal("1234", clientState["id"]);
Assert.Equal("John", clientState["name"]);
Assert.Equal("Hash", clientState["hash"]);
Assert.Equal("20", user.ClientId);
// Need a better way to verify method name and arguments
connection.Verify(m => m.Broadcast("Chat.20", It.IsAny<object>()), Times.Once());
}
}
}
| mit | C# |
2afd29e9c879ce0693f96d85dcd373ceda21d043 | Use existing OnDataContextChanged method. | wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex | src/Avalonia.ReactiveUI/ReactiveUserControl.cs | src/Avalonia.ReactiveUI/ReactiveUserControl.cs | using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia;
using Avalonia.VisualTree;
using Avalonia.Controls;
using ReactiveUI;
namespace Avalonia.ReactiveUI
{
/// <summary>
/// A ReactiveUI <see cref="UserControl"/> that implements the <see cref="IViewFor{TViewModel}"/> interface and
/// will activate your ViewModel automatically if the view model implements <see cref="IActivatableViewModel"/>.
/// When the DataContext property changes, this class will update the ViewModel property with the new DataContext
/// value, and vice versa.
/// </summary>
/// <typeparam name="TViewModel">ViewModel type.</typeparam>
public class ReactiveUserControl<TViewModel> : UserControl, IViewFor<TViewModel> where TViewModel : class
{
public static readonly StyledProperty<TViewModel> ViewModelProperty = AvaloniaProperty
.Register<ReactiveUserControl<TViewModel>, TViewModel>(nameof(ViewModel));
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveUserControl{TViewModel}"/> class.
/// </summary>
public ReactiveUserControl()
{
// This WhenActivated block calls ViewModel's WhenActivated
// block if the ViewModel implements IActivatableViewModel.
this.WhenActivated(disposables => { });
this.GetObservable(ViewModelProperty).Subscribe(OnViewModelChanged);
}
/// <summary>
/// The ViewModel.
/// </summary>
public TViewModel ViewModel
{
get => GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
object IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (TViewModel)value;
}
protected override void OnDataContextChanged(EventArgs e)
{
ViewModel = DataContext as TViewModel;
}
private void OnViewModelChanged(object value)
{
if (value == null)
{
ClearValue(DataContextProperty);
}
else if (DataContext != value)
{
DataContext = value;
}
}
}
}
| using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Avalonia;
using Avalonia.VisualTree;
using Avalonia.Controls;
using ReactiveUI;
namespace Avalonia.ReactiveUI
{
/// <summary>
/// A ReactiveUI <see cref="UserControl"/> that implements the <see cref="IViewFor{TViewModel}"/> interface and
/// will activate your ViewModel automatically if the view model implements <see cref="IActivatableViewModel"/>.
/// When the DataContext property changes, this class will update the ViewModel property with the new DataContext
/// value, and vice versa.
/// </summary>
/// <typeparam name="TViewModel">ViewModel type.</typeparam>
public class ReactiveUserControl<TViewModel> : UserControl, IViewFor<TViewModel> where TViewModel : class
{
public static readonly StyledProperty<TViewModel> ViewModelProperty = AvaloniaProperty
.Register<ReactiveUserControl<TViewModel>, TViewModel>(nameof(ViewModel));
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveUserControl{TViewModel}"/> class.
/// </summary>
public ReactiveUserControl()
{
// This WhenActivated block calls ViewModel's WhenActivated
// block if the ViewModel implements IActivatableViewModel.
this.WhenActivated(disposables => { });
this.GetObservable(DataContextProperty).Subscribe(OnDataContextChanged);
this.GetObservable(ViewModelProperty).Subscribe(OnViewModelChanged);
}
/// <summary>
/// The ViewModel.
/// </summary>
public TViewModel ViewModel
{
get => GetValue(ViewModelProperty);
set => SetValue(ViewModelProperty, value);
}
object IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (TViewModel)value;
}
private void OnDataContextChanged(object value)
{
if (value is TViewModel viewModel)
{
ViewModel = viewModel;
}
else
{
ViewModel = null;
}
}
private void OnViewModelChanged(object value)
{
if (value == null)
{
ClearValue(DataContextProperty);
}
else if (DataContext != value)
{
DataContext = value;
}
}
}
}
| mit | C# |
077655a422a7978220d2964f3dc2c7a99d413d01 | Fix Android | larsbrubaker/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl | SetupWizard/AndroidNetworkTroubleshootingPage.cs | SetupWizard/AndroidNetworkTroubleshootingPage.cs | /*
Copyright (c) 2016, Kevin Pope, 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.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
namespace MatterHackers.MatterControl
{
public class NetworkTroubleshooting : WizardPage
{
public NetworkTroubleshooting()
{
string matterhackersStatusString = "MatterControl was unable to connect to the Internet. Please check your Wifi connection and try again".Localize();
contentRow.AddChild(new TextWidget(matterhackersStatusString + "...", 0, 0, 12, textColor: ActiveTheme.Instance.PrimaryTextColor));
Button configureButton = whiteImageButtonFactory.Generate("Configure Wifi".Localize());
configureButton.Margin = new BorderDouble(0, 0, 10, 0);
configureButton.Click += (s, e) =>
{
MatterControlApplication.Instance.ConfigureWifi();
UiThread.RunOnIdle(WizardWindow.Close, 1);
// We could clear the failure count allowing the user to toggle wifi, then retry sign-in
//ApplicationController.WebRequestSucceeded();
};
//Add buttons to buttonContainer
AddPageAction(configureButton);
cancelButton.Visible = true;
}
}
}
| /*
Copyright (c) 2016, Kevin Pope, 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.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.CustomWidgets;
namespace MatterHackers.MatterControl
{
public class NetworkTroubleshooting : WizardPage
{
public NetworkTroubleshooting()
{
string matterhackersStatusString = "MatterControl was unable to connect to the Internet. Please check your Wifi connection and try again".Localize();
contentRow.AddChild(new TextWidget(matterhackersStatusString + "...", 0, 0, 12, textColor: ActiveTheme.Instance.PrimaryTextColor));
Button configureButton = whiteImageButtonFactory.Generate("Configure Wifi".Localize(), centerText: true);
configureButton.Margin = new BorderDouble(0, 0, 10, 0);
configureButton.Click += (s, e) =>
{
MatterControlApplication.Instance.ConfigureWifi();
UiThread.RunOnIdle(WizardWindow.Close, 1);
// We could clear the failure count allowing the user to toggle wifi, then retry sign-in
//ApplicationController.WebRequestSucceeded();
};
//Add buttons to buttonContainer
AddPageAction(configureButton);
cancelButton.Visible = true;
}
}
}
| bsd-2-clause | C# |
8a407a868688223504e194d168ddde2d56b13182 | Update summary | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/EstoniaProvider.cs | Src/Nager.Date/PublicHolidays/EstoniaProvider.cs | using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
/// <summary>
/// Estonia
/// https://en.wikipedia.org/wiki/Public_holidays_in_Estonia
/// </summary>
public class EstoniaProvider : IPublicHolidayProvider
{
private readonly ICatholicProvider _catholicProvider;
/// <summary>
/// EstoniaProvider
/// </summary>
/// <param name="catholicProvider"></param>
public EstoniaProvider(ICatholicProvider catholicProvider)
{
this._catholicProvider = catholicProvider;
}
/// <summary>
/// Get
/// </summary>
/// <param name="year">The year</param>
/// <returns></returns>
public IEnumerable<PublicHoliday> Get(int year)
{
var countryCode = CountryCode.EE;
var easterSunday = this._catholicProvider.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "uusaasta", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 2, 24, "iseseisvuspäev", "Independence Day", countryCode, 1918));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "suur reede", "Good Friday", countryCode));
items.Add(new PublicHoliday(easterSunday, "ülestõusmispühade 1. püha", "Easter Sunday", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "kevadpüha", "Spring Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(49), "nelipühade 1. püha", "Pentecost", countryCode));
items.Add(new PublicHoliday(year, 6, 23, "võidupüha and jaanilaupäev", "Victory Day", countryCode));
items.Add(new PublicHoliday(year, 6, 24, "jaanipäev", "Midsummer Day", countryCode));
items.Add(new PublicHoliday(year, 8, 20, "taasiseseisvumispäev", "Day of Restoration of Independence", countryCode, 1991));
items.Add(new PublicHoliday(year, 12, 24, "jõululaupäev", "Christmas Eve", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "esimene jõulupüha", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "teine jõulupüha", "St. Stephen's Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
/// <summary>
/// Estonia
/// https://en.wikipedia.org/wiki/Public_holidays_in_Estonia
/// </summary>
public class EstoniaProvider : IPublicHolidayProvider
{
private readonly ICatholicProvider _catholicProvider;
public EstoniaProvider(ICatholicProvider catholicProvider)
{
this._catholicProvider = catholicProvider;
}
public IEnumerable<PublicHoliday> Get(int year)
{
var countryCode = CountryCode.EE;
var easterSunday = this._catholicProvider.EasterSunday(year);
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "uusaasta", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 2, 24, "iseseisvuspäev", "Independence Day", countryCode, 1918));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "suur reede", "Good Friday", countryCode));
items.Add(new PublicHoliday(easterSunday, "ülestõusmispühade 1. püha", "Easter Sunday", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "kevadpüha", "Spring Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(49), "nelipühade 1. püha", "Pentecost", countryCode));
items.Add(new PublicHoliday(year, 6, 23, "võidupüha and jaanilaupäev", "Victory Day", countryCode));
items.Add(new PublicHoliday(year, 6, 24, "jaanipäev", "Midsummer Day", countryCode));
items.Add(new PublicHoliday(year, 8, 20, "taasiseseisvumispäev", "Day of Restoration of Independence", countryCode, 1991));
items.Add(new PublicHoliday(year, 12, 24, "jõululaupäev", "Christmas Eve", countryCode));
items.Add(new PublicHoliday(year, 12, 25, "esimene jõulupüha", "Christmas Day", countryCode));
items.Add(new PublicHoliday(year, 12, 26, "teine jõulupüha", "St. Stephen's Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# |
43965cfae722352e41c01d82b3baf23f94915274 | Simplify TestLayer | charlenni/Mapsui,charlenni/Mapsui | Tests/Mapsui.Tests.Common/TestTools/TestLayer.cs | Tests/Mapsui.Tests.Common/TestTools/TestLayer.cs | using Mapsui.Extensions;
using Mapsui.Layers;
using Mapsui.Providers;
using Mapsui.Styles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mapsui.Tests.Common.TestTools
{
/// <summary>
/// This layer calls the DataSource directly from the GetFeatures method. This should be avoided
/// in a real application because the GetFeatures methods is called in the rendering loop. For
/// testing this layer is used to generate an image from the data source without having to wait for
/// the asynchronous data fetch call to finish.
/// </summary>
public class TestLayer : BaseLayer
{
public IProvider? DataSource { get; set; }
public string? CRS { get; set; }
public override IEnumerable<IFeature> GetFeatures(MRect box, double resolution)
{
if (box == null)
yield break;
var biggerBox = box.Grow(
SymbolStyle.DefaultWidth * 2 * resolution,
SymbolStyle.DefaultHeight * 2 * resolution);
var fetchInfo = new FetchInfo(biggerBox, resolution, CRS);
if (DataSource is null)
yield break;
#pragma warning disable VSTHRD002 // Allow use of .Result for test purposes
foreach (var feature in DataSource.GetFeaturesAsync(fetchInfo).ToListAsync().Result)
yield return feature;
#pragma warning restore VSTHRD002 //
}
public override MRect? Extent => DataSource?.GetExtent();
}
}
| using Mapsui.Extensions;
using Mapsui.Layers;
using Mapsui.Providers;
using Mapsui.Styles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mapsui.Tests.Common.TestTools
{
/// <summary>
/// This layer calls the DataSource directly from the GetFeatures method. This should be avoided
/// in a real application because the GetFeatures methods is called in the rendering loop. For
/// testing this can be useful when wnat to generate an image from the data source without
/// having to wait for the asynchronous data fetch call.
/// </summary>
public class TestLayer : BaseLayer, ILayerDataSource<IProvider>
{
public IProvider? DataSource { get; set; }
public string? CRS { get; set; }
public override IEnumerable<IFeature> GetFeatures(MRect box, double resolution)
{
if (box == null)
yield break;
var biggerBox = box.Grow(
SymbolStyle.DefaultWidth * 2 * resolution,
SymbolStyle.DefaultHeight * 2 * resolution);
var fetchInfo = new FetchInfo(biggerBox, resolution, CRS);
if (DataSource is null)
yield break;
#pragma warning disable VSTHRD002 // Allow use of .Result for test purposes
foreach (var feature in DataSource.GetFeaturesAsync(fetchInfo).ToListAsync().Result)
yield return feature;
#pragma warning restore VSTHRD002 //
}
public override MRect? Extent => DataSource?.GetExtent();
IProvider? ILayerDataSource<IProvider>.DataSource => throw new NotImplementedException();
}
}
| mit | C# |
8a7bf6adb5ba00d073b7ef8e9141288b5b10e948 | Fix possible NRE in SpaceCleaner | Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation | UnityProject/Assets/Scripts/Tool/SpaceCleaner.cs | UnityProject/Assets/Scripts/Tool/SpaceCleaner.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
[RequireComponent(typeof(Pickupable))]
public class SpaceCleaner : NetworkBehaviour, ICheckedInteractable<AimApply>
{
public int travelDistance = 6;
private float travelTime => 1f / travelDistance;
[SerializeField]
[Range(1,50)]
private int reagentsPerUse = 5;
private ReagentContainer reagentContainer;
private void Awake()
{
reagentContainer = GetComponent<ReagentContainer>();
}
public bool WillInteract(AimApply interaction, NetworkSide side)
{
if (interaction.MouseButtonState == MouseButtonState.PRESS)
{
return true;
}
return false;
}
public void ServerPerformInteraction(AimApply interaction)
{
//just in case
if (reagentContainer == null) return;
if (reagentContainer.CurrentCapacity < reagentsPerUse)
{
return;
}
Vector2 startPos = gameObject.AssumedWorldPosServer();
Vector2 targetPos = new Vector2(Mathf.RoundToInt(interaction.WorldPositionTarget.x), Mathf.RoundToInt(interaction.WorldPositionTarget.y));
List<Vector3Int> positionList = MatrixManager.GetTiles(startPos, targetPos, travelDistance);
StartCoroutine(Fire(positionList));
Effect.PlayParticleDirectional( this.gameObject, interaction.TargetVector );
reagentContainer.TakeReagents(reagentsPerUse);
SoundManager.PlayNetworkedAtPos("Spray2", startPos, 1);
interaction.Performer.Pushable()?.NewtonianMove((-interaction.TargetVector).NormalizeToInt(), speed: 1f);
}
private IEnumerator Fire(List<Vector3Int> positionList)
{
for (int i = 0; i < positionList.Count; i++)
{
SprayTile(positionList[i]);
yield return WaitFor.Seconds(travelTime);
}
}
void SprayTile(Vector3Int worldPos)
{
//it actually uses remaining contents of the bottle to react with world
//instead of the sprayed ones. not sure if this is right
MatrixManager.ReagentReact(reagentContainer.Contents, worldPos);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
[RequireComponent(typeof(Pickupable))]
public class SpaceCleaner : NetworkBehaviour, ICheckedInteractable<AimApply>
{
public int travelDistance = 6;
public ReagentContainer reagentContainer;
private float travelTime => 1f / travelDistance;
[SerializeField]
[Range(1,50)]
private int reagentsPerUse = 5;
public bool WillInteract(AimApply interaction, NetworkSide side)
{
if (interaction.MouseButtonState == MouseButtonState.PRESS)
{
return true;
}
return false;
}
public void ServerPerformInteraction(AimApply interaction)
{
if (reagentContainer.CurrentCapacity < reagentsPerUse)
{
return;
}
Vector2 startPos = gameObject.AssumedWorldPosServer();
Vector2 targetPos = new Vector2(Mathf.RoundToInt(interaction.WorldPositionTarget.x), Mathf.RoundToInt(interaction.WorldPositionTarget.y));
List<Vector3Int> positionList = MatrixManager.GetTiles(startPos, targetPos, travelDistance);
StartCoroutine(Fire(positionList));
Effect.PlayParticleDirectional( this.gameObject, interaction.TargetVector );
reagentContainer.TakeReagents(reagentsPerUse);
SoundManager.PlayNetworkedAtPos("Spray2", startPos, 1);
interaction.Performer.Pushable()?.NewtonianMove((-interaction.TargetVector).NormalizeToInt(), speed: 1f);
}
private IEnumerator Fire(List<Vector3Int> positionList)
{
for (int i = 0; i < positionList.Count; i++)
{
SprayTile(positionList[i]);
yield return WaitFor.Seconds(travelTime);
}
}
void SprayTile(Vector3Int worldPos)
{
//it actually uses remaining contents of the bottle to react with world
//instead of the sprayed ones. not sure if this is right
MatrixManager.ReagentReact(reagentContainer.Contents, worldPos);
}
}
| agpl-3.0 | C# |
f1fa5e7c20a55a77ce5be9680a13585b4a47a340 | Clean up server code | explunit/crypto-pitfalls | VulnServer1/Controllers/TransactionController.cs | VulnServer1/Controllers/TransactionController.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using Utils;
namespace VulnServer1.Controllers
{
public struct TransactionResult
{
public string Status;
public long ConfirmationNumber;
}
public class TransactionController : ApiController
{
public TransactionResult Get( string ticket )
{
var encryptionKeyString = "4f256766a4075027695bd48b444e1ac5c7c17385a1b4f1779e6385da24d97997";
byte[] encryptionKey = QuickCrypto.StringToByteArray( encryptionKeyString );
byte[] ticketBytes = QuickCrypto.StringToByteArray( ticket.Substring( 32 ) );
byte[] ivBytes = QuickCrypto.StringToByteArray( ticket.Substring( 0, 32 ) );
string decrypted;
try
{
decrypted = QuickCrypto.DecryptStringFromBytes_Aes( ticketBytes, encryptionKey, ivBytes );
}
catch
{
return new TransactionResult() { Status = "Bad Token" };
}
long accountNumber = 0;
string[] ticketParts = decrypted.Split( '|' );
// some fake validation
bool validAccount = Int64.TryParse( ticketParts[ 0 ], out accountNumber );
if ( ticketParts.Length == 4 && validAccount )
{
return new TransactionResult() { Status = "OK", ConfirmationNumber = 123 };
}
return new TransactionResult() { Status = "Invalid Request" };
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web.Http;
using Utils;
namespace VulnServer1.Controllers
{
public struct TransactionResult
{
public string Status;
public long ConfirmationNumber;
}
public class TransactionController : ApiController
{
public TransactionResult Get( string ticket )
{
var encryptionKeyString = "4f256766a4075027695bd48b444e1ac5c7c17385a1b4f1779e6385da24d97997";
byte[] encryptionKey = QuickCrypto.StringToByteArray( encryptionKeyString );
//var testValue = "15608714654|ACPT|109.76|20150203 23:59";
//var testToken = "cc50cf4e7de93ba5e9b15993b0fc1798208d3c91e0c4c73c1b183e8d1fee07e862c6eae43a91d6c7982163dbfc6df64fe322c63a73f7dfdcbe64992ba826dff5a4ccbb57fcc4e701db12016a17b18874";
//byte[] IV = QuickCrypto.GetRandomIV();
//byte[] encrypted = QuickCrypto.EncryptStringToBytes_Aes( testValue, encryptionKey, IV );
//string ivHex = QuickCrypto.ByteArrayToString( IV );
//string tokenHex = QuickCrypto.ByteArrayToString( encrypted );
byte[] ticketBytes = QuickCrypto.StringToByteArray( ticket.Substring( 32 ) );
byte[] ivBytes = QuickCrypto.StringToByteArray( ticket.Substring( 0, 32 ) );
string decrypted = QuickCrypto.DecryptStringFromBytes_Aes( ticketBytes, encryptionKey, ivBytes );
if ( decrypted.Split( '|' ).Length == 4 )
{
return new TransactionResult() { Status = "OK", ConfirmationNumber = 123 };
}
return new TransactionResult() { Status = "Invalid Request" };
}
}
} | mit | C# |
4f88f0950c53dfe5898ca5d24c319f2d1b017eea | Allow null next middleware | bryceg/Owin.WebSocket | src/Owin.WebSocket/WebSocketConnectionMiddleware.cs | src/Owin.WebSocket/WebSocketConnectionMiddleware.cs | using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Practices.ServiceLocation;
using System;
namespace Owin.WebSocket
{
public class WebSocketConnectionMiddleware<T> : OwinMiddleware where T : WebSocketConnection
{
private readonly Regex mMatchPattern;
private readonly IServiceLocator mServiceLocator;
private static readonly Task completedTask = Task.FromResult(false);
public WebSocketConnectionMiddleware(OwinMiddleware next, IServiceLocator locator)
: base(next)
{
mServiceLocator = locator;
}
public WebSocketConnectionMiddleware(OwinMiddleware next, IServiceLocator locator, Regex matchPattern)
: this(next, locator)
{
mMatchPattern = matchPattern;
}
public override Task Invoke(IOwinContext context)
{
var matches = new Dictionary<string, string>();
if (mMatchPattern != null)
{
var match = mMatchPattern.Match(context.Request.Path.Value);
if(!match.Success)
return Next?.Invoke(context) ?? completedTask;
for (var i = 1; i <= match.Groups.Count; i++)
{
var name = mMatchPattern.GroupNameFromNumber(i);
var value = match.Groups[i];
matches.Add(name, value.Value);
}
}
T socketConnection;
if(mServiceLocator == null)
socketConnection = Activator.CreateInstance<T>();
else
socketConnection = mServiceLocator.GetInstance<T>();
return socketConnection.AcceptSocketAsync(context, matches);
}
}
} | using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Practices.ServiceLocation;
using System;
namespace Owin.WebSocket
{
public class WebSocketConnectionMiddleware<T> : OwinMiddleware where T : WebSocketConnection
{
private readonly Regex mMatchPattern;
private readonly IServiceLocator mServiceLocator;
public WebSocketConnectionMiddleware(OwinMiddleware next, IServiceLocator locator)
: base(next)
{
mServiceLocator = locator;
}
public WebSocketConnectionMiddleware(OwinMiddleware next, IServiceLocator locator, Regex matchPattern)
: this(next, locator)
{
mMatchPattern = matchPattern;
}
public override Task Invoke(IOwinContext context)
{
var matches = new Dictionary<string, string>();
if (mMatchPattern != null)
{
var match = mMatchPattern.Match(context.Request.Path.Value);
if(!match.Success)
return Next.Invoke(context);
for (var i = 1; i <= match.Groups.Count; i++)
{
var name = mMatchPattern.GroupNameFromNumber(i);
var value = match.Groups[i];
matches.Add(name, value.Value);
}
}
T socketConnection;
if(mServiceLocator == null)
socketConnection = Activator.CreateInstance<T>();
else
socketConnection = mServiceLocator.GetInstance<T>();
return socketConnection.AcceptSocketAsync(context, matches);
}
}
} | mit | C# |
de0e35bf95e5edd08c49eebfb2dcbaafce2de728 | Unify formatting | PioneerCode/pioneer-pagination,PioneerCode/pioneer-pagination,PioneerCode/pioneer-pagination | test/Pioneer.Pagination.Tests/ControlTextTests.cs | test/Pioneer.Pagination.Tests/ControlTextTests.cs | using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Pioneer.Pagination.Tests
{
public class ControlTextTests
{
private readonly PioneerPaginationTagHelper _sut = new PioneerPaginationTagHelper();
private readonly PaginatedMetaService _metaData = new PaginatedMetaService();
private readonly TagHelperContext _context = new TagHelperContext(
new TagHelperAttributeList(),
new Dictionary<object, object>(),
Guid.NewGuid().ToString("N"));
private readonly TagHelperOutput _output = new TagHelperOutput("ul",
new TagHelperAttributeList(),
(result, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(string.Empty);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
[Fact]
public void CanShowCustomPreviousPageText()
{
var previousPageText = "Backward";
_sut.Info = _metaData.GetMetaData(10, 10, 1);
_sut.PreviousPageText = previousPageText;
_sut.Process(_context, _output);
var markupResult = _output.Content.GetContent();
Assert.Contains(previousPageText, markupResult);
}
[Fact]
public void CanShowCustomNextPageText()
{
var nextPageText = "Forward";
_sut.Info = _metaData.GetMetaData(10, 1, 1);
_sut.NextPageText = nextPageText;
_sut.Process(_context, _output);
var markupResult = _output.Content.GetContent();
Assert.Contains(nextPageText, markupResult);
}
}
}
| using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
namespace Pioneer.Pagination.Tests
{
public class ControlTextTests
{
private readonly PioneerPaginationTagHelper _sut = new PioneerPaginationTagHelper();
private readonly PaginatedMetaService _metaData = new PaginatedMetaService();
TagHelperContext context = new TagHelperContext(
new TagHelperAttributeList(),
new Dictionary<object, object>(),
Guid.NewGuid().ToString("N"));
TagHelperOutput output = new TagHelperOutput("ul",
new TagHelperAttributeList(),
(result, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetHtmlContent(string.Empty);
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
[Fact]
public void CanShowCustomPreviousPageText()
{
var previousPageText = "Backward";
_sut.Info = _metaData.GetMetaData(10, 10, 1);
_sut.PreviousPageText = previousPageText;
_sut.Process(context, output);
var markupResult = output.Content.GetContent();
Assert.Contains(previousPageText, markupResult);
}
[Fact]
public void CanShowCustomNextPageText()
{
var nextPageText = "Forward";
_sut.Info = _metaData.GetMetaData(10, 1, 1);
_sut.NextPageText = nextPageText;
_sut.Process(context, output);
var markupResult = output.Content.GetContent();
Assert.Contains(nextPageText, markupResult);
}
}
}
| mit | C# |
ef97758c750133aa390cee32784aa1326c6819cc | Update needs to be mapped before create so that post overrides get a chance to work. Closes gh-3 | restful-routing/restful-routing,stevehodgkiss/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing,stevehodgkiss/restful-routing,restful-routing/restful-routing | src/RestfulRouting/Mappings/ResourceMapping.cs | src/RestfulRouting/Mappings/ResourceMapping.cs | using System.Linq;
using System.Web.Routing;
namespace RestfulRouting.Mappings
{
public class ResourceMapping<TController> : Mapping
{
private RouteNames _names;
private ResourceMapper _resourceMapper;
public ResourceMapping(RouteNames names, ResourceMapper resourceMapper)
{
_names = names;
ResourceName = ControllerName<TController>();
MappedName = Inflector.Net.Inflector.Singularize(ResourceName);
resourceMapper.ResourceName = ResourceName;
_resourceMapper = resourceMapper;
}
public override void AddRoutesTo(RouteCollection routeCollection)
{
_resourceMapper.SetResourceAs(MappedName ?? ResourceName);
if (IncludesAction(_names.ShowName))
routeCollection.Add(_resourceMapper.ShowRoute());
if (IncludesAction(_names.UpdateName))
routeCollection.Add(_resourceMapper.UpdateRoute());
if (IncludesAction(_names.CreateName))
routeCollection.Add(_resourceMapper.CreateRoute());
if (IncludesAction(_names.NewName))
routeCollection.Add(_resourceMapper.NewRoute());
if (IncludesAction(_names.EditName))
routeCollection.Add(_resourceMapper.EditRoute());
if (IncludesAction(_names.DestroyName))
routeCollection.Add(_resourceMapper.DestroyRoute());
foreach (var route in routeCollection)
{
ConfigureRoute(route as Route);
}
if (Members != null && Members.Any())
{
foreach (var member in Members)
{
routeCollection.Add(_resourceMapper.MemberRoute(member.Key, member.Value));
}
}
foreach (var mapping in Mappings)
{
mapping.AddRoutesTo(routeCollection);
}
}
}
}
| using System.Linq;
using System.Web.Routing;
namespace RestfulRouting.Mappings
{
public class ResourceMapping<TController> : Mapping
{
private RouteNames _names;
private ResourceMapper _resourceMapper;
public ResourceMapping(RouteNames names, ResourceMapper resourceMapper)
{
_names = names;
ResourceName = ControllerName<TController>();
MappedName = Inflector.Net.Inflector.Singularize(ResourceName);
resourceMapper.ResourceName = ResourceName;
_resourceMapper = resourceMapper;
}
public override void AddRoutesTo(RouteCollection routeCollection)
{
_resourceMapper.SetResourceAs(MappedName ?? ResourceName);
if (IncludesAction(_names.ShowName))
routeCollection.Add(_resourceMapper.ShowRoute());
if (IncludesAction(_names.CreateName))
routeCollection.Add(_resourceMapper.CreateRoute());
if (IncludesAction(_names.NewName))
routeCollection.Add(_resourceMapper.NewRoute());
if (IncludesAction(_names.EditName))
routeCollection.Add(_resourceMapper.EditRoute());
if (IncludesAction(_names.UpdateName))
routeCollection.Add(_resourceMapper.UpdateRoute());
if (IncludesAction(_names.DestroyName))
routeCollection.Add(_resourceMapper.DestroyRoute());
foreach (var route in routeCollection)
{
ConfigureRoute(route as Route);
}
if (Members != null && Members.Any())
{
foreach (var member in Members)
{
routeCollection.Add(_resourceMapper.MemberRoute(member.Key, member.Value));
}
}
foreach (var mapping in Mappings)
{
mapping.AddRoutesTo(routeCollection);
}
}
}
}
| mit | C# |
52afa42186494f14d0eeb633dac4673154085bee | update dispose pattern implementation | vladkol/MixedRealityToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,vladkol/MixedRealityToolkit-Unity,vladkol/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit/Services/BaseService.cs | Assets/MixedRealityToolkit/Services/BaseService.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.MixedReality.Toolkit.Core.Services
{
/// <summary>
/// The base service implements <see cref="Interfaces.IMixedRealityService"/> and provides default properties for all services.
/// </summary>
public abstract class BaseService : Interfaces.IMixedRealityService
{
#region IMixedRealityService Implementation
/// <inheritdoc />
public virtual string Name { get; protected set; }
/// <inheritdoc />
public virtual uint Priority { get; protected set; } = 5;
/// <inheritdoc />
public virtual void Initialize() { }
/// <inheritdoc />
public virtual void Reset() { }
/// <inheritdoc />
public virtual void Enable() { }
/// <inheritdoc />
public virtual void Update() { }
/// <inheritdoc />
public virtual void Disable() { }
/// <inheritdoc />
public virtual void Destroy() { }
#endregion IMixedRealityService Implementation
#region IDisposable Implementation
/// <summary>
/// Finalizer
/// </summary>
~BaseService()
{
Dispose();
}
/// <summary>
/// Cleanup resources used by this object.
/// </summary>
public void Dispose()
{
// Clean up our resources (managed and unmanaged resources)
Dispose(true);
// Suppress finalization as the the finalizer also calls our cleanup code.
GC.SuppressFinalize(this);
}
/// <summary>
/// Cleanup resources used by the object
/// </summary>
/// <param name="disposing">Are we fully disposing the object?
/// True will release all managed resources, unmanaged resources are always released.
/// </param>
protected virtual void Dispose(bool disposing) { }
#endregion IDisposable Implementation
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
namespace Microsoft.MixedReality.Toolkit.Core.Services
{
/// <summary>
/// The base service implements <see cref="Interfaces.IMixedRealityService"/> and provides default properties for all services.
/// </summary>
public abstract class BaseService : Interfaces.IMixedRealityService
{
#region IMixedRealityService Implementation
/// <inheritdoc />
public virtual string Name { get; protected set; }
/// <inheritdoc />
public virtual uint Priority { get; protected set; } = 5;
/// <inheritdoc />
public virtual void Initialize() { }
/// <inheritdoc />
public virtual void Reset() { }
/// <inheritdoc />
public virtual void Enable() { }
/// <inheritdoc />
public virtual void Update() { }
/// <inheritdoc />
public virtual void Disable() { }
/// <inheritdoc />
public virtual void Destroy() { }
#endregion IMixedRealityService Implementation
#region IDisposable Implementation
private bool disposed;
~BaseService()
{
OnDispose(true);
}
public void Dispose()
{
if (disposed) { return; }
disposed = true;
GC.SuppressFinalize(this);
OnDispose(false);
}
protected virtual void OnDispose(bool finalizing) { }
#endregion IDisposable Implementation
}
}
| mit | C# |
fe4d5c3d6f7abda2c37e56e39d846239a3ceb981 | remove an extra slash in front of //api | ronin1/urbanairsharp | src/UrbanAirSharp/Request/ChannelTagRequest.cs | src/UrbanAirSharp/Request/ChannelTagRequest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UrbanAirSharp.Dto;
using UrbanAirSharp.Request.Base;
using UrbanAirSharp.Response;
namespace UrbanAirSharp.Request
{
public class ChannelTagRequest : PostRequest<BaseResponse, TagOperation>
{
public ChannelTagRequest(TagOperation content, ServiceModelConfig cfg) : base(content, cfg)
{
if (content == null)
throw new ArgumentNullException("content");
RequestUrl = "api/channels/tags/";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UrbanAirSharp.Dto;
using UrbanAirSharp.Request.Base;
using UrbanAirSharp.Response;
namespace UrbanAirSharp.Request
{
public class ChannelTagRequest : PostRequest<BaseResponse, TagOperation>
{
public ChannelTagRequest(TagOperation content, ServiceModelConfig cfg) : base(content, cfg)
{
if (content == null)
throw new ArgumentNullException("content");
RequestUrl = "/api/channels/tags/";
}
}
}
| mit | C# |
59e39b7890d698b7b5d67c975dbc0e552d3b4b08 | Add shipment for physical goods | conekta/conekta-.net | src/conekta/conekta/Models/Details.cs | src/conekta/conekta/Models/Details.cs | using System;
using System.Collections.Generic;
namespace conekta
{
public class Details
{
public string name { get; set; }
public string phone { get; set; }
public string email { get; set; }
public Customer customer { get; set; }
public List<LineItem> line_items { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipment { get; set; }
}
}
| using System;
using System.Collections.Generic;
namespace conekta
{
public class Details
{
public string name { get; set; }
public string phone { get; set; }
public string email { get; set; }
public Customer customer { get; set; }
public List<LineItem> line_items { get; set; }
public BillingAddress billing_address { get; set; }
}
}
| mit | C# |
5fcf4b5c24e6fad424a2af777a96977c18770fbd | Remove set property from IAsset.Name | lucas-miranda/Raccoon | Raccoon/Core/IAsset.cs | Raccoon/Core/IAsset.cs | using System.IO;
namespace Raccoon {
public interface IAsset : System.IDisposable {
string Name { get; }
//string Filename { get; }
string[] Filenames { get; }
bool IsDisposed { get; }
void Reload();
void Reload(Stream stream);
}
}
| using System.IO;
namespace Raccoon {
public interface IAsset : System.IDisposable {
string Name { get; set; }
//string Filename { get; }
string[] Filenames { get; }
bool IsDisposed { get; }
void Reload();
void Reload(Stream stream);
}
}
| mit | C# |
61d4d437242614b9044ff046ea073ed13cf90d27 | Update MassRenameChildren.cs | UnityCommunity/UnityLibrary | Assets/Scripts/Editor/BatchTools/MassRenameChildren.cs | Assets/Scripts/Editor/BatchTools/MassRenameChildren.cs | // Renames child gameobjects in hierarchy (by replacting strings)
// open wizard from GameObject/MassRenameChildren menu item
using UnityEditor;
using UnityEngine;
namespace UnityLibrary
{
public class MassRenameChildren : ScriptableWizard
{
public string findString = "";
public string replaceWith = "";
// if set false: would replace "Hand" inside "RightHandRig", if set true: would replace "Hand" only if name starts with "Hand" like "HandRigWasd"
public bool onlyIfStartsWithFindString = true;
[MenuItem("GameObject/Mass Rename Children")]
static void CreateWizard()
{
DisplayWizard<MassRenameChildren>("MassRenamer", "Apply");
}
// user clicked create button
void OnWizardCreate()
{
if (Selection.activeTransform == null || findString == "")
{
Debug.Log(name + " Select Root Transform and set FindString first..");
return;
}
// get all children for the selection, NOTE: includeInactive is true, so disabled objects will get selected also
Transform[] allChildren = Selection.activeTransform.GetComponentsInChildren<Transform>(includeInactive: true);
foreach (Transform child in allChildren)
{
// skip self (selection root)
if (child != Selection.activeTransform)
{
string newName = child.name;
if (onlyIfStartsWithFindString == true)
{
// string starts with our search string
if (child.name.IndexOf(findString) == 0)
{
newName = child.name.Replace(findString, replaceWith);
}
} else // replace anywhere in target string
{
newName = child.name.Replace(findString, replaceWith);
}
// if would have any changes to name, print out and change
if (child.name != newName)
{
Debug.LogFormat("Before: {0} | After: {1}", child.name, newName);
child.name = newName;
}
}
}
}
}
}
| // Renames child gameobjects in hierarchy (by replacting strings)
// open wizard from GameObject/MassRenameChildren menu item
using UnityEditor;
using UnityEngine;
namespace UnityLibrary
{
public class MassRenameChildren : ScriptableWizard
{
public string findString = "";
public string replaceWith = "";
[MenuItem("GameObject/Mass Rename Children")]
static void CreateWizard()
{
DisplayWizard<MassRenameChildren>("MassRenamer", "Apply");
}
// user clicked create button
void OnWizardCreate()
{
if (Selection.activeTransform == null || findString == "")
{
Debug.Log(name + " Select Root Transform and set FindString first..");
return;
}
// get all children for the selection, NOTE: includeInactive is true, so disabled objects will get selected also
Transform[] allChildren = Selection.activeTransform.GetComponentsInChildren<Transform>(includeInactive: true);
foreach (Transform child in allChildren)
{
// skip self (selection root)
if (child != Selection.activeTransform)
{
var newName = child.name.Replace(findString, replaceWith);
Debug.LogFormat("Before: {0} | After: {1}", child.name, newName);
child.name = newName;
}
}
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.