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 |
|---|---|---|---|---|---|---|---|---|
29aa1b451d529069da831feca2d927268fcce6ed | Add version comment | martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site | src/LondonTravel.Site/Views/Shared/_Layout.cshtml | src/LondonTravel.Site/Views/Shared/_Layout.cshtml | @inject IConfiguration Config
@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html lang="en-gb">
<head prefix="og: http://ogp.me/ns#">
@{
string canonicalUri = Context.Request.Canonical();
string image = ViewBag.MetaImage ?? string.Empty;
if (!string.IsNullOrEmpty(image))
{
image = Url.Content(image)!;
}
var model = MetaModel.Create(
Options.Metadata,
canonicalUri: canonicalUri,
description: ViewBag.MetaDescription as string,
imageUri: image,
imageAltText: ViewBag.MetaImageAltText as string,
robots: ViewBag.MetaRobots as string,
title: ViewBag.Title as string);
}
@await Html.PartialAsync("_Meta", model)
@await Html.PartialAsync("_Links", Tuple.Create(canonicalUri, Options))
@await RenderSectionAsync("links", required: false)
@await RenderSectionAsync("meta", required: false)
@await Html.PartialAsync("_StylesHead")
@await RenderSectionAsync("stylesHead", required: false)
<script type="text/javascript" nonce="@Context.EnsureCspNonce()">
@Html.Raw(JavaScriptSnippet.ScriptBody)
</script>
<script type="text/javascript" nonce="@Context.EnsureCspNonce()">
if (self == top) {
document.documentElement.className = document.documentElement.className.replace(/\bjs-flash\b/, '');
}
else {
top.location = self.location;
}
</script>
</head>
<body>
@await Html.PartialAsync("_Navbar")
<main class="container body-content" data-authenticated="@((User?.Identity?.IsAuthenticated == true).ToString().ToLowerInvariant())" data-id="content">
@RenderBody()
@await Html.PartialAsync("_Footer", Options)
</main>
@await Html.PartialAsync("_StylesBody")
@await RenderSectionAsync("stylesBody", required: false)
@await Html.PartialAsync("_Scripts")
@await RenderSectionAsync("scripts", required: false)
</body>
<!--
Environment: @Config.AzureEnvironment()
Datacenter: @Config.AzureDatacenter()
Instance: @Environment.MachineName
Commit: @GitMetadata.Commit
Timestamp: @GitMetadata.Timestamp.ToString("u", CultureInfo.InvariantCulture)
Version: @System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription
-->
</html>
| @inject IConfiguration Config
@inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html lang="en-gb">
<head prefix="og: http://ogp.me/ns#">
@{
string canonicalUri = Context.Request.Canonical();
string image = ViewBag.MetaImage ?? string.Empty;
if (!string.IsNullOrEmpty(image))
{
image = Url.Content(image)!;
}
var model = MetaModel.Create(
Options.Metadata,
canonicalUri: canonicalUri,
description: ViewBag.MetaDescription as string,
imageUri: image,
imageAltText: ViewBag.MetaImageAltText as string,
robots: ViewBag.MetaRobots as string,
title: ViewBag.Title as string);
}
@await Html.PartialAsync("_Meta", model)
@await Html.PartialAsync("_Links", Tuple.Create(canonicalUri, Options))
@await RenderSectionAsync("links", required: false)
@await RenderSectionAsync("meta", required: false)
@await Html.PartialAsync("_StylesHead")
@await RenderSectionAsync("stylesHead", required: false)
<script type="text/javascript" nonce="@Context.EnsureCspNonce()">
@Html.Raw(JavaScriptSnippet.ScriptBody)
</script>
<script type="text/javascript" nonce="@Context.EnsureCspNonce()">
if (self == top) {
document.documentElement.className = document.documentElement.className.replace(/\bjs-flash\b/, '');
}
else {
top.location = self.location;
}
</script>
</head>
<body>
@await Html.PartialAsync("_Navbar")
<main class="container body-content" data-authenticated="@((User?.Identity?.IsAuthenticated == true).ToString().ToLowerInvariant())" data-id="content">
@RenderBody()
@await Html.PartialAsync("_Footer", Options)
</main>
@await Html.PartialAsync("_StylesBody")
@await RenderSectionAsync("stylesBody", required: false)
@await Html.PartialAsync("_Scripts")
@await RenderSectionAsync("scripts", required: false)
</body>
<!--
Environment: @Config.AzureEnvironment()
Datacenter: @Config.AzureDatacenter()
Instance: @Environment.MachineName
Commit: @GitMetadata.Commit
Timestamp: @GitMetadata.Timestamp.ToString("u", CultureInfo.InvariantCulture)
-->
</html>
| apache-2.0 | C# |
9c9a961c9b386c08bae9fcc7d80cae8d2d7f9bf1 | Patch delegates.xml for non Windows platform. | dlemstra/Magick.NET,dlemstra/Magick.NET | src/Magick.NET/Configuration/ConfigurationFile.cs | src/Magick.NET/Configuration/ConfigurationFile.cs | // Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using System.IO;
namespace ImageMagick.Configuration
{
internal sealed class ConfigurationFile : IConfigurationFile
{
public ConfigurationFile(string fileName)
{
FileName = fileName;
Data = LoadData();
}
public string FileName { get; }
public string Data { get; set; }
private string LoadData()
{
using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName))
{
using (var reader = new StreamReader(stream))
{
var data = reader.ReadToEnd();
data = UpdateDelegatesXml(data);
return data;
}
}
}
private string UpdateDelegatesXml(string data)
{
if (OperatingSystem.IsWindows || FileName != "delegates.xml")
return data;
return data.Replace("@PSDelegate@", "gs");
}
}
} | // Copyright 2013-2021 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
using System.IO;
namespace ImageMagick.Configuration
{
internal sealed class ConfigurationFile : IConfigurationFile
{
public ConfigurationFile(string fileName)
{
FileName = fileName;
Data = LoadData();
}
public string FileName { get; }
public string Data { get; set; }
private string LoadData()
{
using (Stream stream = TypeHelper.GetManifestResourceStream(typeof(ConfigurationFile), "ImageMagick.Resources.Xml", FileName))
{
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
}
} | apache-2.0 | C# |
bfca2179a2d88f686ceaea964e9d912b99cee3ed | fix nullable definition | acple/ParsecSharp | ParsecSharp/Data/TokenizedStream.cs | ParsecSharp/Data/TokenizedStream.cs | using System;
using ParsecSharp.Internal;
namespace ParsecSharp
{
public sealed class TokenizedStream<TInput, TToken> : IParsecStateStream<TToken>
{
private readonly IDisposable source;
private readonly LinearPosition _position;
private readonly Lazy<IParsecStateStream<TToken>> _next;
public TToken Current { get; }
public bool HasValue { get; }
public IPosition Position => this._position;
public IParsecStateStream<TToken> Next => this._next.Value;
public TokenizedStream(IParsecStateStream<TInput> source, Parser<TInput, TToken> parser) : this(source, parser, LinearPosition.Initial)
{ }
private TokenizedStream(IParsecStateStream<TInput> source, Parser<TInput, TToken> parser, LinearPosition position)
{
this.source = source;
this._position = position;
var (result, rest) = parser.ParsePartially(source);
this.HasValue = result.CaseOf(_ => false, _ => true);
this.Current = (this.HasValue) ? result.Value : default!;
this._next = new Lazy<IParsecStateStream<TToken>>(() => new TokenizedStream<TInput, TToken>(rest, parser, position.Next()), false);
}
public void Dispose()
=> this.source.Dispose();
public bool Equals(IParsecState<TToken> other)
=> ReferenceEquals(this, other);
public sealed override string ToString()
=> (this.HasValue)
? this.Current?.ToString() ?? string.Empty
: "<EndOfStream>";
}
}
| using System;
using ParsecSharp.Internal;
namespace ParsecSharp
{
public sealed class TokenizedStream<TInput, TToken> : IParsecStateStream<TToken>
{
private readonly IDisposable source;
private readonly LinearPosition _position;
private readonly Lazy<IParsecStateStream<TToken>> _next;
public TToken Current { get; }
public bool HasValue { get; }
public IPosition Position => this._position;
public IParsecStateStream<TToken> Next => this._next.Value;
public TokenizedStream(IParsecStateStream<TInput> source, Parser<TInput, TToken> parser) : this(source, parser, LinearPosition.Initial)
{ }
private TokenizedStream(IParsecStateStream<TInput> source, Parser<TInput, TToken> parser, LinearPosition position)
{
this.source = source;
this._position = position;
var (result, rest) = parser.ParsePartially(source);
this.HasValue = result.CaseOf(_ => false, _ => true);
this.Current = (this.HasValue) ? result.Value : default;
this._next = new Lazy<IParsecStateStream<TToken>>(() => new TokenizedStream<TInput, TToken>(rest, parser, position.Next()), false);
}
public void Dispose()
=> this.source.Dispose();
public bool Equals(IParsecState<TToken> other)
=> ReferenceEquals(this, other);
public sealed override string ToString()
=> (this.HasValue)
? this.Current?.ToString() ?? string.Empty
: "<EndOfStream>";
}
}
| mit | C# |
7d02004ca68c233ff08f7651fe5e033f06562c1e | Add a token fuckup test | tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server | tests/Tgstation.Server.Tests/IntegrationTest.cs | tests/Tgstation.Server.Tests/IntegrationTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Client;
using Tgstation.Server.Host;
namespace Tgstation.Server.Tests
{
[TestClass]
public sealed class IntegrationTest
{
readonly IServerClientFactory clientFactory = new ServerClientFactory(new ProductHeaderValue(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString()));
[TestMethod]
public async Task FullMonty()
{
using (var server = new TestingServer())
using (var serverCts = new CancellationTokenSource())
{
var cancellationToken = serverCts.Token;
var serverTask = server.RunAsync(cancellationToken);
try
{
IServerClient adminClient;
var giveUpAt = DateTimeOffset.Now.AddSeconds(60);
do
{
try
{
adminClient = await clientFactory.CreateServerClient(server.Url, User.AdminName, User.DefaultAdminPassword).ConfigureAwait(false);
break;
}
catch (ServiceUnavailableException)
{
//migrating, to be expected
if (DateTimeOffset.Now > giveUpAt)
throw;
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
} while (true);
using (adminClient)
{
var serverInfo = await adminClient.Version(default).ConfigureAwait(false);
Assert.AreEqual(ApiHeaders.Version, serverInfo.ApiVersion);
Assert.AreEqual(typeof(IServer).Assembly.GetName().Version, serverInfo.Version);
//check that modifying the token even slightly fucks up the auth
var newToken = new Token
{
ExpiresAt = adminClient.Token.ExpiresAt,
Bearer = adminClient.Token.Bearer + '0'
};
var badClient = clientFactory.CreateServerClient(server.Url, newToken);
await Assert.ThrowsExceptionAsync<UnauthorizedException>(() => badClient.Version(cancellationToken)).ConfigureAwait(false);
await new AdministrationTest(adminClient.Administration).Run(cancellationToken).ConfigureAwait(false);
await new InstanceManagerTest(adminClient.Instances, server.Directory).Run(cancellationToken).ConfigureAwait(false);
}
}
finally
{
serverCts.Cancel();
try
{
await serverTask.ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
}
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Client;
using Tgstation.Server.Host;
namespace Tgstation.Server.Tests
{
[TestClass]
public sealed class IntegrationTest
{
readonly IServerClientFactory clientFactory = new ServerClientFactory(new ProductHeaderValue(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString()));
[TestMethod]
public async Task FullMonty()
{
using (var server = new TestingServer())
using (var serverCts = new CancellationTokenSource())
{
var cancellationToken = serverCts.Token;
var serverTask = server.RunAsync(cancellationToken);
try
{
IServerClient adminClient;
var giveUpAt = DateTimeOffset.Now.AddSeconds(60);
do
{
try
{
adminClient = await clientFactory.CreateServerClient(server.Url, User.AdminName, User.DefaultAdminPassword).ConfigureAwait(false);
break;
}
catch (ServiceUnavailableException)
{
//migrating, to be expected
if (DateTimeOffset.Now > giveUpAt)
throw;
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
} while (true);
using (adminClient)
{
var serverInfo = await adminClient.Version(default).ConfigureAwait(false);
Assert.AreEqual(ApiHeaders.Version, serverInfo.ApiVersion);
Assert.AreEqual(typeof(IServer).Assembly.GetName().Version, serverInfo.Version);
await new AdministrationTest(adminClient.Administration).Run(cancellationToken).ConfigureAwait(false);
await new InstanceManagerTest(adminClient.Instances, server.Directory).Run(cancellationToken).ConfigureAwait(false);
}
}
finally
{
serverCts.Cancel();
try
{
await serverTask.ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
}
}
}
}
| agpl-3.0 | C# |
b19aaf7a39a2fb72c640c4fe755251936b14567d | Remove unused usings | nessos/Eff | tests/Eff.Benchmarks/Benchmark.cs | tests/Eff.Benchmarks/Benchmark.cs | #pragma warning disable 1998
using BenchmarkDotNet.Attributes;
using Nessos.Effects.Handlers;
using System.Linq;
using System.Threading.Tasks;
namespace Nessos.Effects.Benchmarks
{
[MemoryDiagnoser]
public class Benchmark
{
private int[] _data = null!;
private IEffectHandler _handler = null!;
[GlobalSetup]
public void Setup()
{
const int offset = 50_000; // prevent task caching from kicking in
_data = Enumerable.Range(0, 100).Select(x => x + offset).ToArray();
_handler = new DefaultEffectHandler();
}
[Benchmark(Description = "Task Builder", Baseline = true)]
public Task TaskBuilder() => TaskFlow.SumOfOddSquares(_data);
[Benchmark(Description = "Eff Builder")]
public Task EffBuilder() => EffFlow.SumOfOddSquares(_data).Run(_handler);
private static class TaskFlow
{
public static async Task<int> SumOfOddSquares(int[] inputs)
{
int sum = 0;
foreach(var i in inputs)
if(i % 2 == 1) sum += await Square(i);
return sum;
static async Task<int> Square(int x) => await Echo(x) * await Echo(x);
static async Task<T> Echo<T>(T x) => x;
}
}
private static class EffFlow
{
public static async Eff<int> SumOfOddSquares(int[] inputs)
{
int sum = 0;
foreach (var i in inputs)
if (i % 2 == 1) sum += await Square(i);
return sum;
static async Eff<int> Square(int x) => await Echo(x) * await Echo(x);
static async Eff<T> Echo<T>(T x) => x;
}
}
}
}
| #pragma warning disable 1998
using System;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Nessos.Effects.Handlers;
namespace Nessos.Effects.Benchmarks
{
[MemoryDiagnoser]
public class Benchmark
{
private int[] _data = null!;
private IEffectHandler _handler = null!;
[GlobalSetup]
public void Setup()
{
const int offset = 50_000; // prevent task caching from kicking in
_data = Enumerable.Range(0, 100).Select(x => x + offset).ToArray();
_handler = new DefaultEffectHandler();
}
[Benchmark(Description = "Task Builder", Baseline = true)]
public Task TaskBuilder() => TaskFlow.SumOfOddSquares(_data);
[Benchmark(Description = "Eff Builder")]
public Task EffBuilder() => EffFlow.SumOfOddSquares(_data).Run(_handler);
private static class TaskFlow
{
public static async Task<int> SumOfOddSquares(int[] inputs)
{
int sum = 0;
foreach(var i in inputs)
if(i % 2 == 1) sum += await Square(i);
return sum;
static async Task<int> Square(int x) => await Echo(x) * await Echo(x);
static async Task<T> Echo<T>(T x) => x;
}
}
private static class EffFlow
{
public static async Eff<int> SumOfOddSquares(int[] inputs)
{
int sum = 0;
foreach (var i in inputs)
if (i % 2 == 1) sum += await Square(i);
return sum;
static async Eff<int> Square(int x) => await Echo(x) * await Echo(x);
static async Eff<T> Echo<T>(T x) => x;
}
}
}
}
| mit | C# |
a2a297d2f59052429c653c16d33bc45f291cc15b | Build test. | lelong37/urf,lelong37/urf,lelong37/urf | main/Sample/Northwind.Web/App_Start/UnityConfig.cs | main/Sample/Northwind.Web/App_Start/UnityConfig.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using CommonServiceLocator;
using Microsoft.Practices.Unity;
using Northwind.Entities.Models;
using Northwind.Service;
using Repository.Pattern.DataContext;
using Repository.Pattern.Ef6;
using Repository.Pattern.Repositories;
using Repository.Pattern.UnitOfWork;
namespace Northwind.Web
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
container
// Register DbContext instead of IDataDataContext, which is now obsolete.
//.RegisterType<IDataContextAsync, NorthwindContext>(new PerRequestLifetimeManager())
.RegisterType<DbContext, NorthwindContext>(new PerRequestLifetimeManager())
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<Customer>, Repository<Customer>>()
.RegisterType<IRepositoryAsync<Product>, Repository<Product>>()
.RegisterType<IProductService, ProductService>()
.RegisterType<ICustomerService, CustomerService>()
.RegisterType<INorthwindStoredProcedures, NorthwindContext>(new PerRequestLifetimeManager())
.RegisterType<IStoredProcedureService, StoredProcedureService>();
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocatorAdapter(container));
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using CommonServiceLocator;
using Microsoft.Practices.Unity;
using Northwind.Entities.Models;
using Northwind.Service;
using Repository.Pattern.DataContext;
using Repository.Pattern.Ef6;
using Repository.Pattern.Repositories;
using Repository.Pattern.UnitOfWork;
namespace Northwind.Web
{
/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
container
// Register DbContext instead of IDataDataContext, which is now obsolete.
//.RegisterType<IDataContextAsync, NorthwindContext>(new PerRequestLifetimeManager())
.RegisterType<DbContext, NorthwindContext>(new PerRequestLifetimeManager())
.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new PerRequestLifetimeManager())
.RegisterType<IRepositoryAsync<Customer>, Repository<Customer>>()
.RegisterType<IRepositoryAsync<Product>, Repository<Product>>()
.RegisterType<IProductService, ProductService>()
.RegisterType<ICustomerService, CustomerService>()
.RegisterType<INorthwindStoredProcedures, NorthwindContext>(new PerRequestLifetimeManager())
.RegisterType<IStoredProcedureService, StoredProcedureService>();
ServiceLocator.SetLocatorProvider(() => new UnityServiceLocatorAdapter(container));
}
}
}
| mit | C# |
2cb3e59c8bc7e67edef4dfe7f9c7dfc01db386a7 | Make MenuItem support nested MenuItems. | DrabWeb/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,default0/osu-framework,ppy/osu-framework,default0/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework | osu.Framework/Graphics/UserInterface/MenuItem.cs | osu.Framework/Graphics/UserInterface/MenuItem.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Configuration;
namespace osu.Framework.Graphics.UserInterface
{
public class MenuItem
{
/// <summary>
/// The text which this <see cref="MenuItem"/> displays.
/// </summary>
public readonly Bindable<string> Text = new Bindable<string>();
/// <summary>
/// The <see cref="Action"/> that is performed when this <see cref="MenuItem"/> is clicked.
/// </summary>
public readonly Bindable<Action> Action = new Bindable<Action>();
/// <summary>
/// A list of items which are to be displayed in a sub-menu originating from this <see cref="MenuItem"/>.
/// </summary>
public IReadOnlyList<MenuItem> Items;
/// <summary>
/// Creates a new <see cref="MenuItem"/>.
/// </summary>
/// <param name="text">The text to display.</param>
public MenuItem(string text)
{
Text.Value = text;
}
/// <summary>
/// Creates a new <see cref="MenuItem"/>.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="action">The <see cref="Action"/> to perform when clicked.</param>
public MenuItem(string text, Action action)
: this(text)
{
Action.Value = action;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using osu.Framework.Configuration;
namespace osu.Framework.Graphics.UserInterface
{
public class MenuItem
{
/// <summary>
/// The text which this <see cref="MenuItem"/> displays.
/// </summary>
public readonly Bindable<string> Text = new Bindable<string>();
/// <summary>
/// The <see cref="Action"/> that is performed when this <see cref="MenuItem"/> is clicked.
/// </summary>
public readonly Bindable<Action> Action = new Bindable<Action>();
/// <summary>
/// Creates a new <see cref="MenuItem"/>.
/// </summary>
/// <param name="text">The text to display.</param>
public MenuItem(string text)
{
Text.Value = text;
}
/// <summary>
/// Creates a new <see cref="MenuItem"/>.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="action">The <see cref="Action"/> to perform when clicked.</param>
public MenuItem(string text, Action action)
: this(text)
{
Action.Value = action;
}
}
}
| mit | C# |
a2d3a3bb300ba78fcbd6214ede543da5dfc55d80 | create console on main scene | reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap | unity/demo/Assets/Scripts/MainSceneBehaviour.cs | unity/demo/Assets/Scripts/MainSceneBehaviour.cs | using UnityEngine;
using UtyMap.Unity.Infrastructure.Config;
namespace Assets.Scripts
{
internal class MainSceneBehaviour : MonoBehaviour
{
private void Awake()
{
ApplicationManager.Instance.InitializeFramework(ConfigBuilder.GetDefault(), _ => { });
ApplicationManager.Instance.CreateDebugConsole(false);
}
}
} | using UnityEngine;
using UtyMap.Unity.Infrastructure.Config;
namespace Assets.Scripts
{
internal class MainSceneBehaviour : MonoBehaviour
{
private void Awake()
{
ApplicationManager.Instance.InitializeFramework(ConfigBuilder.GetDefault(), _ => { });
}
}
} | apache-2.0 | C# |
a5b9a971ac70adfaa31616f216820da74140636a | Revert HttpTaskAsyncHandler.cs to previous behavior of returning null to ASP.NET if ProcessRequestAsync returns null. | shiftkey/SignalR,shiftkey/SignalR | SignalR/Web/HttpTaskAsyncHandler.cs | SignalR/Web/HttpTaskAsyncHandler.cs | using System;
using System.Threading.Tasks;
using System.Web;
namespace SignalR.Web
{
public abstract class HttpTaskAsyncHandler : IHttpAsyncHandler
{
public virtual bool IsReusable
{
get { return false; }
}
public virtual void ProcessRequest(HttpContext context)
{
throw new NotSupportedException();
}
public abstract Task ProcessRequestAsync(HttpContextBase context);
IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
Task task = ProcessRequestAsync(new HttpContextWrapper(context));
var retVal = new TaskWrapperAsyncResult(task, extraData);
if (task == null)
{
// No task, so just let ASP.NET deal with it
return null;
}
if (cb != null)
{
// The callback needs the same argument that the Begin method returns, which is our special wrapper, not the original Task.
task.ContinueWith(_ => cb(retVal));
}
return retVal;
}
void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
// The End* method doesn't actually perform any actual work, but we do need to maintain two invariants:
// 1. Make sure the underlying Task actually *is* complete.
// 2. If the Task encountered an exception, observe it here.
// (The Wait method handles both of those.)
var castResult = (TaskWrapperAsyncResult)result;
castResult.Task.Wait();
}
}
} | using System;
using System.Threading.Tasks;
using System.Web;
namespace SignalR.Web
{
public abstract class HttpTaskAsyncHandler : IHttpAsyncHandler
{
public virtual bool IsReusable
{
get { return false; }
}
public virtual void ProcessRequest(HttpContext context)
{
throw new NotSupportedException();
}
public abstract Task ProcessRequestAsync(HttpContextBase context);
IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
Task task = ProcessRequestAsync(new HttpContextWrapper(context));
var retVal = new TaskWrapperAsyncResult(task, extraData);
if (task == null)
{
// No task, so just call the AsyncCallback and end the request
cb(retVal);
return retVal;
}
if (cb != null)
{
// The callback needs the same argument that the Begin method returns, which is our special wrapper, not the original Task.
task.ContinueWith(_ => cb(retVal));
}
return retVal;
}
void IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
{
if (result == null)
{
throw new ArgumentNullException("result");
}
// The End* method doesn't actually perform any actual work, but we do need to maintain two invariants:
// 1. Make sure the underlying Task actually *is* complete.
// 2. If the Task encountered an exception, observe it here.
// (The Wait method handles both of those.)
var castResult = (TaskWrapperAsyncResult)result;
castResult.Task.Wait();
}
}
} | mit | C# |
9848f6850cee47686f7bae3013ccbc8c0795b04a | Test coverage for runtime-type mapping within a collection | agileobjects/AgileMapper | AgileMapper.UnitTests/WhenMappingDerivedTypes.cs | AgileMapper.UnitTests/WhenMappingDerivedTypes.cs | namespace AgileObjects.AgileMapper.UnitTests
{
using System;
using System.Collections.Generic;
using System.Linq;
using Shouldly;
using TestClasses;
using Xunit;
public class WhenMappingDerivedTypes
{
[Fact]
public void ShouldMapARootComplexTypeFromItsAssignedType()
{
object source = new Product { Price = 100.00 };
var result = Mapper.Map(source).ToNew<Product>();
result.Price.ShouldBe(100.00);
}
[Fact]
public void ShouldMapARootComplexTypeEnumerableFromItsAssignedType()
{
object source = new[] { new Product { Price = 10.01 } };
var result = Mapper.Map(source).ToNew<IEnumerable<Product>>();
result.First().Price.ShouldBe(10.01);
}
[Fact]
public void ShouldMapARootComplexTypeEnumerableElementFromItsAssignedType()
{
var source = new object[] { new Product { Price = 9.99 } };
var result = Mapper.Map(source).ToNew<IEnumerable<Product>>();
result.First().Price.ShouldBe(9.99);
}
[Fact]
public void ShouldMapAComplexTypeMemberFromItsAssignedType()
{
var source = new PublicProperty<object>
{
Value = new { Name = "Frank", Address = (object)new Address { Line1 = "Here!" } }
};
var result = Mapper.Map(source).ToNew<PublicProperty<PersonViewModel>>();
result.Value.ShouldNotBeNull();
result.Value.Name.ShouldBe("Frank");
result.Value.AddressLine1.ShouldBe("Here!");
}
[Fact]
public void ShouldMapAComplexTypeMemberInACollectionFromItsAssignedType()
{
var sourceObjectId = Guid.NewGuid();
var source = new object[]
{
new { Name = "Bob", Address = new { Line1 = "There!" } },
new { Id = sourceObjectId.ToString(), Address = (object)new Address { Line1 = "Somewhere!" } }
};
var result = Mapper.Map(source).ToNew<ICollection<PersonViewModel>>();
result.ShouldNotBeNull();
result.Count.ShouldBe(2);
result.First().Id.ShouldBeDefault();
result.First().Name.ShouldBe("Bob");
result.First().AddressLine1.ShouldBe("There!");
result.Second().Id.ShouldBe(sourceObjectId);
result.Second().Name.ShouldBeNull();
result.Second().AddressLine1.ShouldBe("Somewhere!");
}
}
}
| namespace AgileObjects.AgileMapper.UnitTests
{
using System.Collections.Generic;
using System.Linq;
using Shouldly;
using TestClasses;
using Xunit;
public class WhenMappingDerivedTypes
{
[Fact]
public void ShouldMapARootComplexTypeFromItsAssignedType()
{
object source = new Product { Price = 100.00 };
var result = Mapper.Map(source).ToNew<Product>();
result.Price.ShouldBe(100.00);
}
[Fact]
public void ShouldMapARootComplexTypeEnumerableFromItsAssignedType()
{
object source = new[] { new Product { Price = 10.01 } };
var result = Mapper.Map(source).ToNew<IEnumerable<Product>>();
result.First().Price.ShouldBe(10.01);
}
[Fact]
public void ShouldMapARootComplexTypeEnumerableElementFromItsAssignedType()
{
var source = new object[] { new Product { Price = 9.99 } };
var result = Mapper.Map(source).ToNew<IEnumerable<Product>>();
result.First().Price.ShouldBe(9.99);
}
[Fact]
public void ShouldMapAComplexTypeMemberFromItsAssignedType()
{
var source = new PublicProperty<object>
{
Value = new { Name = "Frank", Address = (object)new Address { Line1 = "Here!" } }
};
var result = Mapper.Map(source).ToNew<PublicProperty<PersonViewModel>>();
result.Value.ShouldNotBeNull();
result.Value.Name.ShouldBe("Frank");
result.Value.AddressLine1.ShouldBe("Here!");
}
}
}
| mit | C# |
3d7ef014fa86ac601a4d3e2e315cf8000de99bbd | Add text/html as first content type, should possible detect IE.. | ryansroberts/Snooze,ryansroberts/Snooze | Source/Snooze/ResourceFormatters.cs | Source/Snooze/ResourceFormatters.cs | #region
using System.Collections.Generic;
#endregion
namespace Snooze
{
public static class ResourceFormatters
{
static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>();
static ResourceFormatters()
{
// The order of formatters matters.
// Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..."
// But we don't want to use the XML formatter by default
// - which would happen since "text/xml" appears first in the list.
// So we add an explicitly typed ViewFormatter first.
_formatters.Add(new ViewFormatter("text/html"));
_formatters.Add(new ViewFormatter("application/xhtml+xml"));
_formatters.Add(new ViewFormatter("*/*")); // similar reason for this.
_formatters.Add(new JsonFormatter());
_formatters.Add(new XmlFormatter());
_formatters.Add(new ViewFormatter());
_formatters.Add(new StringFormatter());
_formatters.Add(new ByteArrayFormatter());
}
public static IList<IResourceFormatter> Formatters
{
get { return _formatters; }
}
}
} | #region
using System.Collections.Generic;
#endregion
namespace Snooze
{
public static class ResourceFormatters
{
static readonly IList<IResourceFormatter> _formatters = new List<IResourceFormatter>();
static ResourceFormatters()
{
// The order of formatters matters.
// Browsers like Chrome will ask for "text/xml, application/xhtml+xml, ..."
// But we don't want to use the XML formatter by default
// - which would happen since "text/xml" appears first in the list.
// So we add an explicitly typed ViewFormatter first.
_formatters.Add(new ViewFormatter("application/xhtml+xml"));
_formatters.Add(new ViewFormatter("*/*")); // similar reason for this.
_formatters.Add(new JsonFormatter());
_formatters.Add(new XmlFormatter());
_formatters.Add(new ViewFormatter());
_formatters.Add(new StringFormatter());
_formatters.Add(new ByteArrayFormatter());
}
public static IList<IResourceFormatter> Formatters
{
get { return _formatters; }
}
}
} | bsd-3-clause | C# |
2b09cca989d548fa682bcdf325d5d61192cd0ee8 | fix the ByRowIdentifier serialization name, closes #5 | CityofSantaMonica/SODA.NET,chrismetcalf/SODA.NET | SODA/SodaResult.cs | SODA/SodaResult.cs | using System.Runtime.Serialization;
namespace SODA
{
/// <summary>
/// A class representing the response from a SODA call.
/// </summary>
[DataContract]
public class SodaResult
{
/// <summary>
/// Gets or sets the number of modifications made based on the row identifier.
/// </summary>
[DataMember(Name = "By RowIdentifier")]
public int ByRowIdentifier { get; set; }
/// <summary>
/// Gets or sets the number of rows updated.
/// </summary>
[DataMember(Name = "Rows Updated")]
public int RowsUpdated { get; set; }
/// <summary>
/// Gets or sets the number of rows deleted.
/// </summary>
[DataMember(Name = "Rows Deleted")]
public int RowsDeleted { get; set; }
/// <summary>
/// Gets or sets the number of rows created.
/// </summary>
[DataMember(Name = "Rows Created")]
public int RowsCreated { get; set; }
/// <summary>
/// Gets or sets the number of errors.
/// </summary>
[DataMember(Name = "Errors")]
public int Errors { get; set; }
/// <summary>
/// Gets or sets the number of modifications made based on the internal Socrata identifier.
/// </summary>
[DataMember(Name = "By SID")]
public int BySID { get; set; }
/// <summary>
/// Gets or sets the explanatory text about this result.
/// </summary>
[DataMember(Name = "message")]
public string Message { get; set; }
/// <summary>
/// Gets or sets a flag indicating if one or more errors occured.
/// </summary>
[DataMember(Name = "error")]
public bool IsError { get; set; }
/// <summary>
/// Gets or sets data about any errors that occured.
/// </summary>
[DataMember(Name = "code")]
public string ErrorCode { get; set; }
/// <summary>
/// Gets or sets any additional data associated with this result.
/// </summary>
[DataMember(Name = "data")]
public dynamic Data { get; set; }
}
}
| using System.Runtime.Serialization;
namespace SODA
{
/// <summary>
/// A class representing the response from a SODA call.
/// </summary>
[DataContract]
public class SodaResult
{
/// <summary>
/// Gets or sets the number of modifications made based on the row identifier.
/// </summary>
[DataMember(Name = "By Row Identifier")]
public int ByRowIdentifier { get; set; }
/// <summary>
/// Gets or sets the number of rows updated.
/// </summary>
[DataMember(Name = "Rows Updated")]
public int RowsUpdated { get; set; }
/// <summary>
/// Gets or sets the number of rows deleted.
/// </summary>
[DataMember(Name = "Rows Deleted")]
public int RowsDeleted { get; set; }
/// <summary>
/// Gets or sets the number of rows created.
/// </summary>
[DataMember(Name = "Rows Created")]
public int RowsCreated { get; set; }
/// <summary>
/// Gets or sets the number of errors.
/// </summary>
[DataMember(Name = "Errors")]
public int Errors { get; set; }
/// <summary>
/// Gets or sets the number of modifications made based on the internal Socrata identifier.
/// </summary>
[DataMember(Name = "By SID")]
public int BySID { get; set; }
/// <summary>
/// Gets or sets the explanatory text about this result.
/// </summary>
[DataMember(Name = "message")]
public string Message { get; set; }
/// <summary>
/// Gets or sets a flag indicating if one or more errors occured.
/// </summary>
[DataMember(Name = "error")]
public bool IsError { get; set; }
/// <summary>
/// Gets or sets data about any errors that occured.
/// </summary>
[DataMember(Name = "code")]
public string ErrorCode { get; set; }
/// <summary>
/// Gets or sets any additional data associated with this result.
/// </summary>
[DataMember(Name = "data")]
public dynamic Data { get; set; }
}
}
| mit | C# |
8ee406b5cce5b3df5923db75811b8e95e044705b | Fix to file compiled | rootdevelop/semm,rootdevelop/semm | SEMMSpaceGame/SpaceGame.Common/InitialGameLayer.cs | SEMMSpaceGame/SpaceGame.Common/InitialGameLayer.cs | using System;
using CocosSharp;
using Microsoft.Xna.Framework.Graphics;
namespace SpaceGame.Common
{
public class InitialGameLayer : CCLayerColor
{
CCLabel helloLabel;
CCTileMap tileMap;
CCSprite playerSprite;
public InitialGameLayer () : base (CCColor4B.Blue)
{
Schedule (RunGameLogic);
}
void RunGameLogic(float frameTimeInSeconds)
{
// Game loop
}
protected override void AddedToScene ()
{
base.AddedToScene ();
tileMap = new CCTileMap ("tilemaps/Level0.tmx");
this.AddChild (tileMap);
playerSprite = new CCSprite ("Images/monkey.png");
playerSprite.PositionX = ContentSize.Width/2;
playerSprite.PositionY = ContentSize.Height/2;
AddChild (playerSprite);
/*
helloLabel = new CCLabel("Hello Space Apps!", "Arial", 30, CCLabelFormat.SystemFont);
helloLabel.PositionX = ContentSize.Height/2;
helloLabel.PositionY = ContentSize.Width/2;
helloLabel.Color = CCColor3B.White;
AddChild (helloLabel);
*/
// Use the bounds to layout the positioning of our drawable assets
CCRect bounds = VisibleBoundsWorldspace;
}
}
} | using System;
using CocosSharp;
using Microsoft.Xna.Framework.Graphics;
namespace SpaceGame.Common
{
public class InitialGameLayer : CCLayerColor
{
CCLabel helloLabel;
CCTileMap tileMap;
CCSprite playerSprite;
public InitialGameLayer () : base (CCColor4B.Blue)
{
Schedule (RunGameLogic);
}
void RunGameLogic(float frameTimeInSeconds)
{
// Game loop
}
protected override void AddedToScene ()
{
base.AddedToScene ();
tileMap = new CCTileMap ("tilemaps/Background_Level_0.tmx");
this.AddChild (tileMap);
playerSprite = new CCSprite ("Images/monkey.png");
playerSprite.PositionX = ContentSize.Width/2;
playerSprite.PositionY = ContentSize.Height/2;
AddChild (playerSprite);
/*
helloLabel = new CCLabel("Hello Space Apps!", "Arial", 30, CCLabelFormat.SystemFont);
helloLabel.PositionX = ContentSize.Height/2;
helloLabel.PositionY = ContentSize.Width/2;
helloLabel.Color = CCColor3B.White;
AddChild (helloLabel);
*/
// Use the bounds to layout the positioning of our drawable assets
CCRect bounds = VisibleBoundsWorldspace;
}
}
} | mit | C# |
b7aad8b5435d60e4c9653ed4790579ddf56768a0 | increase ServiceContract version number | gigya/microdot | Gigya.ServiceContract/Properties/AssemblyInfo.cs | Gigya.ServiceContract/Properties/AssemblyInfo.cs | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
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("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyInformationalVersion("2.6.2")]// if pre-release should be in the format of "2.4.11-pre01".
[assembly: AssemblyVersion("2.6.2")]
[assembly: AssemblyFileVersion("2.6.2")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo("Gigya.Microdot.SharedLogic")] | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
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("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyInformationalVersion("2.6.1")]// if pre-release should be in the format of "2.4.11-pre01".
[assembly: AssemblyVersion("2.6.1")]
[assembly: AssemblyFileVersion("2.6.1")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo("Gigya.Microdot.SharedLogic")] | apache-2.0 | C# |
2e03798dba78c2720310853c081deef04fe5d984 | fix version no | gigya/microdot | Gigya.ServiceContract/Properties/AssemblyInfo.cs | Gigya.ServiceContract/Properties/AssemblyInfo.cs | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
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("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyInformationalVersion("2.4.11-pre01")]// if pre-release should be in the format of "2.4.11-pre01".
[assembly: AssemblyVersion("2.4.11-pre01")]
[assembly: AssemblyFileVersion("2.4.11-pre01")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)] | #region Copyright
// Copyright 2017 Gigya Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
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("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyInformationalVersion("2.4.11")]// if pre-release should be in the format of "2.4.11-pre01".
[assembly: AssemblyVersion("2.4.11")]
[assembly: AssemblyFileVersion("2.4.11")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)] | apache-2.0 | C# |
6296d21ea1cf5a7b1026be44ce9207f76ad07b47 | Define object scopes by blocks | TheBerkin/Rant | Rant/Engine/Syntax/RABlock.cs | Rant/Engine/Syntax/RABlock.cs | using Rant.Stringes;
using System;
using System.Collections.Generic;
using System.Linq;
using Rant.Engine.Constructs;
namespace Rant.Engine.Syntax
{
/// <summary>
/// Represents a block construct, which provides multiple options to the interpreter for the next sequence, one of which is chosen.
/// </summary>
internal class RABlock : RantAction
{
private readonly List<RantAction> _items = new List<RantAction>();
public RABlock(Stringe range, params RantAction[] items)
: base(range)
{
_items.AddRange(items);
}
public RABlock(Stringe range, List<RantAction> items)
: base(range)
{
_items.AddRange(items);
}
public override IEnumerator<RantAction> Run(Sandbox sb)
{
sb.Objects.EnterScope();
var attribs = sb.NextAttribs();
int next = -1;
var block = new BlockState(attribs.Repetitons);
sb.Blocks.Push(block);
for (int i = 0; i < attribs.Repetitons; i++)
{
next = attribs.NextIndex(_items.Count, sb.RNG);
if (next == -1) break;
block.Next(next);
sb.Blocks.Pop(); // Don't allow separator to access block state
// Separator
if (i > 0 && attribs.Separator != null) yield return attribs.Separator;
sb.Blocks.Push(block); // Now put it back
// Prefix
if (attribs.Before != null) yield return attribs.Before;
// Content
yield return _items[next];
// Affix
if (attribs.After != null) yield return attribs.After;
}
sb.Blocks.Pop();
sb.Objects.ExitScope();
}
}
} | using Rant.Stringes;
using System;
using System.Collections.Generic;
using System.Linq;
using Rant.Engine.Constructs;
namespace Rant.Engine.Syntax
{
/// <summary>
/// Represents a block construct, which provides multiple options to the interpreter for the next sequence, one of which is chosen.
/// </summary>
internal class RABlock : RantAction
{
private readonly List<RantAction> _items = new List<RantAction>();
public RABlock(Stringe range, params RantAction[] items)
: base(range)
{
_items.AddRange(items);
}
public RABlock(Stringe range, List<RantAction> items)
: base(range)
{
_items.AddRange(items);
}
public override IEnumerator<RantAction> Run(Sandbox sb)
{
var attribs = sb.NextAttribs();
int next = -1;
var block = new BlockState(attribs.Repetitons);
sb.Blocks.Push(block);
for (int i = 0; i < attribs.Repetitons; i++)
{
next = attribs.NextIndex(_items.Count, sb.RNG);
if (next == -1) break;
block.Next(next);
sb.Blocks.Pop(); // Don't allow separator to access block state
// Separator
if (i > 0 && attribs.Separator != null) yield return attribs.Separator;
sb.Blocks.Push(block); // Now put it back
// Prefix
if (attribs.Before != null) yield return attribs.Before;
// Content
yield return _items[next];
// Affix
if (attribs.After != null) yield return attribs.After;
}
sb.Blocks.Pop();
}
}
} | mit | C# |
31d33d26cc871c20d2a75724032259eacdd726c0 | increase batch version | ibrahimbensalah/Xania.AspNet,ibrahimbensalah/Xania.AspNet,ibrahimbensalah/Xania.AspNet | Xania.AspNet.TagHelpers/Properties/AssemblyInfo.cs | Xania.AspNet.TagHelpers/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Xania.AspNet.TagHelpers")]
[assembly: AssemblyDescription("Tag Helpers")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ibrahim ben Salah")]
[assembly: AssemblyProduct("Xania.AspNet.Components")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("30d59023-a655-44bb-9675-4008eb77fdd1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
[assembly: AssemblyInformationalVersion("1.0.13-beta")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Xania.AspNet.TagHelpers")]
[assembly: AssemblyDescription("Tag Helpers")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ibrahim ben Salah")]
[assembly: AssemblyProduct("Xania.AspNet.Components")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("30d59023-a655-44bb-9675-4008eb77fdd1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
[assembly: AssemblyInformationalVersion("1.0.11-beta")]
| mit | C# |
f8a8db6ed5150fa130e3da92eec2c3c12bf9cb71 | Change order | yishn/GTPWrapper | GTPWrapper/Sgf/SgfProperty.cs | GTPWrapper/Sgf/SgfProperty.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GTPWrapper.Sgf {
/// <summary>
/// Represents a SGF property.
/// </summary>
public class SgfProperty {
/// <summary>
/// The identifier of the property.
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// The value list of the property.
/// </summary>
public List<string> Values { get; set; }
/// <summary>
/// A fixed, canonical value.
/// </summary>
public string Value { get { return Values[0]; } set { Values[0] = value; } }
/// <summary>
/// Initializes a new instance of the SgfProperty class.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <param name="values">A list of values.</param>
public SgfProperty(string identifier, List<string> values) {
this.Identifier = identifier;
this.Values = values;
}
/// <summary>
/// Initializes a new instance of the SgfProperty class.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <param name="value">The value.</param>
public SgfProperty(string identifier, string value) : this(identifier, new string[] { value }.ToList()) { }
/// <summary>
/// Returns a string which represents the object.
/// </summary>
public override string ToString() {
return this.Identifier + "[" + string.Join("][", this.Values.Select(x => SgfProperty.Escape(x))) + "]";
}
/// <summary>
/// Escapes a minimal set of characters (\, ]) by replacing them with their escape codes.
/// </summary>
/// <param name="input">The input string.</param>
public static string Escape(string input) {
return input.Replace(@"\", @"\\").Replace(@"]", @"\]");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GTPWrapper.Sgf {
/// <summary>
/// Represents a SGF property.
/// </summary>
public class SgfProperty {
/// <summary>
/// The identifier of the property.
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// The value list of the property.
/// </summary>
public List<string> Values { get; set; }
/// <summary>
/// A fixed, canonical value.
/// </summary>
public string Value { get { return Values[0]; } set { Values[0] = value; } }
/// <summary>
/// Initializes a new instance of the SgfProperty class.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <param name="values">A list of values.</param>
public SgfProperty(string identifier, List<string> values) {
this.Identifier = identifier;
this.Values = values;
}
/// <summary>
/// Initializes a new instance of the SgfProperty class.
/// </summary>
/// <param name="identifier">The identifier.</param>
/// <param name="value">The value.</param>
public SgfProperty(string identifier, string value) : this(identifier, new string[] { value }.ToList()) { }
/// <summary>
/// Escapes a minimal set of characters (\, ]) by replacing them with their escape codes.
/// </summary>
/// <param name="input">The input string.</param>
public static string Escape(string input) {
return input.Replace(@"\", @"\\").Replace(@"]", @"\]");
}
/// <summary>
/// Returns a string which represents the object.
/// </summary>
public override string ToString() {
return this.Identifier + "[" + string.Join("][", this.Values.Select(x => SgfProperty.Escape(x))) + "]";
}
}
} | mit | C# |
aaf885b0db206f717a8e9094d29c1566385f7d84 | Make griddly defaults and parameters case insensitive | programcsharp/griddly,programcsharp/griddly,programcsharp/griddly | Griddly.Mvc/GriddlyContext.cs | Griddly.Mvc/GriddlyContext.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Griddly.Mvc
{
public class GriddlyContext
{
public string Name { get; set; }
public bool IsDefaultSkipped { get; set; }
public bool IsDeepLink { get; set; }
public GriddlyFilterCookieData CookieData { get; set; }
public string CookieName => "gf_" + Name;
public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
public int PageNumber { get; set; }
public int PageSize { get; set; }
public GriddlyExportFormat? ExportFormat { get; set; }
public SortField[] SortFields { get; set; }
}
public class GriddlyFilterCookieData
{
public Dictionary<string, string[]> Values { get; set; }
public SortField[] SortFields { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Griddly.Mvc
{
public class GriddlyContext
{
public string Name { get; set; }
public bool IsDefaultSkipped { get; set; }
public bool IsDeepLink { get; set; }
public GriddlyFilterCookieData CookieData { get; set; }
public string CookieName => "gf_" + Name;
public Dictionary<string, object> Defaults { get; set; } = new Dictionary<string, object>();
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
public int PageNumber { get; set; }
public int PageSize { get; set; }
public GriddlyExportFormat? ExportFormat { get; set; }
public SortField[] SortFields { get; set; }
}
public class GriddlyFilterCookieData
{
public Dictionary<string, string[]> Values { get; set; }
public SortField[] SortFields { get; set; }
}
}
| mit | C# |
42131774f293af5993319f0a4ed456a9532a779a | Fix tests compilation | tzachshabtay/MonoAGS | Source/Tests/Engine/Misc/Geometry/SquareTests.cs | Source/Tests/Engine/Misc/Geometry/SquareTests.cs | using NUnit.Framework;
using System;
using AGS.Engine;
using AGS.API;
namespace Tests
{
[TestFixture ()]
public class SquareTests
{
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 5f,5f, Result=true)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 15f,15f, Result=false)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 0f,0f, Result=true)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 10f,10f, Result=true)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 11f,11f, Result=false)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 10f,0f, Result=true)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 9f,9f, Result=true)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 9f,-9f, Result=true)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 9f,-11f, Result=false)]
public bool InsideSquareTest (float ax, float ay, float bx, float @by,
float cx, float cy, float dx, float dy, float px, float py)
{
AGSSquare square = new AGSSquare (new AGS.API.PointF (ax, ay), new AGS.API.PointF (bx, @by),
new AGS.API.PointF (cx, cy), new AGS.API.PointF (dx, dy));
return square.Contains (new AGS.API.PointF (px, py));
}
}
}
| using NUnit.Framework;
using System;
using AGS.Engine;
namespace Tests
{
[TestFixture ()]
public class SquareTests
{
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 5f,5f, Result=true)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 15f,15f, Result=false)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 0f,0f, Result=true)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 10f,10f, Result=true)]
[TestCase(0f,0f, 10f,0f, 0f,10f, 10f,10f, 11f,11f, Result=false)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 10f,0f, Result=true)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 9f,9f, Result=true)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 9f,-9f, Result=true)]
[TestCase(0f,0f, 10f,-10f, 10f,10f, 20f,0f, 9f,-11f, Result=false)]
public bool InsideSquareTest (float ax, float ay, float bx, float @by,
float cx, float cy, float dx, float dy, float px, float py)
{
AGSSquare square = new AGSSquare (new AGS.API.PointF (ax, ay), new AGS.API.PointF (bx, @by),
new AGS.API.PointF (cx, cy), new AGS.API.PointF (dx, dy));
return square.Contains (new AGS.API.PointF (px, py));
}
}
}
| artistic-2.0 | C# |
c00703318d75b427993604f308ed3bdd2023f8b2 | Test change in alpha branch | RationalGeek/sordid,RationalGeek/sordid,RationalGeek/sordid | source/Sordid.Web/Views/Home/Index.cshtml | source/Sordid.Web/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>Sordid</h1>
<h2>Dresden RPG Character Builder</h2>
<p class="lead">These words were written on the alpha branch...</p>
<p><a href="https://github.com/RationalGeek/sordid" class=" btn btn-primary btn-large">GitHub Project</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>Sordid</h1>
<h2>Dresden RPG Character Builder</h2>
<p class="lead">More words will appear her once they are written...</p>
<p><a href="https://github.com/RationalGeek/sordid" class=" btn btn-primary btn-large">GitHub Project</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | mit | C# |
992362f29ce417f52872b6a17e573016adc9c495 | Make ObjectPool mandatory for AudioController. | dimixar/audio-controller-unity | AudioController/Assets/Source/AudioController.cs | AudioController/Assets/Source/AudioController.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(ObjectPool))]
public class AudioController : MonoBehaviour
{
private ObjectPool _pool;
public void Play(string name)
{
//TODO: Add Implementation
}
void Awake()
{
_pool = GetComponent<ObjectPool>();
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AudioController : MonoBehaviour
{
public List<AudioObject> _audioObjects;
}
| mit | C# |
30d195b6981d7526cfb00d57707063127296863e | Update SerilogLoggingSetupBase.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Logging/Serilog/SerilogLoggingSetupBase.cs | TIKSN.Core/Analytics/Logging/Serilog/SerilogLoggingSetupBase.cs | using Microsoft.Extensions.Logging;
using Serilog;
namespace TIKSN.Analytics.Logging.Serilog
{
public class SerilogLoggingSetupBase : ILoggingSetup
{
protected LoggerConfiguration _loggerConfiguration;
protected SerilogLoggingSetupBase() => this._loggerConfiguration = new LoggerConfiguration();
public void Setup(ILoggingBuilder loggingBuilder)
{
this.SetupSerilog();
_ = loggingBuilder.AddSerilog(this._loggerConfiguration.CreateLogger(), true);
}
protected virtual void SetupSerilog()
{
_ = this._loggerConfiguration.MinimumLevel.Verbose();
_ = this._loggerConfiguration.Enrich.FromLogContext();
}
}
}
| using Microsoft.Extensions.Logging;
using Serilog;
namespace TIKSN.Analytics.Logging.Serilog
{
public class SerilogLoggingSetupBase : ILoggingSetup
{
protected LoggerConfiguration _loggerConfiguration;
protected SerilogLoggingSetupBase() => this._loggerConfiguration = new LoggerConfiguration();
public void Setup(ILoggingBuilder loggingBuilder)
{
this.SetupSerilog();
loggingBuilder.AddSerilog(this._loggerConfiguration.CreateLogger(), true);
}
protected virtual void SetupSerilog()
{
this._loggerConfiguration.MinimumLevel.Verbose();
this._loggerConfiguration.Enrich.FromLogContext();
}
}
}
| mit | C# |
d9f6857a6f302fc1881b5b237d844b061890e897 | revert to previous version. just set StoreUniqueId = true; | jeremytammik/TraverseAllSystems,ChengZY/TraverseAllSystems,jeremytammik/TraverseAllSystems,ChengZY/TraverseAllSystems | TraverseAllSystems/Options.cs | TraverseAllSystems/Options.cs | namespace TraverseAllSystems
{
class Options
{
/// <summary>
/// Store element id or UniqueId in JSON output?
/// </summary>
public static bool StoreUniqueId = true;
public static bool StoreElementId = !StoreUniqueId;
/// <summary>
/// Store parent node id in child, or recursive
/// tree of children in parent?
/// </summary>
public static bool StoreJsonGraphBottomUp = false;
public static bool StoreJsonGraphTopDown
= !StoreJsonGraphBottomUp;
}
}
| namespace TraverseAllSystems
{
class Options
{
/// <summary>
/// Store element id or UniqueId in JSON output?
/// </summary>
public static bool StoreUniqueId = true;
public static bool StoreElementId = !StoreUniqueId;
/// <summary>
/// Store parent node id in child, or recursive
/// tree of children in parent?
/// </summary>
public static bool StoreJsonGraphBottomUp = false;
public static bool StoreJsonGraphTopDown
= !StoreJsonGraphBottomUp;
public const string USC_FORGE_JSON_TREE_FORMAT = "{\"id\" : \"{0}\" , \"name\" : \"{1}\", \"udids\" : [ {2} ], \"children\" : [ ]}";
}
}
| mit | C# |
4dbcbbee20e6adc805be6cf1d23a657158a5d293 | Remove subjects from Teacher class | victoria92/university-program-generator,victoria92/university-program-generator | UniProgramGen/Data/Teacher.cs | UniProgramGen/Data/Teacher.cs | using System.Collections.Generic;
namespace UniProgramGen.Data
{
public class Teacher
{
// TODO: add list of requirements (as Requirement)
public readonly string name;
public Teacher(string name)
{
this.name = name;
}
}
}
| using System.Collections.Generic;
namespace UniProgramGen.Data
{
public class Teacher
{
// TODO: add list of requirements (as Requirement)
public readonly List<Subject> subjects;
public readonly string name;
public Teacher(List<Subject> subjects, string name)
{
this.subjects = subjects;
this.name = name;
}
}
}
| bsd-2-clause | C# |
ea2b0958b26a42b55dbd78c08b4549f11b5414ac | Edit Form1_Load method | 60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope | VisualStudioProjects/ArrayDataGraphic/ArrayDataGraphic/Form1.cs | VisualStudioProjects/ArrayDataGraphic/ArrayDataGraphic/Form1.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;
namespace ArrayDataGraphic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Add channels
List<string> TestList = new List<string>();
TestList.Add("Channel1");
TestList.Add("Channel2");
TestList.Add("Channel3");
// Create ArrayDataGraphic object
CSharpFiles.ArrayDataGraphic ArrayDataGraphic1 = new CSharpFiles.ArrayDataGraphic(TestList);
// Add datas
for (int Loopnum = 0; Loopnum < 500; Loopnum++)
{
ArrayDataGraphic1.AddData("Channel1", Loopnum * 2);
}
// Set graph width and height
ArrayDataGraphic1.SetWidth(panel1.Size.Width);
ArrayDataGraphic1.SetHeight(panel1.Size.Height);
panel1.Paint += new PaintEventHandler(ArrayDataGraphic1.DrawGraph);
panel1.Refresh();
}
}
}
| 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;
namespace ArrayDataGraphic
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
| apache-2.0 | C# |
4e5bcf62cd155f473204ee02354a085957c4e8d8 | Clean code | michael-reichenauer/Dependinator | Dependinator/ModelViewing/Items/ItemViewModel.cs | Dependinator/ModelViewing/Items/ItemViewModel.cs | using System.Windows;
using Dependinator.Utils.UI;
namespace Dependinator.ModelViewing.Items
{
internal abstract class ItemViewModel : ViewModel, IItem
{
// UI properties
public string Type => this.GetType().Name;
public double CanvasWidth => ItemBounds.Width;
public double CanvasTop => ItemBounds.Top;
public double CanvasLeft => ItemBounds.Left;
public virtual double CanvasHeight => ItemBounds.Height;
public Rect ItemBounds => GetItemBounds();
public ViewModel ViewModel => this;
public object ItemState { get; set; }
public bool CanShow { get; private set; }
public bool IsShowing { get; private set; }
public void Hide() => CanShow = false;
public void Show() => CanShow = true;
public virtual void ItemRealized() => IsShowing = true;
public virtual void ItemVirtualized() => IsShowing = false;
protected abstract Rect GetItemBounds();
}
} | using System.Windows;
using Dependinator.Utils.UI;
namespace Dependinator.ModelViewing.Items
{
internal abstract class ItemViewModel : ViewModel, IItem
{
// UI properties
public string Type => this.GetType().Name;
public double CanvasWidth => ItemBounds.Width;
public double CanvasTop => ItemBounds.Top;
public double CanvasLeft => ItemBounds.Left;
public virtual double CanvasHeight => ItemBounds.Height;
public Rect ItemBounds => GetItemBounds();
public ViewModel ViewModel => this;
public object ItemState { get; set; }
public bool CanShow { get; private set; }
public bool IsShowing { get; private set; }
public void Hide()
{
CanShow = false;
}
public void Show()
{
CanShow = true;
}
public virtual void ItemRealized()
{
//Log.Debug($"{GetType()} {this}");
IsShowing = true;
}
public virtual void ItemVirtualized()
{
//Log.Debug($"{GetType()} {this}");
if (this.ToString().EndsWith("Acs"))
{
}
IsShowing = false;
}
protected abstract Rect GetItemBounds();
}
} | mit | C# |
bca4894e8b9dc1485c9fca06bfcd184d378cefd5 | Update AssemblyInfo.cs | sbidy/privacyIDEA-ADFSProvider,sbidy/privacyIDEA-ADFSProvider | privacyIDEAADFSProvider/Properties/AssemblyInfo.cs | privacyIDEAADFSProvider/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("privacyIDEA-ADFSProvider")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("audius GmbH")]
[assembly: AssemblyProduct("privacyIDEAADFSProvider")]
[assembly: AssemblyCopyright("Copyright © audius GmbH 2018 - Stephan Traub")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a9a54d7-f23b-469c-ba61-8c69cbaf50f5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.2.0")]
[assembly: AssemblyFileVersion("1.3.2.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("privacyIDEA-ADFSProvider")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("audius GmbH")]
[assembly: AssemblyProduct("privacyIDEAADFSProvider")]
[assembly: AssemblyCopyright("Copyright © audius GmbH 2018 - Stephan traub")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a9a54d7-f23b-469c-ba61-8c69cbaf50f5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.2.0")]
[assembly: AssemblyFileVersion("1.3.2.0")]
| mit | C# |
08f3952a3ac8c49bc434bfbe96963b796b64e100 | Update CustomizingRibbonXML.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Articles/CustomizingRibbonXML.cs | Examples/CSharp/Articles/CustomizingRibbonXML.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class CustomizingRibbonXML
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx");
FileInfo fi = new FileInfo(dataDir+ "CustomUI.xml");
StreamReader sr = fi.OpenText();
wb.RibbonXml = sr.ReadToEnd();
sr.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class CustomizingRibbonXML
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Workbook wb = new Workbook(dataDir+ "aspose-sample.xlsx");
FileInfo fi = new FileInfo(dataDir+ "CustomUI.xml");
StreamReader sr = fi.OpenText();
wb.RibbonXml = sr.ReadToEnd();
sr.Close();
}
}
} | mit | C# |
1ffdbf39387c8ac54af915da74e45f8a6c85be80 | Throw ResultFailedException when error occured. | sdcb/sdmap | sdmap/src/sdmap/Functional/Result.cs | sdmap/src/sdmap/Functional/Result.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace sdmap.Functional
{
public class Result
{
public bool IsSuccess { get; }
public string Error { get; }
public bool IsFailure => !IsSuccess;
protected Result(bool isSuccess, string error)
{
if (isSuccess && error != string.Empty)
throw new InvalidOperationException();
if (!isSuccess && error == string.Empty)
throw new InvalidOperationException();
IsSuccess = isSuccess;
Error = error;
}
public static Result Fail(string message)
{
return new Result(false, message);
}
public static Result<T> Fail<T>(string message)
{
return new Result<T>(default(T), false, message);
}
public static Result Ok()
{
return new Result(true, string.Empty);
}
public static Result<T> Ok<T>(T value)
{
return new Result<T>(value, true, string.Empty);
}
public static Result Combine(IEnumerable<Result> results)
{
foreach (Result result in results)
{
if (result.IsFailure)
return result;
}
return Ok();
}
}
public class Result<T> : Result
{
private readonly T _value;
public T Value
{
get
{
if (!IsSuccess)
throw new ResultFailedException(Error);
return _value;
}
}
protected internal Result(T value, bool isSuccess, string error)
: base(isSuccess, error)
{
_value = value;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace sdmap.Functional
{
public class Result
{
public bool IsSuccess { get; }
public string Error { get; }
public bool IsFailure => !IsSuccess;
protected Result(bool isSuccess, string error)
{
if (isSuccess && error != string.Empty)
throw new InvalidOperationException();
if (!isSuccess && error == string.Empty)
throw new InvalidOperationException();
IsSuccess = isSuccess;
Error = error;
}
public static Result Fail(string message)
{
return new Result(false, message);
}
public static Result<T> Fail<T>(string message)
{
return new Result<T>(default(T), false, message);
}
public static Result Ok()
{
return new Result(true, string.Empty);
}
public static Result<T> Ok<T>(T value)
{
return new Result<T>(value, true, string.Empty);
}
public static Result Combine(IEnumerable<Result> results)
{
foreach (Result result in results)
{
if (result.IsFailure)
return result;
}
return Ok();
}
}
public class Result<T> : Result
{
private readonly T _value;
public T Value
{
get
{
if (!IsSuccess)
throw new InvalidOperationException();
return _value;
}
}
protected internal Result(T value, bool isSuccess, string error)
: base(isSuccess, error)
{
_value = value;
}
}
}
| mit | C# |
28642ab94978d91095f2511f5b24d22a6b66f6d9 | index on pin messageId | jyarbro/forum,jyarbro/forum,jyarbro/forum | Forum3/Models/DataModels/ApplicationDbContext.cs | Forum3/Models/DataModels/ApplicationDbContext.cs | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Forum3.Models.DataModels {
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> {
public DbSet<Board> Boards { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<MessageBoard> MessageBoards { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<MessageThought> MessageThoughts { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<Participant> Participants { get; set; }
public DbSet<Pin> Pins { get; set; }
public DbSet<SiteSetting> SiteSettings { get; set; }
public DbSet<Smiley> Smileys { get; set; }
public DbSet<ViewLog> ViewLogs { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Message>()
.HasIndex(b => b.LastReplyPosted);
modelBuilder.Entity<Pin>()
.HasIndex(b => b.MessageId);
}
}
} | using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Forum3.Models.DataModels {
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> {
public DbSet<Board> Boards { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<MessageBoard> MessageBoards { get; set; }
public DbSet<Message> Messages { get; set; }
public DbSet<MessageThought> MessageThoughts { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<Participant> Participants { get; set; }
public DbSet<Pin> Pins { get; set; }
public DbSet<SiteSetting> SiteSettings { get; set; }
public DbSet<Smiley> Smileys { get; set; }
public DbSet<ViewLog> ViewLogs { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Message>()
.HasIndex(b => b.LastReplyPosted);
}
}
} | unlicense | C# |
4735e2a0f028ce8dee418ce48d8a7aeb06da557a | Remove extraneous code | mstrother/BmpListener | src/BmpListener/Bmp/PeerUpNotification.cs | src/BmpListener/Bmp/PeerUpNotification.cs | using System;
using System.Net;
using BmpListener.Bgp;
using BmpListener.MiscUtil.Conversion;
namespace BmpListener.Bmp
{
public class PeerUpNotification : BmpMessage
{
public IPAddress LocalAddress { get; private set; }
public int LocalPort { get; private set; }
public int RemotePort { get; private set; }
public BgpOpenMessage SentOpenMessage { get; private set; }
public BgpOpenMessage ReceivedOpenMessage { get; private set; }
public override void Decode(byte[] data, int offset)
{
if ((PeerHeader.Flags & (1 << 7)) != 0)
{
var ipBytes = new byte[16];
Array.Copy(data, offset, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
else
{
var ipBytes = new byte[4];
Array.Copy(data, offset + 12, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
offset += 16;
LocalPort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
RemotePort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
offset += SentOpenMessage?.Header.Length ?? 0;
ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
}
}
} | using System;
using System.Net;
using BmpListener.Bgp;
using System.Linq;
using BmpListener.MiscUtil.Conversion;
namespace BmpListener.Bmp
{
public class PeerUpNotification : BmpMessage
{
public IPAddress LocalAddress { get; private set; }
public int LocalPort { get; private set; }
public int RemotePort { get; private set; }
public BgpOpenMessage SentOpenMessage { get; private set; }
public BgpOpenMessage ReceivedOpenMessage { get; private set; }
public override void Decode(byte[] data, int offset)
{
if (((PeerHeader.Flags & (1 << 7)) != 0))
{
var ipBytes = new byte[16];
Array.Copy(data, offset, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
else
{
var ipBytes = new byte[4];
Array.Copy(data, offset + 12, ipBytes, 0, 4);
LocalAddress = new IPAddress(ipBytes);
}
offset += 16;
LocalPort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
RemotePort = EndianBitConverter.Big.ToUInt16(data, offset);
offset += 2;
SentOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
offset += SentOpenMessage.Header.Length;
ReceivedOpenMessage = BgpMessage.DecodeMessage(data, offset) as BgpOpenMessage;
}
}
} | mit | C# |
4a2a794ff4ae9c92cfa730f5491e61223f71078a | Bump assembly version numbers | agc93/Cake.NSwag | src/Cake.NSwag/Properties/AssemblyInfo.cs | src/Cake.NSwag/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cake.NSwag")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cake.NSwag")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("63e80fbd-eabe-4fc8-b9e4-b82dd077fda0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Cake.NSwag")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Cake.NSwag")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("63e80fbd-eabe-4fc8-b9e4-b82dd077fda0")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | mit | C# |
c48510c39af0e98f8547d3da663909138ada5513 | Update HtmlSanitizerOptions.cs | mganss/HtmlSanitizer | src/HtmlSanitizer/HtmlSanitizerOptions.cs | src/HtmlSanitizer/HtmlSanitizerOptions.cs | using AngleSharp.Css.Dom;
using System;
using System.Collections.Generic;
namespace Ganss.XSS
{
/// <summary>
/// Provides options to be used with <see cref="HtmlSanitizer"/>.
/// </summary>
public class HtmlSanitizerOptions
{
/// <summary>
/// Gets or sets the allowed tag names such as "a" and "div".
/// </summary>
public ISet<string> AllowedTags { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the allowed HTML attributes such as "href" and "alt".
/// </summary>
public ISet<string> AllowedAttributes { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the allowed CSS properties such as "font" and "margin".
/// </summary>
public ISet<string> AllowedCssProperties { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the allowed CSS at-rules such as "@media" and "@font-face".
/// </summary>
public ISet<CssRuleType> AllowedAtRules { get; set; } = new HashSet<CssRuleType>();
/// <summary>
/// Gets or sets the allowed URI schemes such as "http" and "https".
/// </summary>
public ISet<string> AllowedSchemes { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the HTML attributes that can contain a URI such as "href".
/// </summary>
public ISet<string> UriAttributes { get; set; } = new HashSet<string>();
}
}
| using System;
using System.Collections.Generic;
namespace Ganss.XSS
{
/// <summary>
/// Provides options to be used with <see cref="HtmlSanitizer"/>.
/// </summary>
public class HtmlSanitizerOptions
{
/// <summary>
/// Gets or sets the allowed tag names such as "a" and "div".
// </summary>
public ISet<string> AllowedTags { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the allowed HTML attributes such as "href" and "alt".
// </summary>
public ISet<string> AllowedAttributes { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the allowed CSS properties such as "font" and "margin".
// </summary>
public ISet<string> AllowedCssProperties { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the allowed CSS at-rules such as "@media" and "@font-face".
// </summary>
public ISet<CssRuleType> AllowedAtRules { get; set; } = new HashSet<CssRuleType>();
/// <summary>
/// Gets or sets the allowed URI schemes such as "http" and "https".
// </summary>
public ISet<string> AllowedSchemes { get; set; } = new HashSet<string>();
/// <summary>
/// Gets or sets the HTML attributes that can contain a URI such as "href".
// </summary>
public ISet<string> UriAttributes { get; set; } = new HashSet<string>();
}
}
| mit | C# |
fbc3cb02774037dc281e143230218191aad2f180 | Add field for error responses | Inumedia/SlackAPI | SlackAPI/RPCMessages/ConversationsOpenResponse.cs | SlackAPI/RPCMessages/ConversationsOpenResponse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
[RequestPath("conversations.open")]
public class ConversationsOpenResponse : Response
{
public string no_op;
public string already_open;
public Channel channel;
public string error;
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SlackAPI
{
[RequestPath("conversations.open")]
public class ConversationsOpenResponse : Response
{
public string no_op;
public string already_open;
public Channel channel;
}
}
| mit | C# |
e346adbb166f5d1ed31d96dc017610bccb590877 | Fix directory structure inside .bloom | BloomBooks/PhotoStoryToBloomConverter,BloomBooks/PhotoStoryToBloomConverter | PhotoStoryToBloomConverter/Utilities/ZipHelper.cs | PhotoStoryToBloomConverter/Utilities/ZipHelper.cs | using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using SIL.IO;
namespace PhotoStoryToBloomConverter.Utilities
{
/// <summary>
/// Copied and modified from BloomDesktop's BloomZipFile
/// </summary>
public static class ZipHelper
{
public static void Zip(string directoryPath, string outputPath)
{
var fsOut = RobustFile.Create(outputPath);
ZipOutputStream zipStream = new ZipOutputStream(fsOut);
AddDirectoryContents(directoryPath, zipStream);
zipStream.IsStreamOwner = true; // makes the Close() also close the underlying stream
zipStream.Close();
}
/// <summary>
/// Adds a directory's files and subdirectories, but not the directory itself
/// </summary>
private static void AddDirectoryContents(string directoryPath, ZipOutputStream zipStream)
{
AddDirectory(directoryPath, directoryPath.Length, zipStream);
}
private static void AddDirectory(string directoryPath, int dirNameOffset, ZipOutputStream zipStream)
{
var files = Directory.GetFiles(directoryPath);
foreach (var path in files)
{
var entryName = path.Substring(dirNameOffset);
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
AddFile(path, entryName, zipStream);
}
var folders = Directory.GetDirectories(directoryPath);
foreach (var folder in folders)
{
var dirName = Path.GetFileName(folder);
if (dirName == null)
continue; // Don't want to bundle these up
AddDirectory(folder, dirNameOffset, zipStream);
}
}
private static void AddFile(string path, string entryName, ZipOutputStream zipStream)
{
var fi = new FileInfo(path);
var newEntry = new ZipEntry(entryName) { DateTime = fi.LastWriteTime, Size = fi.Length, IsUnicodeText = true };
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
var buffer = new byte[4096];
using (var streamReader = RobustFile.OpenRead(path))
{
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
}
}
| using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using SIL.IO;
namespace PhotoStoryToBloomConverter.Utilities
{
/// <summary>
/// Copied and modified from BloomDesktop's BloomZipFile
/// </summary>
public static class ZipHelper
{
public static void Zip(string directoryPath, string outputPath)
{
var fsOut = RobustFile.Create(outputPath);
ZipOutputStream zipStream = new ZipOutputStream(fsOut);
AddDirectory(directoryPath, zipStream);
zipStream.IsStreamOwner = true; // makes the Close() also close the underlying stream
zipStream.Close();
}
/// <summary>
/// Adds a directory, along with all files and subdirectories
/// </summary>
private static void AddDirectory(string directoryPath, ZipOutputStream zipStream)
{
var rootName = Path.GetFileName(directoryPath);
if (rootName == null)
return;
var dirNameOffset = directoryPath.Length - rootName.Length;
AddDirectory(directoryPath, dirNameOffset, zipStream);
}
private static void AddDirectory(string directoryPath, int dirNameOffset, ZipOutputStream zipStream)
{
var files = Directory.GetFiles(directoryPath);
foreach (var path in files)
{
var entryName = path.Substring(dirNameOffset);
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
AddFile(path, entryName, zipStream);
}
var folders = Directory.GetDirectories(directoryPath);
foreach (var folder in folders)
{
var dirName = Path.GetFileName(folder);
if (dirName == null)
continue; // Don't want to bundle these up
AddDirectory(folder, dirNameOffset, zipStream);
}
}
private static void AddFile(string path, string entryName, ZipOutputStream zipStream)
{
var fi = new FileInfo(path);
var newEntry = new ZipEntry(entryName) { DateTime = fi.LastWriteTime, Size = fi.Length, IsUnicodeText = true };
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
var buffer = new byte[4096];
using (var streamReader = RobustFile.OpenRead(path))
{
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
}
}
| mit | C# |
a8455ee93e3bc79708fb90fa26905764b9737b3b | Update Index.cshtml | feinoujc/RavenMailtrap | RavenMailtrap.Website/Views/Messages/Index.cshtml | RavenMailtrap.Website/Views/Messages/Index.cshtml | @using MvcContrib.Pagination
@using MvcContrib.UI.Pager
@using MvcContrib.UI.Grid
@using RavenMailtrap.Model
@model IEnumerable<Message>
@{
ViewBag.Title = "Home Page";
}
@Html.Grid(Model).Columns(columns =>
{
columns.For(m => m.From).Sortable(true);
columns.For(m => m.Subject).Sortable(true);
columns.For(m => string.Join("; ", m.To)).Named("To").Sortable(false);
columns.For(m => m.ReceivedDate).Sortable(true);
columns.For(m => m.ServerHostName).Named("Server").Sortable(true);
columns.For(m => Html.ActionLink("View", "Details", new { id = m.Id }, new { @class = "details_link" }));
}).Sort(ViewBag.Sort ?? new GridSortOptions())
@Html.Raw(Html.Pager((IPagination)Model))
<div id="mail_dialog">
</div>
@section scripts
{
<script type="text/javascript">
setInterval(function() {
var dialog = $('#mail_dialog').data('ui-dialog');
if (!dialog || !dialog.isOpen) {
window.location.reload();
}
}, 20000);
$('.details_link').on('click', function (evt) {
evt.preventDefault();
$.get($(this).attr('href'), function (data) {
var container = $('#mail_dialog');
container.html(data);
container.dialog({
width: '800',
height: 'auto',
modal: true,
close: function () {
container.dialog('destroy');
container.empty();
}
});
});
});
</script>
}
| @using MvcContrib.Pagination
@using MvcContrib.UI.Pager
@using MvcContrib.UI.Grid
@using RavenMailtrap.Model
@model IEnumerable<Message>
@{
ViewBag.Title = "Home Page";
}
@Html.Grid(Model).Columns(columns =>
{
columns.For(m => m.From).Sortable(true);
columns.For(m => m.Subject).Sortable(true);
columns.For(m => string.Join("; ", m.To)).Named("To").Sortable(false);
columns.For(m => m.ReceivedDate).Sortable(true);
columns.For(m => m.ServerHostName).Named("Server").Sortable(true);
columns.For(m => Html.ActionLink("View", "Details", new { id = m.Id }, new { @class = "details_link" }));
}).Sort(ViewBag.Sort ?? new GridSortOptions())
@Html.Raw(Html.Pager((IPagination)Model))
<div id="mail_dialog">
</div>
@section scripts
{
<script type="text/javascript">
setInterval(function() {
var dialog = $('#mail_dialog').data('ui-dialog');
if (!dialog || !dialog.isOpen) {
window.location.reload();
}
}, 20000);
$('.details_link').on('click', function (evt) {
evt.preventDefault();
$.get($(this).attr('href'), function (data) {
var container = $('#mail_dialog');
container.html(data);
container.dialog({
width: '800',
height: 'auto',
modal: true,
close: function () {
container.dialog('destroy');
}
});
});
});
</script>
}
| apache-2.0 | C# |
3abc87385e5195b28c63759f07be2ac8aff380d9 | fix paging bug | MattsGitCode/DevDotMail,MattsGitCode/DevDotMail | DevDotMail/EmailListModel.cs | DevDotMail/EmailListModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DevDotMail
{
public class EmailListModel
{
public List<Email> Emails { get; private set; }
public int TotalRecordCount { get; private set; }
public QueryBuilder Builder { get; private set; }
public int CurrentPage { get; private set; }
public int PageStartRecord { get; private set; }
public int PageLastRecord { get; private set; }
public int TotalPages { get; private set; }
public IEnumerable<int> PagesToLink { get; private set; }
public bool ShowFirstPageLink { get; private set; }
public bool ShowLastPageLink { get; private set; }
public EmailListModel(List<Email> emails, int total, QueryBuilder builder)
{
Emails = emails;
TotalRecordCount = total;
Builder = builder;
CurrentPage = builder.Page;
PageStartRecord = (CurrentPage - 1) * builder.PageSize + 1;
PageLastRecord = PageStartRecord + Emails.Count;
TotalPages = total / builder.PageSize + (((total % builder.PageSize) == 0) ? 0 : 1);
int pagesToShow = 10;
if (pagesToShow > TotalPages)
{
PagesToLink = Enumerable.Range(1, TotalPages);
}
else
{
int pagesBefore = pagesToShow / 2;
int startPage;
if ((CurrentPage - 1) < pagesBefore)
startPage = 1;
else if (CurrentPage > (TotalPages - pagesToShow) + pagesBefore)
startPage = TotalPages - pagesToShow + 1;
else
startPage = CurrentPage - pagesBefore;
PagesToLink = Enumerable.Range(startPage, pagesToShow);
ShowFirstPageLink = startPage > 1;
ShowLastPageLink = startPage + pagesToShow - 1 < TotalPages;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DevDotMail
{
public class EmailListModel
{
public List<Email> Emails { get; private set; }
public int TotalRecordCount { get; private set; }
public QueryBuilder Builder { get; private set; }
public int CurrentPage { get; private set; }
public int PageStartRecord { get; private set; }
public int PageLastRecord { get; private set; }
public int TotalPages { get; private set; }
public IEnumerable<int> PagesToLink { get; private set; }
public bool ShowFirstPageLink { get; private set; }
public bool ShowLastPageLink { get; private set; }
public EmailListModel(List<Email> emails, int total, QueryBuilder builder)
{
Emails = emails;
TotalRecordCount = total;
Builder = builder;
CurrentPage = builder.Page;
PageStartRecord = (CurrentPage - 1) * builder.PageSize + 1;
PageLastRecord = PageStartRecord + Emails.Count;
TotalPages = total / builder.PageSize + (((total % builder.PageSize) == 0) ? 1 : 0);
int pagesToShow = 10;
if (pagesToShow > TotalPages)
{
PagesToLink = Enumerable.Range(1, TotalPages);
}
else
{
int pagesBefore = pagesToShow / 2;
int startPage;
if ((CurrentPage - 1) < pagesBefore)
startPage = 1;
else if (CurrentPage > (TotalPages - pagesToShow) + pagesBefore)
startPage = TotalPages - pagesToShow + 1;
else
startPage = CurrentPage - pagesBefore;
PagesToLink = Enumerable.Range(startPage, pagesToShow);
ShowFirstPageLink = startPage > 1;
ShowLastPageLink = startPage + pagesToShow - 1 < TotalPages;
}
}
}
} | mit | C# |
2c78f7d21cdac0f07309e419c4679b88ae3707b7 | Change StandardBase32Encoding.Alphabet constant to a readonly property. | wiry-net/Wiry.Base32,wiry-net/Base32,wiry-net/Wiry.Base32,wiry-net/Base32 | src/Wiry.Base32/StandardBase32Encoding.cs | src/Wiry.Base32/StandardBase32Encoding.cs | // Copyright (c) Dmitry Razumikhin, 2016-2019.
// Licensed under the MIT License.
// See LICENSE in the project root for license information.
namespace Wiry.Base32
{
internal sealed class StandardBase32Encoding : Base32Encoding
{
private string Alphabet => "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
public override string GetString(byte[] bytes, int index, int count)
{
return ToBase32(bytes, index, count, Alphabet, '=');
}
public override byte[] ToBytes(string encoded, int index, int length)
{
return ToBytes(encoded, index, length, '=', GetOrCreateLookupTable(Alphabet));
}
public override ValidationResult Validate(string encoded, int index, int length)
{
return Validate(encoded, index, length, '=', GetOrCreateLookupTable(Alphabet));
}
}
} | // Copyright (c) Dmitry Razumikhin, 2016-2019.
// Licensed under the MIT License.
// See LICENSE in the project root for license information.
namespace Wiry.Base32
{
internal sealed class StandardBase32Encoding : Base32Encoding
{
private const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
public override string GetString(byte[] bytes, int index, int count)
{
return ToBase32(bytes, index, count, Alphabet, '=');
}
public override byte[] ToBytes(string encoded, int index, int length)
{
return ToBytes(encoded, index, length, '=', GetOrCreateLookupTable(Alphabet));
}
public override ValidationResult Validate(string encoded, int index, int length)
{
return Validate(encoded, index, length, '=', GetOrCreateLookupTable(Alphabet));
}
}
} | mit | C# |
ed92cdc8cb157aa6c4e2b9edf2ef2eeeec79c931 | Fix typo in martial-art genre descrption string | InfiniteSoul/Azuria | Azuria/Enums/Info/Genre.cs | Azuria/Enums/Info/Genre.cs | using System.ComponentModel;
#pragma warning disable 1591
namespace Azuria.Enums.Info
{
public enum Genre
{
[Description("Abenteuer")] Adventure,
[Description("Action")] Action,
[Description("Adult")] Adult,
[Description("Comedy")] Comedy,
[Description("Cyberpunk")] Cyberpunk,
[Description("Drama")] Drama,
[Description("Ecchi")] Ecchi,
[Description("Fantasy")] Fantasy,
[Description("Harem")] Harem,
[Description("Historical")] Historical,
[Description("Horror")] Horror,
[Description("Josei")] Josei,
[Description("Magic")] Magic,
[Description("Martial-Art")] MartialArt,
[Description("Mecha")] Mecha,
[Description("Military")] Military,
[Description("Musik")] Music,
[Description("Mystery")] Mystery,
[Description("Psychological")] Psychological,
[Description("Romance")] Romance,
[Description("School")] School,
[Description("SciFi")] SciFi,
[Description("Seinen")] Seinen,
[Description("Shoujou")] Shoujou,
[Description("Shoujou-Ai")] ShoujouAi,
[Description("Shounen")] Shounen,
[Description("Shounen-Ai")] ShounenAi,
[Description("Slice_of_Life")] SliceOfLife,
[Description("Splatter")] Splatter,
[Description("Sport")] Sport,
[Description("Superpower")] Superpower,
[Description("Vampire")] Vampire,
[Description("Violence")] Violence,
[Description("Yaoi")] Yaoi,
[Description("Yuri")] Yuri
}
} | using System.ComponentModel;
#pragma warning disable 1591
namespace Azuria.Enums.Info
{
public enum Genre
{
[Description("Abenteuer")] Adventure,
[Description("Action")] Action,
[Description("Adult")] Adult,
[Description("Comedy")] Comedy,
[Description("Cyberpunk")] Cyberpunk,
[Description("Drama")] Drama,
[Description("Ecchi")] Ecchi,
[Description("Fantasy")] Fantasy,
[Description("Harem")] Harem,
[Description("Historical")] Historical,
[Description("Horror")] Horror,
[Description("Josei")] Josei,
[Description("Magic")] Magic,
[Description("Marial-Art")] MartialArt,
[Description("Mecha")] Mecha,
[Description("Military")] Military,
[Description("Musik")] Music,
[Description("Mystery")] Mystery,
[Description("Psychological")] Psychological,
[Description("Romance")] Romance,
[Description("School")] School,
[Description("SciFi")] SciFi,
[Description("Seinen")] Seinen,
[Description("Shoujou")] Shoujou,
[Description("Shoujou-Ai")] ShoujouAi,
[Description("Shounen")] Shounen,
[Description("Shounen-Ai")] ShounenAi,
[Description("Slice_of_Life")] SliceOfLife,
[Description("Splatter")] Splatter,
[Description("Sport")] Sport,
[Description("Superpower")] Superpower,
[Description("Vampire")] Vampire,
[Description("Violence")] Violence,
[Description("Yaoi")] Yaoi,
[Description("Yuri")] Yuri
}
} | mit | C# |
5c88ad53bcee510b1c1416a430ab5f8878ceeef7 | Fix code quality issues | tewarid/NetTools,tewarid/net-tools | Common/NameValueDialog.cs | Common/NameValueDialog.cs | using System;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace Common
{
public partial class NameValueDialog : Form
{
NameValueCollection collection;
public NameValueCollection NameValues
{
get
{
return collection;
}
}
public NameValueDialog()
{
InitializeComponent();
collection = new NameValueCollection();
}
public NameValueDialog(string title,
NameValueCollection initialValues) : this()
{
this.Text = title;
this.collection.Add(initialValues);
foreach(string key in this.collection)
{
headers.Rows.Add(key, this.collection[key]);
}
}
private void remove_Click(object sender, EventArgs e)
{
if (headers.SelectedRows.Count > 0 && !headers.SelectedRows[0].IsNewRow)
{
headers.Rows.Remove(headers.SelectedRows[0]);
}
}
private void done_Click(object sender, EventArgs e)
{
collection = new NameValueCollection();
foreach (DataGridViewRow row in headers.Rows)
{
string name = (string)row.Cells[0].Value;
string value = (string)row.Cells[1].Value;
if (!string.IsNullOrWhiteSpace(name))
collection.Add(name, value);
}
this.Hide();
}
}
}
| using System;
using System.Collections.Specialized;
using System.Windows.Forms;
namespace Common
{
public partial class NameValueDialog : Form
{
NameValueCollection collection;
public NameValueCollection NameValues
{
get
{
return collection;
}
}
public NameValueDialog()
{
InitializeComponent();
collection = new NameValueCollection();
}
public NameValueDialog(string title,
NameValueCollection initialValues) : this()
{
this.Text = title;
this.collection.Add(initialValues);
foreach(string key in this.collection)
{
headers.Rows.Add(key, this.collection[key]);
}
}
private void remove_Click(object sender, EventArgs e)
{
if (headers.SelectedRows.Count > 0 && !headers.SelectedRows[0].IsNewRow)
headers.Rows.Remove(headers.SelectedRows[0]);
}
private void done_Click(object sender, EventArgs e)
{
collection = new NameValueCollection();
foreach (DataGridViewRow row in headers.Rows)
{
string name = (string)row.Cells[0].Value;
string value = (string)row.Cells[1].Value;
if (!string.IsNullOrWhiteSpace(name))
collection.Add(name, value);
}
this.Hide();
}
}
}
| mit | C# |
01bda82d20fb894e38d2f2f845f055ef9a3e53eb | Fix styling | It423/enigma-simulator,wrightg42/enigma-simulator | Enigma/Enigma/App.xaml.cs | Enigma/Enigma/App.xaml.cs | // App.xaml.cs
// <copyright file="App.xaml.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Enigma
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| // App.xaml.cs
// <copyright file="App.xaml.cs"> This code is protected under the MIT License. </copyright>using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Enigma
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| mit | C# |
e6e85f67eb20dc105e1b75dcbb3a8eb67d61d83d | Add license disclaimer Cleanup formatting | jamespearce2006/CefSharp,Livit/CefSharp,AJDev77/CefSharp,rlmcneary2/CefSharp,haozhouxu/CefSharp,rover886/CefSharp,yoder/CefSharp,dga711/CefSharp,VioletLife/CefSharp,twxstar/CefSharp,windygu/CefSharp,ruisebastiao/CefSharp,wangzheng888520/CefSharp,NumbersInternational/CefSharp,dga711/CefSharp,illfang/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,twxstar/CefSharp,zhangjingpu/CefSharp,zhangjingpu/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,gregmartinhtc/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,ruisebastiao/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,ITGlobal/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,illfang/CefSharp,Livit/CefSharp,windygu/CefSharp,rover886/CefSharp,ITGlobal/CefSharp,AJDev77/CefSharp,joshvera/CefSharp,Livit/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,AJDev77/CefSharp,illfang/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,Livit/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,dga711/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,yoder/CefSharp,windygu/CefSharp,windygu/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,NumbersInternational/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,gregmartinhtc/CefSharp | CefSharp.Wpf.Example/Handlers/MenuHandler.cs | CefSharp.Wpf.Example/Handlers/MenuHandler.cs | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
namespace CefSharp.Wpf.Example.Handlers
{
public class MenuHandler : IMenuHandler
{
public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters)
{
Console.WriteLine("Context menu opened");
Console.WriteLine(parameters.MisspelledWord);
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CefSharp.Wpf.Example.Handlers
{
public class MenuHandler : IMenuHandler
{
public bool OnBeforeContextMenu(IWebBrowser browser, IContextMenuParams parameters)
{
Console.WriteLine("Context menu opened");
Console.WriteLine(parameters.MisspelledWord);
return true;
}
}
}
| bsd-3-clause | C# |
8bd73d083dd8a3bd0c800c60919ff64a676ef986 | Add property 'Descricao' to class 'DetalheCurso' | fmassaretto/formacao-talentos,fmassaretto/formacao-talentos,fmassaretto/formacao-talentos | Fatec.Treinamento.Model/DTO/DetalhesCurso.cs | Fatec.Treinamento.Model/DTO/DetalhesCurso.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fatec.Treinamento.Model.DTO
{
public class DetalhesCurso
{
public int Id { get; set; }
public string Nome { get; set; }
public string Assunto { get; set; }
public string Autor { get; set; }
public DateTime DataCriacao { get; set; }
public int Classificacao { get; set; }
//public string Descricao { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Fatec.Treinamento.Model.DTO
{
public class DetalhesCurso
{
public int Id { get; set; }
public string Nome { get; set; }
public string Assunto { get; set; }
public string Autor { get; set; }
public DateTime DataCriacao { get; set; }
public int Classificacao { get; set; }
}
}
| apache-2.0 | C# |
862ab13ae752363b322be9d2008cc44bcec9ef29 | Update Version | HittPre/Hipre | PreLeBlanc/PreLeBlanc/Properties/AssemblyInfo.cs | PreLeBlanc/PreLeBlanc/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LeBlanc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PreLeBlanc")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("08c2d11a-6e8b-48da-9859-1eec58d3ec95")]
// 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("7.7.1.4")]
[assembly: AssemblyFileVersion("7.7.1.4")]
| 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("PreLeBlanc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PreLeBlanc")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("08c2d11a-6e8b-48da-9859-1eec58d3ec95")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
c429de4869f6f01869c29e43e0002a08974e6e7d | Add Peter Parker to contact page. | 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:Support@example.com">Support@wechangedthis.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a>
<strong>Peter Parker</strong> <a href="mailto:spiderman@spiderman.com">Spiderman@spiderman.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:Support@example.com">Support@wechangedthis.com</a><br />
<strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a>
<strong>Batman:</strong> <a href="mailto:Batman@batman.com">Batman@batman.com</a>
</address> | mit | C# |
03dc90bad47103fd03687dbe167faf078cfdac6f | add wav conversion | jasonracey/ConvertToMp3,jasonracey/ConvertToMp3 | ConvertToMp3/FileFinder.cs | ConvertToMp3/FileFinder.cs | using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace ConvertToMp3
{
public static class FileFinder
{
private static readonly List<string> Extensions = new List<string>
{
".ape",
".flac",
".m4a",
".mp4",
".wav"
};
public static IEnumerable<string> GetSupportedFiles(string path)
{
return Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
.Where(file => Extensions.Contains(Path.GetExtension(file) ?? string.Empty, StringComparer.OrdinalIgnoreCase));
}
}
}
| using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace ConvertToMp3
{
public static class FileFinder
{
private static readonly List<string> Extensions = new List<string> { ".ape", ".flac", ".m4a", ".mp4" };
public static IEnumerable<string> GetSupportedFiles(string path)
{
return Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
.Where(file => Extensions.Contains(Path.GetExtension(file) ?? string.Empty, StringComparer.OrdinalIgnoreCase));
}
}
}
| mit | C# |
838274a0bc56cf1d113c3230bd9e4f100f69f466 | Fix soname | CallumDev/FontConfigSharp | FontConfigSharp/Native.cs | FontConfigSharp/Native.cs | using System;
using System.Runtime.InteropServices;
namespace FontConfigSharp
{
internal static class Native
{
public const string LIB = "libfontconfig.so.1";
[DllImport(LIB)]
public static extern IntPtr FcInitLoadConfigAndFonts();
[DllImport(LIB)]
public static extern IntPtr FcPatternCreate();
[DllImport(LIB)]
public static extern IntPtr FcFontList (IntPtr config, IntPtr p, IntPtr os);
//this is varargs
[DllImport(LIB)]
public static extern IntPtr FcObjectSetCreate();
[DllImport(LIB)]
public static extern void FcFontSetDestroy (IntPtr fs);
[DllImport(LIB)]
public static extern int FcObjectSetAdd (IntPtr os, [MarshalAs(UnmanagedType.LPStr)]string obj);
[DllImport(LIB)]
public static extern FcResult FcPatternGetString (
IntPtr p,
[MarshalAs (UnmanagedType.LPStr)]string obj,
int n,
ref IntPtr s);
[DllImport(LIB)]
public static extern void FcPatternDestroy (IntPtr p);
[DllImport(LIB)]
public static extern void FcObjectSetDestroy (IntPtr os);
[DllImport(LIB)]
public static extern IntPtr FcNameParse ([MarshalAs(UnmanagedType.LPStr)]string name);
[DllImport(LIB)]
public static extern void FcDefaultSubstitute (IntPtr pattern);
[DllImport(LIB)]
public static extern int FcConfigSubstitute (IntPtr config, IntPtr p, FcMatchKind kind);
[DllImport(LIB)]
public static extern IntPtr FcFontMatch (IntPtr config, IntPtr p, out FcResult result);
[DllImport(LIB)]
public static extern IntPtr FcCharSetCreate();
[DllImport(LIB)]
public static extern IntPtr FcCharSetAddChar(IntPtr fcs, uint ucs4);
[DllImport(LIB)]
public static extern bool FcPatternAddCharSet(IntPtr p, string obj, IntPtr c);
[DllImport(LIB)]
public static extern void FcCharSetDestroy(IntPtr fcs);
}
}
| using System;
using System.Runtime.InteropServices;
namespace FontConfigSharp
{
internal static class Native
{
[DllImport("libfontconfig.so")]
public static extern IntPtr FcInitLoadConfigAndFonts();
[DllImport("libfontconfig.so")]
public static extern IntPtr FcPatternCreate();
[DllImport("libfontconfig.so")]
public static extern IntPtr FcFontList (IntPtr config, IntPtr p, IntPtr os);
//this is varargs
[DllImport("libfontconfig.so")]
public static extern IntPtr FcObjectSetCreate();
[DllImport("libfontconfig.so")]
public static extern void FcFontSetDestroy (IntPtr fs);
[DllImport("libfontconfig.so")]
public static extern int FcObjectSetAdd (IntPtr os, [MarshalAs(UnmanagedType.LPStr)]string obj);
[DllImport("libfontconfig.so")]
public static extern FcResult FcPatternGetString (
IntPtr p,
[MarshalAs (UnmanagedType.LPStr)]string obj,
int n,
ref IntPtr s);
[DllImport("libfontconfig.so")]
public static extern void FcPatternDestroy (IntPtr p);
[DllImport("libfontconfig.so")]
public static extern void FcObjectSetDestroy (IntPtr os);
[DllImport("libfontconfig.so")]
public static extern IntPtr FcNameParse ([MarshalAs(UnmanagedType.LPStr)]string name);
[DllImport("libfontconfig.so")]
public static extern void FcDefaultSubstitute (IntPtr pattern);
[DllImport("libfontconfig.so")]
public static extern int FcConfigSubstitute (IntPtr config, IntPtr p, FcMatchKind kind);
[DllImport("libfontconfig.so")]
public static extern IntPtr FcFontMatch (IntPtr config, IntPtr p, out FcResult result);
[DllImport("libfontconfig.so")]
public static extern IntPtr FcCharSetCreate();
[DllImport("libfontconfig.so")]
public static extern IntPtr FcCharSetAddChar(IntPtr fcs, uint ucs4);
[DllImport("libfontconfig.so")]
public static extern bool FcPatternAddCharSet(IntPtr p, string obj, IntPtr c);
[DllImport("libfontconfig.so")]
public static extern void FcCharSetDestroy(IntPtr fcs);
}
}
| mit | C# |
d04466bd62f4c356997bcb9d4ce0cdf21b741d9e | Fix default name for images | pleonex/deblocus,pleonex/deblocus | Deblocus/Entities/Image.cs | Deblocus/Entities/Image.cs | //
// Image.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
namespace Deblocus.Entities
{
public class Image
{
private string name;
public Image()
{
Name = DefaultName;
}
public static string DefaultName {
get { return "No Name"; }
}
public virtual int Id { get; protected set; }
public virtual byte[] Data { get; set; }
public virtual string Name {
get { return name; }
set { name = string.IsNullOrEmpty(value) ? DefaultName : value; }
}
public virtual string Description { get; set; }
}
}
| //
// Image.cs
//
// Author:
// Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com>
//
// Copyright (c) 2015 Benito Palacios Sánchez (c) 2015
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
namespace Deblocus.Entities
{
public class Image
{
private string name;
public Image()
{
Name = DefaultName;
}
public static string DefaultName {
get { return "No Title"; }
}
public virtual int Id { get; protected set; }
public virtual byte[] Data { get; set; }
public virtual string Name {
get { return name; }
set { name = string.IsNullOrEmpty(value) ? DefaultName : value; }
}
public virtual string Description { get; set; }
}
}
| agpl-3.0 | C# |
5c6d9751ca9c70194dbfda9414883b9de3288a6a | Remove unneeded property | eggapauli/MyDocs,eggapauli/MyDocs | JsonNetDal/SubDocument.cs | JsonNetDal/SubDocument.cs | using MyDocs.Common;
using MyDocs.Common.Contract.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Logic = MyDocs.Common.Model.Logic;
namespace JsonNetDal
{
public class SubDocument
{
public string Title { get; set; }
public string File { get; set; }
public List<string> Photos { get; set; }
public SubDocument() { }
public SubDocument(string title, string file, IEnumerable<string> photos)
{
Title = title;
File = file;
Photos = photos.ToList();
}
public static SubDocument FromLogic(Logic.SubDocument subDocument)
{
return new SubDocument(subDocument.Title, subDocument.File.GetUri().AbsoluteUri, subDocument.Photos.Select(p => p.File.GetUri().AbsoluteUri));
}
public async Task<Logic.SubDocument> ToLogic()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(File));
var photoTasks =
Photos
.Select(p => new Uri(p))
.Select(StorageFile.GetFileFromApplicationUriAsync)
.Select(x => x.AsTask());
var photos = await Task.WhenAll(photoTasks);
return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p)));
}
}
}
| using MyDocs.Common;
using MyDocs.Common.Contract.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Logic = MyDocs.Common.Model.Logic;
namespace JsonNetDal
{
public class SubDocument
{
public Guid Id { get; set; }
public string Title { get; set; }
public string File { get; set; }
public List<string> Photos { get; set; }
public SubDocument() { }
public SubDocument(string title, string file, IEnumerable<string> photos)
{
Title = title;
File = file;
Photos = photos.ToList();
}
public static SubDocument FromLogic(Logic.SubDocument subDocument)
{
return new SubDocument(subDocument.Title, subDocument.File.GetUri().AbsoluteUri, subDocument.Photos.Select(p => p.File.GetUri().AbsoluteUri));
}
public async Task<Logic.SubDocument> ToLogic()
{
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(File));
var photoTasks =
Photos
.Select(p => new Uri(p))
.Select(StorageFile.GetFileFromApplicationUriAsync)
.Select(x => x.AsTask());
var photos = await Task.WhenAll(photoTasks);
return new Logic.SubDocument(file, photos.Select(p => new Logic.Photo(p)));
}
}
}
| mit | C# |
3cf7b2a0f0ceb272a0a7807c322586276d9f3d19 | Fix code analysis | github/VisualStudio,naveensrinivasan/VisualStudio,amytruong/VisualStudio,luizbon/VisualStudio,pwz3n0/VisualStudio,github/VisualStudio,github/VisualStudio,HeadhunterXamd/VisualStudio,bradthurber/VisualStudio | src/GitHub.VisualStudio/Base/TeamExplorerBase.cs | src/GitHub.VisualStudio/Base/TeamExplorerBase.cs | using System;
using System.ComponentModel;
using System.Diagnostics;
using GitHub.Primitives;
using NullGuard;
using GitHub.Services;
namespace GitHub.VisualStudio.Base
{
public abstract class TeamExplorerBase : NotificationAwareObject, IDisposable
{
internal static readonly Guid TeamExplorerConnectionsSectionId = new Guid("ef6a7a99-f01f-4c91-ad31-183c1354dd97");
[AllowNull]
protected IServiceProvider ServiceProvider
{
[return: AllowNull]
get; set;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
[return: AllowNull]
public T GetService<T>()
{
Debug.Assert(ServiceProvider != null, "GetService<T> called before service provider is set");
if (ServiceProvider == null)
return default(T);
return (T)ServiceProvider.GetService(typeof(T));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[return: AllowNull]
public Ret GetService<T, Ret>() where Ret : class
{
return GetService<T>() as Ret;
}
protected static void OpenInBrowser(Lazy<IVisualStudioBrowser> browser, Uri uri)
{
OpenInBrowser(browser.Value, uri);
}
protected static void OpenInBrowser(IVisualStudioBrowser browser, Uri uri)
{
Debug.Assert(browser != null, "Could not create a browser helper instance.");
browser?.OpenUrl(uri);
}
}
}
| using System;
using System.ComponentModel;
using System.Diagnostics;
using GitHub.Primitives;
using NullGuard;
using GitHub.Services;
namespace GitHub.VisualStudio.Base
{
public abstract class TeamExplorerBase : NotificationAwareObject, IDisposable
{
internal static readonly Guid TeamExplorerConnectionsSectionId = new Guid("ef6a7a99-f01f-4c91-ad31-183c1354dd97");
[AllowNull]
protected IServiceProvider ServiceProvider
{
[return: AllowNull]
get; set;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
[return: AllowNull]
public T GetService<T>()
{
Debug.Assert(ServiceProvider != null, "GetService<T> called before service provider is set");
if (ServiceProvider == null)
return default(T);
return (T)ServiceProvider.GetService(typeof(T));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
[return: AllowNull]
public Ret GetService<T, Ret>() where Ret : class
{
return GetService<T>() as Ret;
}
protected void OpenInBrowser(Lazy<IVisualStudioBrowser> browser, Uri uri)
{
OpenInBrowser(browser.Value, uri);
}
protected void OpenInBrowser(IVisualStudioBrowser browser, Uri uri)
{
Debug.Assert(browser != null, "Could not create a browser helper instance.");
browser?.OpenUrl(uri);
}
}
}
| mit | C# |
46f2a66a6f94bca714357823801be3b5f9b644ab | Add extension methods | takeshik/linx | Linx/Extension/StreamUtil.cs | Linx/Extension/StreamUtil.cs | // -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
// vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et:
// $Id: a7db7754a428ebb526d000b64ab4e48866a29032 $
/* Linx
* Library that Integrates .NET with eXtremes
* Copyright © 2008-2010 Takeshi KIRIYA (aka takeshik) <takeshik@users.sf.net>
* All rights reserved.
*
* This file is part of Linx.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace XSpect.Extension
{
public static class StreamUtil
{
public static Byte[] ReadAll(this Stream stream)
{
Byte[] buffer = new Byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
return buffer;
}
public static Byte[] ReadAll(this Stream stream, Int32 bufferSize)
{
IEnumerable<Byte> ret = Enumerable.Empty<Byte>();
Byte[] buffer = new Byte[bufferSize];
for (Int32 length; (length = stream.Read(buffer, 0, bufferSize)) != 0; )
{
ret = ret.Concat(buffer.Take(length).ToArray());
if (length < bufferSize)
{
break;
}
}
return ret.ToArray();
}
public static Int32 Read(this Stream stream, Byte[] buffer)
{
return stream.Read(buffer, 0, buffer.Length);
}
public static void Write(this Stream stream, Byte[] buffer)
{
stream.Write(buffer, 0, buffer.Length);
}
}
} | // -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
// vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et:
// $Id: a7db7754a428ebb526d000b64ab4e48866a29032 $
/* Linx
* Library that Integrates .NET with eXtremes
* Copyright © 2008-2010 Takeshi KIRIYA (aka takeshik) <takeshik@users.sf.net>
* All rights reserved.
*
* This file is part of Linx.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
namespace XSpect.Extension
{
public static class StreamUtil
{
public static Byte[] ReadAll(this Stream stream)
{
Byte[] buffer = new Byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
return buffer;
}
public static Byte[] ReadAll(this Stream stream, Int32 bufferSize)
{
IEnumerable<Byte> ret = Enumerable.Empty<Byte>();
Byte[] buffer = new Byte[bufferSize];
for (Int32 length; (length = stream.Read(buffer, 0, bufferSize)) != 0; )
{
ret = ret.Concat(buffer.Take(length).ToArray());
if (length < bufferSize)
{
break;
}
}
return ret.ToArray();
}
}
} | mit | C# |
1d4a54af4735ef71ca0683897598604ae742105b | Change to CreateFile for existance checking | jonstodle/mowali | Mowali/SettingsWrapper.cs | Mowali/SettingsWrapper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using TmdbWrapper;
using TmdbWrapper.Movies;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Mowali {
public sealed class SettingsWrapper {
const string DATA_FILE_NAME = "data.mwl";
static ApplicationDataContainer roamingSettings;
static StorageFolder localFolder;
static ObservableCollection<Movie> toWatchList;
static ObservableCollection<Movie> watchedList;
#region Class initialization
static SettingsWrapper() {
roamingSettings = ApplicationData.Current.RoamingSettings;
localFolder = ApplicationData.Current.LocalFolder;
LoadDataFile();
}
async static void LoadDataFile() {
var dataFile = await localFolder.CreateFileAsync(DATA_FILE_NAME, CreationCollisionOption.OpenIfExists);
var json = await FileIO.ReadTextAsync(dataFile);
JObject obj = JObject.Parse(json);
toWatchList = await JsonConvert.DeserializeObjectAsync<ObservableCollection<Movie>>((string)obj["ToWatch"]);
watchedList = await JsonConvert.DeserializeObjectAsync<ObservableCollection<Movie>>((string)obj["Watched"]);
}
public async static void saveDataFile(){
string dataJson = await JsonConvert.SerializeObjectAsync(new { ToWatch = toWatchList, Watched = watchedList });
var dataFile = await localFolder.CreateFileAsync(DATA_FILE_NAME, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(dataFile, dataJson);
}
#endregion
public static ObservableCollection<Movie> ToWatchList {
get {
return toWatchList;
}
}
public static ObservableCollection<Movie> WatchedList {
get {
return watchedList;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using TmdbWrapper;
using TmdbWrapper.Movies;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Mowali {
public sealed class SettingsWrapper {
const string DATA_FILE_NAME = "data.mwl";
static ApplicationDataContainer roamingSettings;
static StorageFolder localFolder;
static ObservableCollection<Movie> toWatchList;
static ObservableCollection<Movie> watchedList;
#region Class initialization
static SettingsWrapper() {
roamingSettings = ApplicationData.Current.RoamingSettings;
localFolder = ApplicationData.Current.LocalFolder;
LoadDataFile();
}
async static void LoadDataFile() {
var dataFile = await localFolder.GetFileAsync(DATA_FILE_NAME);
var json = await FileIO.ReadTextAsync(dataFile);
JObject obj = JObject.Parse(json);
toWatchList = await JsonConvert.DeserializeObjectAsync<ObservableCollection<Movie>>((string)obj["ToWatch"]);
watchedList = await JsonConvert.DeserializeObjectAsync<ObservableCollection<Movie>>((string)obj["Watched"]);
}
public async static void saveDataFile(){
string dataJson = await JsonConvert.SerializeObjectAsync(new { ToWatch = toWatchList, Watched = watchedList });
var dataFile = await localFolder.CreateFileAsync(DATA_FILE_NAME, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(dataFile, dataJson);
}
#endregion
public static ObservableCollection<Movie> ToWatchList {
get {
return toWatchList;
}
}
public static ObservableCollection<Movie> WatchedList {
get {
return watchedList;
}
}
}
}
| mit | C# |
4ba682f0d462a3681fa0a23e7a588e82786fef37 | fix multiple concurrent download of sysmsg | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Parsing/Messages/C_LOGIN_ARBITER.cs | TCC.Core/Parsing/Messages/C_LOGIN_ARBITER.cs | using TCC.Data;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class C_LOGIN_ARBITER : ParsedMessage
{
public string AccountName { get; }
public LangEnum Language { get; set; }
public int Version { get; set; }
public C_LOGIN_ARBITER(TeraMessageReader reader) : base(reader)
{
var nameOffset = reader.ReadUInt16();
reader.Skip(9);
Language = (LangEnum)reader.ReadUInt32();
Version = reader.ReadInt32();
reader.RepositionAt(nameOffset);
AccountName = reader.ReadTeraString();
reader.Factory.ReleaseVersion = Version;
}
}
}
| using TCC.Data;
using TCC.TeraCommon.Game.Messages;
using TCC.TeraCommon.Game.Services;
namespace TCC.Parsing.Messages
{
public class C_LOGIN_ARBITER : ParsedMessage
{
public string AccountName { get; }
public LangEnum Language { get; set; }
public int Version { get; set; }
public C_LOGIN_ARBITER(TeraMessageReader reader) : base(reader)
{
var nameOffset = reader.ReadUInt16();
reader.Skip(9);
Language = (LangEnum)reader.ReadUInt32();
Version = reader.ReadInt32();
reader.RepositionAt(nameOffset);
AccountName = reader.ReadTeraString();
reader.Factory.ReleaseVersion = Version;
reader.Factory.ReloadSysMsg();
}
}
}
| mit | C# |
ce85afc3846e7e35a6d85fe44c3479f91d6b0484 | Add JsonConstructor | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Models/SerializableException.cs | WalletWasabi/Models/SerializableException.cs | using Newtonsoft.Json;
using System;
using System.Text;
namespace WalletWasabi.Models
{
[JsonObject(MemberSerialization.OptIn)]
public record SerializableException
{
[JsonConstructor]
protected SerializableException(string exceptionType, string message, string stackTrace, SerializableException innerException)
{
ExceptionType = exceptionType;
Message = message;
StackTrace = stackTrace;
InnerException = innerException;
}
public SerializableException(Exception ex)
{
if (ex.InnerException is { })
{
InnerException = new SerializableException(ex.InnerException);
}
ExceptionType = ex.GetType().FullName;
Message = ex.Message;
StackTrace = ex.StackTrace;
}
[JsonProperty(PropertyName = "ExceptionType")]
public string? ExceptionType { get; }
[JsonProperty(PropertyName = "Message")]
public string Message { get; }
[JsonProperty(PropertyName = "StackTrace")]
public string? StackTrace { get; }
[JsonProperty(PropertyName = "InnerException")]
public SerializableException? InnerException { get; }
public static string ToBase64String(SerializableException exception)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(exception)));
}
public static SerializableException FromBase64String(string base64String)
{
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
return JsonConvert.DeserializeObject<SerializableException>(json);
}
}
}
| using Newtonsoft.Json;
using System;
using System.Text;
namespace WalletWasabi.Models
{
[JsonObject(MemberSerialization.OptIn)]
public record SerializableException
{
public SerializableException()
{
}
public SerializableException(Exception ex)
{
if (ex.InnerException is { })
{
InnerException = new SerializableException(ex.InnerException);
}
ExceptionType = ex.GetType().FullName;
Message = ex.Message;
StackTrace = ex.StackTrace;
}
[JsonProperty(PropertyName = "ExceptionType")]
public string? ExceptionType { get; private set; }
[JsonProperty(PropertyName = "Message")]
public string? Message { get; private set; }
[JsonProperty(PropertyName = "StackTrace")]
public string? StackTrace { get; private set; }
[JsonProperty(PropertyName = "InnerException")]
public SerializableException? InnerException { get; private set; }
public static string ToBase64String(SerializableException exception)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(exception)));
}
public static SerializableException FromBase64String(string base64String)
{
var json = Encoding.UTF8.GetString(Convert.FromBase64String(base64String));
return JsonConvert.DeserializeObject<SerializableException>(json);
}
}
}
| mit | C# |
d5d75008172ad890c893353eeabe889168dbbb54 | Correct typeo. | sharpjs/PSql,sharpjs/PSql | PSql/_Data/AzureSqlContext.cs | PSql/_Data/AzureSqlContext.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Data.SqlClient;
namespace PSql
{
/// <summary>
/// Information necessary to connect to an Azure SQL Database or
/// compatible database.
/// </summary>
public class AzureSqlContext : SqlContext
{
public AzureSqlContext()
{
EncryptionMode = EncryptionMode.Full;
}
public string ResourceGroupName { get; set; }
public string ServerFullName { get; private set; }
protected override void BuildConnectionString(SqlConnectionStringBuilder builder)
{
if (Credential.IsNullOrEmpty())
throw new NotSupportedException("A credential is required when connecting to Azure SQL Database.");
base.BuildConnectionString(builder);
builder.DataSource = ServerFullName ?? ResolveServerFullName();
if (string.IsNullOrEmpty(DatabaseName))
builder.InitialCatalog = MasterDatabaseName;
}
protected override void ConfigureEncryption(SqlConnectionStringBuilder builder)
{
builder.Encrypt = true;
}
private string ResolveServerFullName()
{
var value = ScriptBlock
.Create("param ($x) Get-AzSqlServer @x -ea Stop")
.Invoke(new Dictionary<string, object>
{
["ResourceGroupName"] = ResourceGroupName,
["ServerName"] = ServerName,
})
.FirstOrDefault()
?.Properties["FullyQualifiedDomainName"]
?.Value as string;
if (string.IsNullOrEmpty(value))
throw new InvalidOperationException(
"The Get-AzSqlServer command completed without error, " +
"but did not yield an object with a FullyQualifiedDomainName " +
"property set to a non-null, non-empty string."
);
return ServerFullName = value;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Data.SqlClient;
namespace PSql
{
/// <summary>
/// Information necessary to connect to an Azyure SQL Database or
/// compatible database.
/// </summary>
public class AzureSqlContext : SqlContext
{
public AzureSqlContext()
{
EncryptionMode = EncryptionMode.Full;
}
public string ResourceGroupName { get; set; }
public string ServerFullName { get; private set; }
protected override void BuildConnectionString(SqlConnectionStringBuilder builder)
{
if (Credential.IsNullOrEmpty())
throw new NotSupportedException("A credential is required when connecting to Azure SQL Database.");
base.BuildConnectionString(builder);
builder.DataSource = ServerFullName ?? ResolveServerFullName();
if (string.IsNullOrEmpty(DatabaseName))
builder.InitialCatalog = MasterDatabaseName;
}
protected override void ConfigureEncryption(SqlConnectionStringBuilder builder)
{
builder.Encrypt = true;
}
private string ResolveServerFullName()
{
var value = ScriptBlock
.Create("param ($x) Get-AzSqlServer @x -ea Stop")
.Invoke(new Dictionary<string, object>
{
["ResourceGroupName"] = ResourceGroupName,
["ServerName"] = ServerName,
})
.FirstOrDefault()
?.Properties["FullyQualifiedDomainName"]
?.Value as string;
if (string.IsNullOrEmpty(value))
throw new InvalidOperationException(
"The Get-AzSqlServer command completed without error, " +
"but did not yield an object with a FullyQualifiedDomainName " +
"property set to a non-null, non-empty string."
);
return ServerFullName = value;
}
}
}
| isc | C# |
0692f017e10d821fbb8a8e9e14b66e854cf0f628 | Fix html enconded characters in plain text | janabimustafa/waslibs,pellea/waslibs,wasteam/waslibs,pellea/waslibs,pellea/waslibs,wasteam/waslibs,janabimustafa/waslibs,janabimustafa/waslibs,wasteam/waslibs | src/AppStudio.Uwp/Html/HtmlText.cs | src/AppStudio.Uwp/Html/HtmlText.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace AppStudio.Uwp.Html
{
public sealed class HtmlText : HtmlFragment
{
private string _content;
public string Content
{
get
{
return _content;
}
set
{
_content = WebUtility.HtmlDecode(value);
}
}
public HtmlText()
{
Name = "text";
}
public HtmlText(string doc, int startIndex, int endIndex) : this()
{
if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0)
{
Content = doc.Substring(startIndex, endIndex - startIndex);
}
}
public override string ToString()
{
return Content;
}
internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag)
{
var startIndex = 0;
if (startTag != null)
{
startIndex = startTag.StartIndex + startTag.Length;
}
var endIndex = doc.Length;
if (endTag != null)
{
endIndex = endTag.StartIndex;
}
var text = new HtmlText(doc, startIndex, endIndex);
if (text != null && !string.IsNullOrEmpty(text.Content))
{
return text;
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace AppStudio.Uwp.Html
{
public sealed class HtmlText : HtmlFragment
{
public string Content { get; set; }
public HtmlText()
{
Name = "text";
}
public HtmlText(string doc, int startIndex, int endIndex) : this()
{
if (!string.IsNullOrEmpty(doc) && endIndex - startIndex > 0)
{
Content = WebUtility.HtmlDecode(doc.Substring(startIndex, endIndex - startIndex));
}
}
public override string ToString()
{
return Content;
}
internal static HtmlText Create(string doc, HtmlTag startTag, HtmlTag endTag)
{
var startIndex = 0;
if (startTag != null)
{
startIndex = startTag.StartIndex + startTag.Length;
}
var endIndex = doc.Length;
if (endTag != null)
{
endIndex = endTag.StartIndex;
}
var text = new HtmlText(doc, startIndex, endIndex);
if (text != null && !string.IsNullOrEmpty(text.Content))
{
return text;
}
return null;
}
}
}
| mit | C# |
48668265634fcb1eb3b93f7cfdfe505d75401da1 | test change | JoinPatterns/ScalableJoins | Samples/Buffer/Program.cs | Samples/Buffer/Program.cs | //------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <disclaimer>
// THIS CODE AND INFORMATION ARE 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.
// </disclaimer>
//------------------------------------------------------------------------------
using System;
using System.Threading;
using Microsoft.Research.Joins;
//some examples
namespace Buffer {
class Buffer {
// Declare the (a)synchronous channels
public readonly Asynchronous.Channel<string> Put;
public readonly Synchronous<string>.Channel Get;
public Buffer() {
// Allocate a new Join object for this buffer
Join join = Join.Create();
// Use it to initialize the channels
join.Initialize(out Put);
join.Initialize(out Get);
// Finally, declare the patterns(s)
join.When(Get).And(Put).Do(delegate(String s) {
return s;
});
}
}
/* client code */
class Program {
static Buffer b = new Buffer();
static void Producer() {
Console.WriteLine("Producer Started");
for (int i = 0; i < 20; i++) {
b.Put(i.ToString());
Console.WriteLine("Produced!{0}", i);
Thread.Sleep(10);
}
}
static void Consumer() {
Console.WriteLine("Consumer Started");
for (int i = 0; i < 20; i++) {
string s = b.Get();
Console.WriteLine("Consumed?{0}", s);
Thread.Sleep(8);
}
Console.WriteLine("Done Consuming");
}
public static void Main() {
Thread producer = new Thread(new ThreadStart(Producer));
Thread consumer = new Thread(new ThreadStart(Consumer));
producer.Start();
consumer.Start();
consumer.Join();
Console.WriteLine("Hit return to exit");
System.Console.ReadLine();
}
}
}
| //------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <disclaimer>
// THIS CODE AND INFORMATION ARE 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.
// </disclaimer>
//------------------------------------------------------------------------------
using System;
using System.Threading;
using Microsoft.Research.Joins;
namespace Buffer {
class Buffer {
// Declare the (a)synchronous channels
public readonly Asynchronous.Channel<string> Put;
public readonly Synchronous<string>.Channel Get;
public Buffer() {
// Allocate a new Join object for this buffer
Join join = Join.Create();
// Use it to initialize the channels
join.Initialize(out Put);
join.Initialize(out Get);
// Finally, declare the patterns(s)
join.When(Get).And(Put).Do(delegate(String s) {
return s;
});
}
}
/* client code */
class Program {
static Buffer b = new Buffer();
static void Producer() {
Console.WriteLine("Producer Started");
for (int i = 0; i < 20; i++) {
b.Put(i.ToString());
Console.WriteLine("Produced!{0}", i);
Thread.Sleep(10);
}
}
static void Consumer() {
Console.WriteLine("Consumer Started");
for (int i = 0; i < 20; i++) {
string s = b.Get();
Console.WriteLine("Consumed?{0}", s);
Thread.Sleep(8);
}
Console.WriteLine("Done Consuming");
}
public static void Main() {
Thread producer = new Thread(new ThreadStart(Producer));
Thread consumer = new Thread(new ThreadStart(Consumer));
producer.Start();
consumer.Start();
consumer.Join();
Console.WriteLine("Hit return to exit");
System.Console.ReadLine();
}
}
}
| mit | C# |
b3bc183961b7bfd99a36ab28158608546ed9bf98 | Update ProtectingSpecificRowInWorksheet.cs | aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Worksheets/Security/Protecting/ProtectingSpecificRowInWorksheet.cs | Examples/CSharp/Worksheets/Security/Protecting/ProtectingSpecificRowInWorksheet.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security.Protecting
{
public class ProtectingSpecificRowInWorksheet
{
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);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Create a new workbook.
Workbook wb = new Workbook();
// Create a worksheet object and obtain the first sheet.
Worksheet sheet = wb.Worksheets[0];
// Define the style object.
Style style;
// Define the styleflag object.
StyleFlag flag;
// Loop through all the columns in the worksheet and unlock them.
for (int i = 0; i <= 255; i++)
{
style = sheet.Cells.Columns[(byte)i].Style;
style.IsLocked = false;
flag = new StyleFlag();
flag.Locked = true;
sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag);
}
// Get the first row style.
style = sheet.Cells.Rows[0].Style;
// Lock it.
style.IsLocked = true;
// Instantiate the flag.
flag = new StyleFlag();
// Set the lock setting.
flag.Locked = true;
// Apply the style to the first row.
sheet.Cells.ApplyRowStyle(0, style, flag);
// Protect the sheet.
sheet.Protect(ProtectionType.All);
// Save the excel file.
wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security.Protecting
{
public class ProtectingSpecificRowInWorksheet
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Create a new workbook.
Workbook wb = new Workbook();
// Create a worksheet object and obtain the first sheet.
Worksheet sheet = wb.Worksheets[0];
// Define the style object.
Style style;
// Define the styleflag object.
StyleFlag flag;
// Loop through all the columns in the worksheet and unlock them.
for (int i = 0; i <= 255; i++)
{
style = sheet.Cells.Columns[(byte)i].Style;
style.IsLocked = false;
flag = new StyleFlag();
flag.Locked = true;
sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag);
}
// Get the first row style.
style = sheet.Cells.Rows[0].Style;
// Lock it.
style.IsLocked = true;
// Instantiate the flag.
flag = new StyleFlag();
// Set the lock setting.
flag.Locked = true;
// Apply the style to the first row.
sheet.Cells.ApplyRowStyle(0, style, flag);
// Protect the sheet.
sheet.Protect(ProtectionType.All);
// Save the excel file.
wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003);
}
}
} | mit | C# |
f0da32c4ba1d6a55cf20022b6a45fecfafaba95f | Allow model config to be modified | visualeyes/halcyon | src/Halcyon/HAL/IHALModelConfig.cs | src/Halcyon/HAL/IHALModelConfig.cs | namespace Halcyon.HAL {
public interface IHALModelConfig {
string LinkBase { get; set; }
bool ForceHAL { get; set; }
}
} | namespace Halcyon.HAL {
public interface IHALModelConfig {
string LinkBase { get; }
bool ForceHAL { get; }
}
} | mit | C# |
faf66493eb03bb9385dbe52b5c1513d29737b157 | Remove not used using | marska/habitrpg-api-dotnet-client | src/HabitRPG.Client/Model/Habit.cs | src/HabitRPG.Client/Model/Habit.cs | using System.Collections.Generic;
using Newtonsoft.Json;
namespace HabitRPG.Client.Model
{
public class Habit : Task
{
public override string Type
{
get { return "habit"; }
}
public Habit()
{
Up = true;
Down = true;
}
[JsonProperty("history")]
public List<History> History { get; set; }
[JsonProperty("up")]
public bool Up { get; set; }
[JsonProperty("down")]
public bool Down { get; set; }
}
} | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace HabitRPG.Client.Model
{
public class Habit : Task
{
public override string Type
{
get { return "habit"; }
}
public Habit()
{
Up = true;
Down = true;
}
[JsonProperty("history")]
public List<History> History { get; set; }
[JsonProperty("up")]
public bool Up { get; set; }
[JsonProperty("down")]
public bool Down { get; set; }
}
} | apache-2.0 | C# |
e49aac33fb9995ed4f17549d2a983c47e9ed7501 | Change the behavior of the object serializer so that objects are initialized with values instead of Nulls | tekbird/LoveSeat | LoveSeat/ObjectSerializer.cs | LoveSeat/ObjectSerializer.cs | using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace LoveSeat
{
public interface IObjectSerializer<T>
{
T Deserialize(string json);
string Serialize(object obj);
}
public class ObjectSerializer<T> : IObjectSerializer<T>
{
protected readonly JsonSerializerSettings settings;
public ObjectSerializer()
{
settings = new JsonSerializerSettings();
var converters = new List<JsonConverter> { new IsoDateTimeConverter() };
settings.Converters = converters;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Include;
}
public virtual T Deserialize(string json)
{
return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings);
}
public virtual string Serialize(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev");
}
}
} | using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace LoveSeat
{
public interface IObjectSerializer<T>
{
T Deserialize(string json);
string Serialize(object obj);
}
public class ObjectSerializer<T> : IObjectSerializer<T>
{
protected readonly JsonSerializerSettings settings;
public ObjectSerializer()
{
settings = new JsonSerializerSettings();
var converters = new List<JsonConverter> { new IsoDateTimeConverter() };
settings.Converters = converters;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;
}
public virtual T Deserialize(string json)
{
return JsonConvert.DeserializeObject<T>(json.Replace("_id", "id").Replace("_rev", "rev"), settings);
}
public virtual string Serialize(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, settings).Replace("id", "_id").Replace("rev", "_rev");
}
}
} | mit | C# |
fc36b7db7b0906cb1d729a45580a4396cae5246a | Add test for 2000 (MM) - this should have been done before adding loop for M. | pvasys/PillarRomanNumeralKata | VasysRomanNumeralsKataTest/ToRomanNumeralsTest.cs | VasysRomanNumeralsKataTest/ToRomanNumeralsTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VasysRomanNumeralsKata;
namespace VasysRomanNumeralsKataTest
{
[TestClass]
public class ToRomanNumeralsTest
{
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
{
int ten = 10;
Assert.IsTrue(ten.ToRomanNumeral() == "X");
}
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
{
int oneThousand = 1000;
Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
int nineHundred = 900;
Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
int fiveHundred = 500;
Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
int fourHundred = 400;
Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
int oneHundred = 100;
Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
int twoHundred = 200;
Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
int threeHundred = 300;
Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
int twoThousand = 2000;
Assert.IsTrue(twoThousand.ToRomanNumeral() == "MM");
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VasysRomanNumeralsKata;
namespace VasysRomanNumeralsKataTest
{
[TestClass]
public class ToRomanNumeralsTest
{
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedTenItReturnsX()
{
int ten = 10;
Assert.IsTrue(ten.ToRomanNumeral() == "X");
}
[TestMethod]
public void WhenRomanNumeralExtensionIsPassedNumbersDivisibleByOneHundredItReturnsARomanNumeral()
{
int oneThousand = 1000;
Assert.IsTrue(oneThousand.ToRomanNumeral() == "M");
int nineHundred = 900;
Assert.IsTrue(nineHundred.ToRomanNumeral() == "CM");
int fiveHundred = 500;
Assert.IsTrue(fiveHundred.ToRomanNumeral() == "D");
int fourHundred = 400;
Assert.IsTrue(fourHundred.ToRomanNumeral() == "CD");
int oneHundred = 100;
Assert.IsTrue(oneHundred.ToRomanNumeral() == "C");
int twoHundred = 200;
Assert.IsTrue(twoHundred.ToRomanNumeral() == "CC");
int threeHundred = 300;
Assert.IsTrue(threeHundred.ToRomanNumeral() == "CCC");
}
}
}
| mit | C# |
d31196c5b3a60042ead3a553b313765f1aca6dc5 | Fix logging issue | PolemoIDE/Polemo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node | src/Polemo.NetCore.Node/Startup.cs | src/Polemo.NetCore.Node/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Polemo.NetCore.Node
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddConfiguration();
services.AddCors(c => c.AddPolicy("Polemo", x =>
x.AllowCredentials()
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
));
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
services.AddLogging();
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
app.UseCors("Polemo");
app.UseSignalR();
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Polemo.NetCore.Node
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddConfiguration();
services.AddCors(c => c.AddPolicy("Polemo", x =>
x.AllowCredentials()
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
));
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
app.UseCors("Polemo");
app.UseSignalR();
loggerFactory.AddConsole(LogLevel.Debug);
}
}
}
| mit | C# |
32b01face558530aeab410ab51bfd3864f609346 | convert TODO to issue #142 | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | src/FilterLists.Api/Controllers/ListsController.cs | src/FilterLists.Api/Controllers/ListsController.cs | using FilterLists.Services.Contracts;
using Microsoft.AspNetCore.Mvc;
namespace FilterLists.Api.Controllers
{
[Route("v1/[controller]")]
[Produces("application/json")]
public class ListsController : Controller
{
private readonly IFilterListService filterListService;
public ListsController(IFilterListService filterListService)
{
this.filterListService = filterListService;
}
/// <summary>
/// Get Lists
/// </summary>
/// <returns>All FilterLists</returns>
[HttpGet]
public IActionResult Get()
{
return Json(filterListService.GetAll());
}
}
} | using FilterLists.Services.Contracts;
using Microsoft.AspNetCore.Mvc;
namespace FilterLists.Api.Controllers
{
//TODO: migrate controllers to separate projects by version, use dependency injection
//TODO: automate URL versioning
[Route("v1/[controller]")]
[Produces("application/json")]
public class ListsController : Controller
{
private readonly IFilterListService filterListService;
public ListsController(IFilterListService filterListService)
{
this.filterListService = filterListService;
}
/// <summary>
/// Get Lists
/// </summary>
/// <returns>All FilterLists</returns>
[HttpGet]
public IActionResult Get()
{
return Json(filterListService.GetAll());
}
}
} | mit | C# |
272d575f8807d9b36511446d9d8db896b0091f2e | use Parallel.ForEach | vinhch/SimpleScheduler | SimpleScheduler/JobManager.cs | SimpleScheduler/JobManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleScheduler
{
public class JobManager
{
private IEnumerable<JobInfo> _listOfJobInfo;
public JobManager()
{
}
public void ExecuteAllJobs()
{
if (_listOfJobInfo == null || _listOfJobInfo.Count() <= 0)
{
return;
}
//foreach (var jobInfo in _listOfJobInfo)
//{
// var jobThread = new Thread(new ThreadStart(jobInfo.ExecuteJob));
//}
Parallel.ForEach(_listOfJobInfo.Where(s => s.Enabled), jobInfo =>
{
var jobThread = new Thread(new ThreadStart(jobInfo.ExecuteJob));
jobThread.Start();
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SimpleScheduler
{
public class JobManager
{
private IEnumerable<JobInfo> _listOfJobInfo;
public JobManager()
{
}
public void ExecuteAllJobs()
{
if (_listOfJobInfo == null || _listOfJobInfo.Count() <= 0)
{
return;
}
foreach (var jobInfo in _listOfJobInfo)
{
var jobThread = new Thread(new ThreadStart(jobInfo.ExecuteJob));
}
}
}
}
| mit | C# |
9db36169b39e92e1dc3632097ab7e792ed0f7162 | Implement LocatorBasedDispatcher tests. | yonglehou/msgpack-rpc-cli,yfakariya/msgpack-rpc-cli | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Dispatch/LocatorBasedDispatcherTest.cs | test/MsgPack.Rpc.Server.UnitTest/Rpc/Server/Dispatch/LocatorBasedDispatcherTest.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.IO;
using System.Threading;
using MsgPack.Rpc.Server.Protocols;
using NUnit.Framework;
using System.Globalization;
namespace MsgPack.Rpc.Server.Dispatch
{
/// <summary>
///Tests the Locator Based Dispatcher
/// </summary>
[TestFixture()]
public class LocatorBasedDispatcherTest
{
[Test]
public void TestDispatch_MethodExists_Success()
{
var svcFile = ".\\Services.svc";
File.WriteAllText(
svcFile,
String.Format( CultureInfo.InvariantCulture, "<% @ ServiceHost Service=\"{0}\" %>", typeof( TestService ).FullName )
);
try
{
var configuration = new RpcServerConfiguration();
configuration.ServiceTypeLocatorProvider = conf => new FileBasedServiceTypeLocator();
using ( var server = new RpcServer( configuration ) )
using ( var transportManager = new NullServerTransportManager( server ) )
using ( var transport = new NullServerTransport( transportManager ) )
using ( var requestContext = DispatchTestHelper.CreateRequestContext() )
using ( var argumentsBuffer = new MemoryStream() )
using ( var waitHandle = new ManualResetEventSlim() )
{
var message = Guid.NewGuid().ToString();
using ( var argumentsPacker = Packer.Create( argumentsBuffer, false ) )
{
argumentsPacker.PackArrayHeader( 1 );
argumentsPacker.Pack( message );
}
argumentsBuffer.Position = 0;
var target = new LocatorBasedDispatcher( server );
MessagePackObject response = MessagePackObject.Nil;
requestContext.MethodName = "Echo:TestService:1";
requestContext.MessageId = 1;
requestContext.SetTransport( transport );
requestContext.ArgumentsUnpacker = Unpacker.Create( argumentsBuffer );
transport.Sent +=
( sender, e ) =>
{
response = Unpacking.UnpackString( e.Context.GetReturnValueData() ).Value;
waitHandle.Set();
};
target.Dispatch( transport, requestContext );
Assert.That( waitHandle.Wait( TimeSpan.FromSeconds( 1 ) ) );
Assert.That( message == response, "{0} != {1}", message, response );
}
}
finally
{
File.Delete( svcFile );
}
}
[Test]
public void TestDispatch_MethodNotExists_NoMethodError()
{
using ( var server = new RpcServer() )
using ( var transportManager = new NullServerTransportManager( server ) )
using ( var transport = new NullServerTransport( transportManager ) )
using ( var requestContext = DispatchTestHelper.CreateRequestContext() )
using ( var argumentsBuffer = new MemoryStream() )
using ( var waitHandle = new ManualResetEventSlim() )
{
var message = Guid.NewGuid().ToString();
using ( var argumentsPacker = Packer.Create( argumentsBuffer, false ) )
{
argumentsPacker.PackArrayHeader( 1 );
argumentsPacker.Pack( message );
}
argumentsBuffer.Position = 0;
var target = new LocatorBasedDispatcher( server );
MessagePackObject response = MessagePackObject.Nil;
requestContext.MethodName = "Echo:TestServices:1";
requestContext.MessageId = 1;
requestContext.SetTransport( transport );
requestContext.ArgumentsUnpacker = Unpacker.Create( argumentsBuffer );
transport.Sent +=
( sender, e ) =>
{
response = Unpacking.UnpackString( e.Context.GetErrorData() ).Value;
waitHandle.Set();
};
target.Dispatch( transport, requestContext );
Assert.That( waitHandle.Wait( TimeSpan.FromSeconds( 1 ) ) );
Assert.That( RpcError.NoMethodError.Identifier == response, "{0} != {1}", message, response );
}
}
}
[MessagePackRpcServiceContract( Name = "TestService", Version = 1 )]
public sealed class TestService
{
[MessagePackRpcMethod]
public string Echo( string message )
{
return message;
}
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using NUnit.Framework;
namespace MsgPack.Rpc.Server.Dispatch
{
/// <summary>
///Tests the Locator Based Dispatcher
/// </summary>
[TestFixture()]
public class LocatorBasedDispatcherTest
{
// FIXME: Tests as facade.
}
}
| apache-2.0 | C# |
6a98d0ee849ed88ace70ba7132b02aeda49c1f50 | Fix editMetadata button | andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop | src/BloomExe/ElementProxy.cs | src/BloomExe/ElementProxy.cs | using System;
using System.Xml;
using Gecko;
using Palaso.Code;
namespace Bloom
{
/// <summary>
/// Takes a Gecko element or an XmlElement, and then provides a few simple operations on
/// the element so that the client doesn't have to know which it has.
/// This is useful because it would be hard to introduce gecko elements in many simple
/// unit tests.
/// </summary>
public class ElementProxy
{
private readonly GeckoHtmlElement _geckoElement;
private readonly XmlElement _xmlElement;
public ElementProxy(GeckoHtmlElement element)
{
_geckoElement = element;
}
public ElementProxy(XmlElement element)
{
Guard.AgainstNull(element, "element");
_xmlElement = element;
}
/// <summary>
/// Sets the named attribute
/// </summary>
public void SetAttribute(string attributeName, string value)
{
if (_xmlElement == null)
{
_geckoElement.SetAttribute(attributeName, value);
}
else
{
_xmlElement.SetAttribute(attributeName, value);
}
}
/// <summary>
/// Gets the class name
/// </summary>
public string Name
{
get
{
if (_xmlElement == null)
{
return _geckoElement.NodeName;
}
else
{
return _xmlElement.Name;
}
}
}
/// <summary>
/// Gets the named attribute
/// </summary>
/// <returns>An empty string is returned if a matching attribute is not found or if the attribute does not have a specified or default value.</returns>
public string GetAttribute(string attributeName)
{
if (_xmlElement == null)
{
return _geckoElement.GetAttribute(attributeName);
}
else
{
return _xmlElement.GetAttribute(attributeName);
}
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
protected bool Equals(UrlPathString other)
{
throw new NotImplementedException();
}
public static bool operator ==(ElementProxy a, ElementProxy b)
{
throw new NotImplementedException();
}
public static bool operator !=(ElementProxy a, ElementProxy b)
{
throw new NotImplementedException();
}
}
} | using System;
using System.Xml;
using Gecko;
using Palaso.Code;
namespace Bloom
{
/// <summary>
/// Takes a Gecko element or an XmlElement, and then provides a few simple operations on
/// the element so that the client doesn't have to know which it has.
/// This is useful because it would be hard to introduce gecko elements in many simple
/// unit tests.
/// </summary>
public class ElementProxy
{
private readonly GeckoHtmlElement _geckoElement;
private readonly XmlElement _xmlElement;
public ElementProxy(GeckoHtmlElement element)
{
_geckoElement = element;
}
public ElementProxy(XmlElement element)
{
Guard.AgainstNull(element, "element");
_xmlElement = element;
}
/// <summary>
/// Sets the named attribute
/// </summary>
public void SetAttribute(string attributeName, string value)
{
if (_xmlElement == null)
{
_geckoElement.SetAttribute(attributeName, value);
}
else
{
_xmlElement.SetAttribute(attributeName, value);
}
}
/// <summary>
/// Gets the class name
/// </summary>
public string Name
{
get
{
if (_xmlElement == null)
{
return _geckoElement.ClassName;
}
else
{
return _xmlElement.Name;
}
}
}
/// <summary>
/// Gets the named attribute
/// </summary>
/// <returns>An empty string is returned if a matching attribute is not found or if the attribute does not have a specified or default value.</returns>
public string GetAttribute(string attributeName)
{
if (_xmlElement == null)
{
return _geckoElement.GetAttribute(attributeName);
}
else
{
return _xmlElement.GetAttribute(attributeName);
}
}
public override bool Equals(object obj)
{
throw new NotImplementedException();
}
protected bool Equals(UrlPathString other)
{
throw new NotImplementedException();
}
public static bool operator ==(ElementProxy a, ElementProxy b)
{
throw new NotImplementedException();
}
public static bool operator !=(ElementProxy a, ElementProxy b)
{
throw new NotImplementedException();
}
}
} | mit | C# |
3fe9e4c813e60c04536a9e2c333794ff1226cb4b | Change ParentType to public | nickdodd79/AutoBogus | src/AutoBogus/AutoGenerateContext.cs | src/AutoBogus/AutoGenerateContext.cs | using Bogus;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoBogus
{
/// <summary>
/// A class that provides context for a generate request.
/// </summary>
public sealed class AutoGenerateContext
{
internal AutoGenerateContext(AutoConfig config)
: this(config.FakerHub, config)
{ }
internal AutoGenerateContext(Faker faker, AutoConfig config)
{
Faker = faker ?? new Faker(config.Locale);
Config = config;
TypesStack = new Stack<Type>();
RuleSets = Enumerable.Empty<string>();
}
internal AutoConfig Config { get; }
internal Stack<Type> TypesStack { get; }
internal object Instance { get; set; }
/// <summary>
/// The parent type of the type associated with the current generate request.
/// </summary>
public Type ParentType { get; set; }
/// <summary>
/// The type associated with the current generate request.
/// </summary>
public Type GenerateType { get; internal set; }
/// <summary>
/// The name associated with the current generate request.
/// </summary>
public string GenerateName { get; internal set; }
/// <summary>
/// The underlying <see cref="Bogus.Faker"/> instance used to generate random values.
/// </summary>
public Faker Faker { get; }
/// <summary>
/// The requested rule sets provided for the generate request.
/// </summary>
public IEnumerable<string> RuleSets { get; internal set; }
internal IAutoBinder Binder => Config.Binder;
internal IEnumerable<AutoGeneratorOverride> Overrides => Config.Overrides;
}
}
| using Bogus;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AutoBogus
{
/// <summary>
/// A class that provides context for a generate request.
/// </summary>
public sealed class AutoGenerateContext
{
internal AutoGenerateContext(AutoConfig config)
: this(config.FakerHub, config)
{ }
internal AutoGenerateContext(Faker faker, AutoConfig config)
{
Faker = faker ?? new Faker(config.Locale);
Config = config;
TypesStack = new Stack<Type>();
RuleSets = Enumerable.Empty<string>();
}
internal AutoConfig Config { get; }
internal Stack<Type> TypesStack { get; }
internal Type ParentType { get; set; }
internal object Instance { get; set; }
/// <summary>
/// The type associated with the current generate request.
/// </summary>
public Type GenerateType { get; internal set; }
/// <summary>
/// The name associated with the current generate request.
/// </summary>
public string GenerateName { get; internal set; }
/// <summary>
/// The underlying <see cref="Bogus.Faker"/> instance used to generate random values.
/// </summary>
public Faker Faker { get; }
/// <summary>
/// The requested rule sets provided for the generate request.
/// </summary>
public IEnumerable<string> RuleSets { get; internal set; }
internal IAutoBinder Binder => Config.Binder;
internal IEnumerable<AutoGeneratorOverride> Overrides => Config.Overrides;
}
}
| mit | C# |
c7f4bae569d931a9b6d4dae5a038ef218a8163e3 | Fix broken async call | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.Web/Filters/LevyEmployerTypeOnly.cs | src/SFA.DAS.EmployerFinance.Web/Filters/LevyEmployerTypeOnly.cs | using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;
using SFA.DAS.Common.Domain.Types;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EAS.Account.Api.Types;
using SFA.DAS.EmployerFinance.Web.Helpers;
namespace SFA.DAS.EmployerFinance.Web.Filters
{
public class LevyEmployerTypeOnly : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
if(filterContext.ActionParameters == null || !filterContext.ActionParameters.ContainsKey("HashedAccountId"))
{
filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName };
return;
}
var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString();
var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>();
var task = Task.Run(async () => await accountApi.GetAccount(hashedAccountId));
AccountDetailViewModel account = task.Result;
ApprenticeshipEmployerType apprenticeshipEmployerType = (ApprenticeshipEmployerType)Enum.Parse(typeof(ApprenticeshipEmployerType), account.ApprenticeshipEmployerType, true);
if (apprenticeshipEmployerType == ApprenticeshipEmployerType.Levy)
{
base.OnActionExecuting(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new
{
controller = ControllerConstants.AccessDeniedControllerName,
action = "Index",
}));
}
}
catch (Exception ex)
{
filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName };
}
}
}
} | using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;
using SFA.DAS.Common.Domain.Types;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EAS.Account.Api.Types;
using SFA.DAS.EmployerFinance.Web.Helpers;
namespace SFA.DAS.EmployerFinance.Web.Filters
{
public class LevyEmployerTypeOnly : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
if(filterContext.ActionParameters == null || !filterContext.ActionParameters.ContainsKey("HashedAccountId"))
{
filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName };
return;
}
var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString();
var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>();
AccountDetailViewModel account = accountApi.GetAccount(hashedAccountId).GetAwaiter().GetResult();
ApprenticeshipEmployerType apprenticeshipEmployerType = (ApprenticeshipEmployerType)Enum.Parse(typeof(ApprenticeshipEmployerType), account.ApprenticeshipEmployerType, true);
if (apprenticeshipEmployerType == ApprenticeshipEmployerType.Levy)
{
base.OnActionExecuting(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new
{
controller = ControllerConstants.AccessDeniedControllerName,
action = "Index",
}));
}
}
catch (Exception ex)
{
filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName };
}
}
}
} | mit | C# |
f4dca1b9487ce49ee8c57243a9b518e1bed82160 | Handle failed Api call within Action Filter | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerFinance.Web/Filters/LevyEmployerTypeOnly.cs | src/SFA.DAS.EmployerFinance.Web/Filters/LevyEmployerTypeOnly.cs | using System;
using System.Web.Mvc;
using System.Web.Routing;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EmployerFinance.Web.Helpers;
namespace SFA.DAS.EmployerFinance.Web.Filters
{
public class LevyEmployerTypeOnly : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString();
var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>();
var task = accountApi.GetAccount(hashedAccountId);
task.RunSynchronously();
var account = task.Result;
if (account.ApprenticeshipEmployerType == "1")
{
base.OnActionExecuting(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new
{
controller = ControllerConstants.AccessDeniedControllerName,
action = "Index",
}));
}
}
catch (Exception ex)
{
filterContext.Result = new ViewResult { ViewName = ControllerConstants.BadRequestViewName };
}
}
}
} | using System.Web.Mvc;
using System.Web.Routing;
using SFA.DAS.EAS.Account.Api.Client;
using SFA.DAS.EAS.Account.Api.Types;
namespace SFA.DAS.EmployerFinance.Web.Filters
{
public class LevyEmployerTypeOnly : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var hashedAccountId = filterContext.ActionParameters["HashedAccountId"].ToString();
var accountApi = DependencyResolver.Current.GetService<IAccountApiClient>();
var account = accountApi.GetAccount(hashedAccountId).Result;
if (account.ApprenticeshipEmployerType == "1")
{
base.OnActionExecuting(filterContext);
}
else
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new
{
controller = "AccessDenied",
action = "Index",
}));
}
}
}
} | mit | C# |
54e507a589ffe9ea2d4b1db88e01fb37e0afa831 | Include GogoKit version in User-Agent header | viagogo/gogokit.net | src/GogoKit/Http/UserAgentHandler.cs | src/GogoKit/Http/UserAgentHandler.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace GogoKit.Http
{
public class UserAgentHandler : DelegatingHandler
{
private static readonly ProductInfoHeaderValue GogoKitVersionHeaderValue =
new ProductInfoHeaderValue(
"GogoKit",
FileVersionInfo.GetVersionInfo(typeof(UserAgentHandler).Assembly.Location).ProductVersion);
private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues;
public UserAgentHandler(ProductHeaderValue product)
{
Requires.ArgumentNotNull(product, nameof(product));
_userAgentHeaderValues = GetUserAgentHeaderValues(product);
}
private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product)
{
return new List<ProductInfoHeaderValue>
{
new ProductInfoHeaderValue(product),
GogoKitVersionHeaderValue
};
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
foreach (var product in _userAgentHeaderValues)
{
request.Headers.UserAgent.Add(product);
}
return base.SendAsync(request, cancellationToken);
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace GogoKit.Http
{
public class UserAgentHandler : DelegatingHandler
{
private readonly IReadOnlyList<ProductInfoHeaderValue> _userAgentHeaderValues;
public UserAgentHandler(ProductHeaderValue product)
{
Requires.ArgumentNotNull(product, nameof(product));
_userAgentHeaderValues = GetUserAgentHeaderValues(product);
}
private IReadOnlyList<ProductInfoHeaderValue> GetUserAgentHeaderValues(ProductHeaderValue product)
{
return new List<ProductInfoHeaderValue>
{
new ProductInfoHeaderValue(product),
//new ProductInfoHeaderValue($"({CultureInfo.CurrentCulture.Name}; GogoKit {AssemblyVersionInformation.Version})")
};
}
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
foreach (var product in _userAgentHeaderValues)
{
request.Headers.UserAgent.Add(product);
}
return base.SendAsync(request, cancellationToken);
}
}
}
| mit | C# |
5b02b3726fd75473fe80e270987172d737d3196a | resolve conflicts | DigDes/SoapCore | src/SoapCore.Tests/Wsdl/WsdlTests.cs | src/SoapCore.Tests/Wsdl/WsdlTests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoapCore.Tests.Wsdl.Services;
namespace SoapCore.Tests.Wsdl
{
[TestClass]
public class WsdlTests
{
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
[TestMethod]
public void CheckTaskReturnMethod()
{
string serviceUrl = "http://localhost:5053";
StartService(typeof(TaskNoReturnService), serviceUrl);
var wsdl = GetWsdl(serviceUrl);
Trace.TraceInformation(wsdl);
Assert.IsNotNull(wsdl);
StopServer();
}
[TestMethod]
public void CheckDataContractContainsItself()
{
string serviceUrl = "http://localhost:5054";
StartService(typeof(DataContractContainsItselfService), serviceUrl);
var wsdl = GetWsdl(serviceUrl);
Trace.TraceInformation(wsdl);
Assert.IsNotNull(wsdl);
StopServer();
}
[TestMethod]
public void CheckDataContractCircularReference()
{
StartService(typeof(DataContractCircularReferenceService));
var wsdl = GetWsdl();
Trace.TraceInformation(wsdl);
Assert.IsNotNull(wsdl);
StopServer();
}
[TestCleanup]
public void StopServer()
{
_cancellationTokenSource.Cancel();
}
private string GetWsdl(string serviceUrl, string serviceName = "Service.svc")
{
using (var httpClient = new HttpClient())
{
return httpClient.GetStringAsync(string.Format("{0}/{1}?wsdl", serviceUrl, serviceName)).Result;
}
}
private void StartService(Type serviceType, string serviceUrl)
{
Task.Run(async () =>
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls(serviceUrl)
.ConfigureServices(services => services.AddSingleton<IStartupConfiguration>(new StartupConfiguration(serviceType)))
.UseStartup<Startup>()
.Build();
await host.RunAsync(_cancellationTokenSource.Token);
}).Wait(1000);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SoapCore.Tests.Wsdl.Services;
namespace SoapCore.Tests.Wsdl
{
[TestClass]
public class WsdlTests
{
private const string ServiceUrl = "http://localhost:5052";
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
[TestMethod]
public void CheckTaskReturnMethod()
{
StartService(typeof(TaskNoReturnService));
var wsdl = GetWsdl();
Trace.TraceInformation(wsdl);
Assert.IsNotNull(wsdl);
StopServer();
}
[TestMethod]
public void CheckDataContractContainsItself()
{
StartService(typeof(DataContractContainsItselfService));
var wsdl = GetWsdl();
Trace.TraceInformation(wsdl);
Assert.IsNotNull(wsdl);
StopServer();
}
[TestMethod]
public void CheckDataContractCircularReference()
{
StartService(typeof(DataContractCircularReferenceService));
var wsdl = GetWsdl();
Trace.TraceInformation(wsdl);
Assert.IsNotNull(wsdl);
StopServer();
}
[TestCleanup]
public void StopServer()
{
_cancellationTokenSource.Cancel();
}
private string GetWsdl(string serviceName = "Service.svc")
{
using (var httpClient = new HttpClient())
{
return httpClient.GetStringAsync(string.Format("{0}/{1}?wsdl", ServiceUrl, serviceName)).Result;
}
}
private void StartService(Type serviceType)
{
Task.Run(async () =>
{
var host = new WebHostBuilder()
.UseKestrel()
.UseUrls(ServiceUrl)
.ConfigureServices(services => services.AddSingleton<IStartupConfiguration>(new StartupConfiguration(serviceType)))
.UseStartup<Startup>()
.Build();
await host.RunAsync(_cancellationTokenSource.Token);
}).Wait(1000);
}
}
}
| mit | C# |
c9ef50c40a2d2e04235d62ef5c9bf105561e3c85 | Fix Edit POS | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Persistence.MongoDB/GestionePOS/EditPOS.cs | src/backend/SO115App.Persistence.MongoDB/GestionePOS/EditPOS.cs | //-----------------------------------------------------------------------
// <copyright file="EditPOS.cs" company="CNVVF">
// Copyright (C) 2021 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using Microsoft.AspNetCore.Http;
using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.Models.Classi.Pos;
using SO115App.Models.Servizi.Infrastruttura.GestionePOS;
using System.IO;
namespace SO115App.Persistence.MongoDB.GestionePOS
{
public class EditPOS : IEditPos
{
private readonly DbContext _dbcontex;
public EditPOS(DbContext dbcontex)
{
_dbcontex = dbcontex;
}
public void Edit(DtoPos pos)
{
var posNew = new PosDAO()
{
Id = pos.Id,
CodSede = pos.CodSede,
DescrizionePos = pos.DescrizionePos,
FDFile = ByteArrayConvert(pos.FDFile),
ListaTipologie = pos.ListaTipologieConvert
};
var filter = Builders<PosDAO>.Filter.Eq(s => s.Id, pos.Id);
_dbcontex.DtoPosCollection.ReplaceOne(filter, posNew);
}
private byte[] ByteArrayConvert(IFormFile fDFile)
{
MemoryStream ms = new MemoryStream();
fDFile.CopyTo(ms);
return ms.ToArray();
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="EditPOS.cs" company="CNVVF">
// Copyright (C) 2021 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using Microsoft.AspNetCore.Http;
using MongoDB.Driver;
using Persistence.MongoDB;
using SO115App.Models.Classi.Pos;
using SO115App.Models.Servizi.Infrastruttura.GestionePOS;
using System.IO;
namespace SO115App.Persistence.MongoDB.GestionePOS
{
public class EditPOS : IEditPos
{
private readonly DbContext _dbcontex;
public EditPOS(DbContext dbcontex)
{
_dbcontex = dbcontex;
}
public void Edit(DtoPos pos)
{
var posNew = new PosDAO()
{
CodSede = pos.CodSede,
DescrizionePos = pos.DescrizionePos,
FDFile = ByteArrayConvert(pos.FDFile),
ListaTipologie = pos.ListaTipologieConvert
};
var filter = Builders<PosDAO>.Filter.Eq(s => s.Id, pos.Id);
_dbcontex.DtoPosCollection.ReplaceOne(filter, posNew);
}
private byte[] ByteArrayConvert(IFormFile fDFile)
{
MemoryStream ms = new MemoryStream();
fDFile.CopyTo(ms);
return ms.ToArray();
}
}
}
| agpl-3.0 | C# |
44b33a149e935c156616642ccaa5f1189773b994 | Make MethodReplacer change opcode to CALL as default | pardeike/Harmony | Harmony/Transpilers.cs | Harmony/Transpilers.cs | using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode? callOpcode = null)
{
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = callOpcode ?? OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
} | using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
instruction.operand = to;
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
} | mit | C# |
281da6d50eaea232cb2d5ec3ff01b49c371a4897 | fix for setting rawname on computation operation model | ezg/PanoramicDataWin8,ezg/PanoramicDataWin8 | PanoramicDataWin8/model/data/operation/computational/ComputationalOperationModel.cs | PanoramicDataWin8/model/data/operation/computational/ComputationalOperationModel.cs | using IDEA_common.catalog;
using IDEA_common.operations;
using Newtonsoft.Json;
using PanoramicDataWin8.model.data.attribute;
using PanoramicDataWin8.model.data.idea;
using PanoramicDataWin8.utils;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using static PanoramicDataWin8.model.data.attribute.AttributeModel;
namespace PanoramicDataWin8.model.data.operation
{
public class ComputationalOperationModel : AttributeUsageOperationModel
{
string _rawName;
protected virtual void updateName()
{
var str = "(";
var code = (GetCode().FuncModel as AttributeFuncModel.AttributeCodeFuncModel).Code;
var terms = new Regex("\\b", RegexOptions.Compiled).Split(code);
foreach (var n in terms)
if (n != null && AttributeTransformationModel.MatchesExistingField(n, true) != null)
str += n + ",";
str = str.TrimEnd(',') + ")";
var newName = new Regex("\\(.*\\)", RegexOptions.Compiled).Replace(GetCode().RawName, str);
//GetCode().DisplayName = newName;
SetRawName(newName);
}
public ComputationalOperationModel(SchemaModel schemaModel, string code, DataType dataType, string visualizationType, string rawName, string displayName = null) : base(schemaModel)
{
_rawName = rawName;
if (rawName != null && !IDEAAttributeModel.NameExists(rawName))
{
IDEAAttributeModel.AddCodeField(rawName, displayName == null ? rawName : displayName, code, dataType, visualizationType, new List<VisualizationHint>());
}
}
public void SetRawName(string name)
{
var code = GetCode();
code.DisplayName = code.RawName = _rawName = name;
}
public IDEAAttributeModel GetCode()
{
return IDEAAttributeModel.Function(_rawName);
}
public void SetCode(string code, DataType dataType)
{
GetCode().SetCode(code, dataType);
updateName();
}
}
} | using IDEA_common.catalog;
using IDEA_common.operations;
using Newtonsoft.Json;
using PanoramicDataWin8.model.data.attribute;
using PanoramicDataWin8.model.data.idea;
using PanoramicDataWin8.utils;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using static PanoramicDataWin8.model.data.attribute.AttributeModel;
namespace PanoramicDataWin8.model.data.operation
{
public class ComputationalOperationModel : AttributeUsageOperationModel
{
string _rawName;
protected virtual void updateName()
{
var str = "(";
var code = (GetCode().FuncModel as AttributeFuncModel.AttributeCodeFuncModel).Code;
var terms = new Regex("\\b", RegexOptions.Compiled).Split(code);
foreach (var n in terms)
if (n != null && AttributeTransformationModel.MatchesExistingField(n, true) != null)
str += n + ",";
str = str.TrimEnd(',') + ")";
var newName = new Regex("\\(.*\\)", RegexOptions.Compiled).Replace(GetCode().RawName, str);
GetCode().DisplayName = newName;
}
public ComputationalOperationModel(SchemaModel schemaModel, string code, DataType dataType, string visualizationType, string rawName, string displayName = null) : base(schemaModel)
{
_rawName = rawName;
if (rawName != null && !IDEAAttributeModel.NameExists(rawName))
{
IDEAAttributeModel.AddCodeField(rawName, displayName == null ? rawName : displayName, code, dataType, visualizationType, new List<VisualizationHint>());
}
}
public void SetRawName(string name)
{
var code = GetCode();
code.DisplayName = code.RawName = _rawName = name;
}
public IDEAAttributeModel GetCode()
{
return IDEAAttributeModel.Function(_rawName);
}
public void SetCode(string code, DataType dataType)
{
GetCode().SetCode(code, dataType);
updateName();
}
}
} | apache-2.0 | C# |
659cf629b6d62e614bc5bc87eefcaf6075b78182 | Add skin seleciton dropdown to settings | Frontear/osuKyzer,peppy/osu-new,johnneijzen/osu,ZLima12/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,ppy/osu,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,Nabile-Rahmani/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,naoey/osu,DrabWeb/osu,DrabWeb/osu,naoey/osu,DrabWeb/osu,peppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu | osu.Game/Overlays/Settings/Sections/SkinSection.cs | osu.Game/Overlays/Settings/Sections/SkinSection.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Skinning;
using OpenTK;
namespace osu.Game.Overlays.Settings.Sections
{
public class SkinSection : SettingsSection
{
private SettingsDropdown<SkinInfo> skinDropdown;
public override string Header => "Skin";
public override FontAwesome Icon => FontAwesome.fa_paint_brush;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, SkinManager skins)
{
FlowContent.Spacing = new Vector2(0, 5);
Children = new Drawable[]
{
skinDropdown = new SettingsDropdown<SkinInfo>(),
new SettingsSlider<double, SizeSlider>
{
LabelText = "Menu cursor size",
Bindable = config.GetBindable<double>(OsuSetting.MenuCursorSize),
KeyboardStep = 0.1f
},
new SettingsSlider<double, SizeSlider>
{
LabelText = "Gameplay cursor size",
Bindable = config.GetBindable<double>(OsuSetting.GameplayCursorSize),
KeyboardStep = 0.1f
},
new SettingsCheckbox
{
LabelText = "Adjust gameplay cursor size based on current beatmap",
Bindable = config.GetBindable<bool>(OsuSetting.AutoCursorSize)
},
};
void reloadSkins() => skinDropdown.Items = skins.GetAllUsableSkins().Select(s => new KeyValuePair<string, SkinInfo>(s.Name, s));
skins.ItemAdded += _ => reloadSkins();
skins.ItemRemoved += _ => reloadSkins();
reloadSkins();
skinDropdown.Bindable = skins.CurrentSkinInfo;
}
private class SizeSlider : OsuSliderBar<double>
{
public override string TooltipText => Current.Value.ToString(@"0.##x");
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.UserInterface;
using OpenTK;
namespace osu.Game.Overlays.Settings.Sections
{
public class SkinSection : SettingsSection
{
public override string Header => "Skin";
public override FontAwesome Icon => FontAwesome.fa_paint_brush;
[BackgroundDependencyLoader]
private void load(OsuConfigManager config)
{
FlowContent.Spacing = new Vector2(0, 5);
Children = new Drawable[]
{
new SettingsSlider<double, SizeSlider>
{
LabelText = "Menu cursor size",
Bindable = config.GetBindable<double>(OsuSetting.MenuCursorSize),
KeyboardStep = 0.1f
},
new SettingsSlider<double, SizeSlider>
{
LabelText = "Gameplay cursor size",
Bindable = config.GetBindable<double>(OsuSetting.GameplayCursorSize),
KeyboardStep = 0.1f
},
new SettingsCheckbox
{
LabelText = "Adjust gameplay cursor size based on current beatmap",
Bindable = config.GetBindable<bool>(OsuSetting.AutoCursorSize)
},
};
}
private class SizeSlider : OsuSliderBar<double>
{
public override string TooltipText => Current.Value.ToString(@"0.##x");
}
}
}
| mit | C# |
aa24482e02063f16938fdeb6b8d0d75c1adaca4f | Use Generator.Lazy instead | inputfalken/Sharpy | src/Sharpy.Core/Linq/Skip.cs | src/Sharpy.Core/Linq/Skip.cs | using System;
namespace Sharpy.Core.Linq {
public static partial class Extensions {
/// <summary>
/// <para>
/// Skips the number given to <paramref name="count" /> from <see cref="IGenerator{T}" />.
/// </para>
/// </summary>
/// <typeparam name="TSource">
/// The type of the elements of <paramref name="generator" />.
/// </typeparam>
/// <param name="generator">The <paramref name="generator" /> whose generations will be skipped.</param>
/// <param name="count">The number of generations to be released.</param>
/// <exception cref="ArgumentNullException">Argument <paramref name="generator" /> is null.</exception>
/// <exception cref="ArgumentException">Argument <paramref name="count" /> is less than 0.</exception>
/// <returns>
/// A <see cref="IGenerator{T}" /> whose elements has been skipped by the number equal to argument
/// <paramref name="count" />.
/// </returns>
/// <remarks>
/// <para>
/// This works the same way as <see cref="Release{TSource}" /> except that it's lazy evaluated.
/// </para>
/// </remarks>
public static IGenerator<TSource> Skip<TSource>(this IGenerator<TSource> generator, int count) {
if (generator == null) throw new ArgumentNullException(nameof(generator));
if (count < 0) throw new ArgumentException($"{nameof(count)} Cant be negative");
if (count == 0) return generator;
return Generator.Lazy(() => ReleaseIterator(generator, count).Generate());
}
}
} | using System;
namespace Sharpy.Core.Linq {
public static partial class Extensions {
/// <summary>
/// <para>
/// Skips the number given to <paramref name="count" /> from <see cref="IGenerator{T}" />.
/// </para>
/// </summary>
/// <typeparam name="TSource">
/// The type of the elements of <paramref name="generator" />.
/// </typeparam>
/// <param name="generator">The <paramref name="generator" /> whose generations will be skipped.</param>
/// <param name="count">The number of generations to be released.</param>
/// <exception cref="ArgumentNullException">Argument <paramref name="generator" /> is null.</exception>
/// <exception cref="ArgumentException">Argument <paramref name="count" /> is less than 0.</exception>
/// <returns>
/// A <see cref="IGenerator{T}" /> whose elements has been skipped by the number equal to argument
/// <paramref name="count" />.
/// </returns>
/// <remarks>
/// <para>
/// This works the same way as <see cref="Release{TSource}" /> except that it's lazy evaluated.
/// </para>
/// </remarks>
public static IGenerator<TSource> Skip<TSource>(this IGenerator<TSource> generator, int count) {
if (generator == null) throw new ArgumentNullException(nameof(generator));
if (count < 0) throw new ArgumentException($"{nameof(count)} Cant be negative");
if (count == 0) return generator;
var skipped = new Lazy<IGenerator<TSource>>(() => ReleaseIterator(generator, count));
return Generator.Function(() => skipped.Value.Generate());
}
}
} | mit | C# |
b67e1546300440c0d0f82b57a534486a5a886c7c | fix test data type registration | 6bee/aqua-core | test/Aqua.Tests/Serialization/ProtobufNetSerializationHelper.cs | test/Aqua.Tests/Serialization/ProtobufNetSerializationHelper.cs | // Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Aqua.Tests.Serialization
{
using Aqua.EnumerableExtensions;
using Aqua.TypeExtensions;
using System;
using System.Linq;
////using System.Collections;
////using System.Linq;
using System.Numerics;
using Xunit;
public static class ProtobufNetSerializationHelper
{
private static readonly global::ProtoBuf.Meta.TypeModel _configuration = CreateTypeModel();
private static global::ProtoBuf.Meta.TypeModel CreateTypeModel()
{
var configuration = ProtoBufTypeModel.ConfigureAquaTypes();
var testdatatypes = TestData.TestTypes
.Select(x => (Type)x[0])
.Select(x => x.AsNonNullableType())
.Distinct()
.ToArray();
testdatatypes.ForEach(x => configuration.AddDynamicPropertyType(x));
return configuration;
}
public static T Serialize<T>(this T graph) => Serialize(graph, null);
public static T Serialize<T>(this T graph, global::ProtoBuf.Meta.TypeModel model)
=> (T)(model ?? _configuration).DeepClone(graph);
public static void SkipUnsupportedDataType(Type type, object value)
{
Skip.If(type.Is<DateTimeOffset>(), $"{type} not supported by out-of-the-box protobuf-net");
Skip.If(type.Is<BigInteger>(), $"{type} not supported by out-of-the-box protobuf-net");
Skip.If(type.Is<Complex>(), $"{type} not supported by out-of-the-box protobuf-net");
Skip.If(type.IsNotPublic(), $"Not-public {type} not supported protobuf-net");
#if !NET48
Skip.If(type.Is<Half>(), $"{type} serialization is not supported.");
#endif // NET48
}
}
} | // Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.
namespace Aqua.Tests.Serialization
{
using Aqua.EnumerableExtensions;
using Aqua.TypeExtensions;
using System;
using System.Linq;
////using System.Collections;
////using System.Linq;
using System.Numerics;
using Xunit;
public static class ProtobufNetSerializationHelper
{
private static readonly global::ProtoBuf.Meta.TypeModel _configuration = CreateTypeModel();
private static global::ProtoBuf.Meta.TypeModel CreateTypeModel()
{
var configuration = ProtoBufTypeModel.ConfigureAquaTypes();
var testdatatypes = TestData.TestTypes
.Select(x => (Type)x[0])
.Select(x => x.AsNonNullableType())
.Distinct()
.Where(x => x.IsPublic)
.ToArray();
testdatatypes.ForEach(x => configuration.AddDynamicPropertyType(x));
return configuration;
}
public static T Serialize<T>(this T graph) => Serialize(graph, null);
public static T Serialize<T>(this T graph, global::ProtoBuf.Meta.TypeModel model)
=> (T)(model ?? _configuration).DeepClone(graph);
public static void SkipUnsupportedDataType(Type type, object value)
{
Skip.If(type.Is<DateTimeOffset>(), $"{type} not supported by out-of-the-box protobuf-net");
Skip.If(type.Is<BigInteger>(), $"{type} not supported by out-of-the-box protobuf-net");
Skip.If(type.Is<Complex>(), $"{type} not supported by out-of-the-box protobuf-net");
Skip.If(type.IsNotPublic(), $"Not-public {type} not supported protobuf-net");
#if !NET48
Skip.If(type.Is<Half>(), $"{type} serialization is not supported.");
#endif // NET48
}
}
} | mit | C# |
1b44711ceb6f84c6eaa503d5d08ce30cb49a01e8 | Clarify some names | Michelle-Argus/ArribasimExtract,bravelittlescientist/opensim-performance,RavenB/opensim,N3X15/VoxelSim,rryk/omp-server,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,allquixotic/opensim-autobackup,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,AlexRa/opensim-mods-Alex,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip,M-O-S-E-S/opensim,Michelle-Argus/ArribasimExtract,OpenSimian/opensimulator,RavenB/opensim,AlexRa/opensim-mods-Alex,N3X15/VoxelSim,bravelittlescientist/opensim-performance,AlexRa/opensim-mods-Alex,ft-/arribasim-dev-tests,OpenSimian/opensimulator,BogusCurry/arribasim-dev,QuillLittlefeather/opensim-1,RavenB/opensim,TomDataworks/opensim,allquixotic/opensim-autobackup,Michelle-Argus/ArribasimExtract,Michelle-Argus/ArribasimExtract,TechplexEngineer/Aurora-Sim,cdbean/CySim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,RavenB/opensim,QuillLittlefeather/opensim-1,justinccdev/opensim,bravelittlescientist/opensim-performance,TechplexEngineer/Aurora-Sim,bravelittlescientist/opensim-performance,rryk/omp-server,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,TomDataworks/opensim,TomDataworks/opensim,TomDataworks/opensim,ft-/arribasim-dev-extras,N3X15/VoxelSim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,Michelle-Argus/ArribasimExtract,N3X15/VoxelSim,OpenSimian/opensimulator,cdbean/CySim,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-tests,justinccdev/opensim,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-extras,TomDataworks/opensim,N3X15/VoxelSim,OpenSimian/opensimulator,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,allquixotic/opensim-autobackup,cdbean/CySim,OpenSimian/opensimulator,ft-/arribasim-dev-tests,OpenSimian/opensimulator,rryk/omp-server,BogusCurry/arribasim-dev,cdbean/CySim,RavenB/opensim,QuillLittlefeather/opensim-1,justinccdev/opensim,ft-/arribasim-dev-extras,OpenSimian/opensimulator,cdbean/CySim,M-O-S-E-S/opensim,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip,justinccdev/opensim,TechplexEngineer/Aurora-Sim,ft-/opensim-optimizations-wip-extras,N3X15/VoxelSim,rryk/omp-server,ft-/arribasim-dev-tests,ft-/opensim-optimizations-wip-tests,TomDataworks/opensim,TechplexEngineer/Aurora-Sim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,bravelittlescientist/opensim-performance,BogusCurry/arribasim-dev,justinccdev/opensim,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,justinccdev/opensim,allquixotic/opensim-autobackup,AlexRa/opensim-mods-Alex,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,BogusCurry/arribasim-dev,ft-/arribasim-dev-tests,TomDataworks/opensim,allquixotic/opensim-autobackup,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,AlexRa/opensim-mods-Alex,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,N3X15/VoxelSim,BogusCurry/arribasim-dev,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,cdbean/CySim,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,RavenB/opensim | OpenSim/Services/Interfaces/IFriendsService.cs | OpenSim/Services/Interfaces/IFriendsService.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.
*/
using OpenMetaverse;
using OpenSim.Framework;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Interfaces
{
public struct FriendInfo
{
public UUID PrincipalID;
public string Friend;
int MyFlags;
int TheirFlags;
}
public interface IFriendsService
{
FriendInfo[] GetFriends(UUID PrincipalID);
bool StoreFriend(UUID PrincipalID, string Friend, int flags);
bool Delete(UUID PrincipalID, string Friend);
}
}
| /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.
*/
using OpenMetaverse;
using OpenSim.Framework;
using System.Collections.Generic;
namespace OpenSim.Region.Framework.Interfaces
{
public struct FriendInfo
{
public UUID PrincipalID;
public string Friend;
int MyRights;
int TheirRights;
}
public interface IFriendsService
{
FriendInfo[] GetFriends(UUID PrincipalID);
bool StoreFriend(UUID PrincipalID, string Friend, int flags);
bool SetFlags(UUID PrincipalID, int flags);
bool Delete(UUID PrincipalID, string Friend);
}
}
| bsd-3-clause | C# |
5ad2fb0d80c443eb2e36ce0d93913184497940ad | Update agent name to only allow 18 characters so that it looks good on the screen | reichlew/planet-wars-competition,aaron-lillywhite/planet-wars-competition,reichlew/planet-wars-competition,reichlew/planet-wars-competition,aaron-lillywhite/planet-wars-competition,aaron-lillywhite/planet-wars-competition | PlanetWars/Validators/LogonRequestValidator.cs | PlanetWars/Validators/LogonRequestValidator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;
using PlanetWars.Shared;
namespace PlanetWars.Validators
{
public class LogonRequestValidator : AbstractValidator<LogonRequest>
{
public LogonRequestValidator()
{
RuleFor(logon => logon.AgentName)
.NotEmpty().WithMessage("Please use a non empty agent name, logon failed")
.Length(1, 18).WithMessage("Please use an agent name between 1-18 characters, logon failed");
RuleFor(logon => logon.MapGeneration)
.Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option");
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentValidation;
using PlanetWars.Shared;
namespace PlanetWars.Validators
{
public class LogonRequestValidator : AbstractValidator<LogonRequest>
{
public LogonRequestValidator()
{
RuleFor(logon => logon.AgentName)
.NotEmpty().WithMessage("Please use a non empty agent name, logon failed")
.Length(1, 20).WithMessage("Please use an agent name between 1-20 characters, logon failed");
RuleFor(logon => logon.MapGeneration)
.Must(x => x == MapGenerationOption.Basic || x == MapGenerationOption.Random).WithMessage("Please use a valid Map Generation Option");
}
}
} | bsd-3-clause | C# |
82a9eca0a60a6c68f448dc3d7dfe18429592e03a | add a test for pushing and progress bar | shiftkey/ReactiveGit | ReactiveGit.Tests/ObservableRepositoryTests.cs | ReactiveGit.Tests/ObservableRepositoryTests.cs | using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
using LibGit2Sharp;
using Xunit;
namespace ReactiveGit.Tests
{
public class ObservableRepositoryTests
{
[Fact]
public async Task CanPullSomeRepository()
{
Credentials credentials = new UsernamePasswordCredentials
{
Username = "shiftkey-tester",
Password = "haha-password"
};
var repository = new ObservableRepository(
@"C:\Users\brendanforster\Documents\GìtHūb\atom-dark-syntax",
credentials);
var progress = 0;
var pullObserver = Observer.Create<Tuple<string, int>>(
next =>
{
Console.WriteLine("pull progress: " + next.Item2);
progress = (next.Item2 * 2) / 3;
},
() => { Console.WriteLine("pull completed"); });
var pullResult = await repository.Pull(pullObserver);
Assert.Equal(66, progress);
Assert.NotEqual(MergeStatus.Conflicts, pullResult.Status);
var pushObserver = Observer.Create<Tuple<string, int>>(
next =>
{
progress = 66 + (next.Item2 * 2) / 3;
Console.WriteLine("push progress: " + next.Item2);
},
() => { Console.WriteLine("push completed"); })
.NotifyOn(DefaultScheduler.Instance);
var pushResult = await repository.Push(pushObserver);
Assert.Equal(100, progress);
}
}
}
| using System;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
using LibGit2Sharp;
using Xunit;
namespace ReactiveGit.Tests
{
public class ObservableRepositoryTests
{
[Fact]
public async Task CanPullSomeRepository()
{
Credentials credentials = new UsernamePasswordCredentials
{
Username = "shiftkey-tester",
Password = "haha-password"
};
var repository = new ObservableRepository(
@"C:\Users\brendanforster\Documents\GìtHūb\atom-dark-syntax",
credentials);
var pullObserver = Observer.Create<Tuple<string, int>>(
next => { Console.WriteLine("progress: " + next.Item2); },
() => { Console.WriteLine("it is done"); })
.NotifyOn(DefaultScheduler.Instance);
var result = await repository.Pull(pullObserver);
Assert.NotEqual(MergeStatus.Conflicts, result.Status);
}
}
}
| mit | C# |
9c31b8856d8d4dc2d91a344249f02590c7809e61 | change image url replace implementation | ppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,peppy/osu | osu.Game/Overlays/Wiki/Markdown/WikiMarkdownImage.cs | osu.Game/Overlays/Wiki/Markdown/WikiMarkdownImage.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax.Inlines;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Cursor;
namespace osu.Game.Overlays.Wiki.Markdown
{
public class WikiMarkdownImage : MarkdownImage, IHasTooltip
{
public string TooltipText { get; }
public WikiMarkdownImage(LinkInline linkInline)
: base(linkInline.Url)
{
TooltipText = linkInline.Title;
}
protected override ImageContainer CreateImageContainer(string url)
{
// The idea is replace "https://website.url/wiki/{path-to-image}" to "https://website.url/wiki/images/{path-to-image}"
// "/wiki/images/*" is route to fetch wiki image from osu!web server (see: https://github.com/ppy/osu-web/blob/4205eb66a4da86bdee7835045e4bf28c35456e04/routes/web.php#L289)
url = url.Replace("/wiki/", "/wiki/images/");
return base.CreateImageContainer(url);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using Markdig.Syntax.Inlines;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Cursor;
using osu.Game.Online.API;
namespace osu.Game.Overlays.Wiki.Markdown
{
public class WikiMarkdownImage : MarkdownImage, IHasTooltip
{
private readonly string url;
public string TooltipText { get; }
public WikiMarkdownImage(LinkInline linkInline)
: base(linkInline.Url)
{
url = linkInline.Url;
TooltipText = linkInline.Title;
}
[BackgroundDependencyLoader]
private void load(IAPIProvider api)
{
// The idea is replace "{api.WebsiteRootUrl}/wiki/{path-to-image}" to "{api.WebsiteRootUrl}/wiki/images/{path-to-image}"
// "/wiki/images/*" is route to fetch wiki image from osu!web server (see: https://github.com/ppy/osu-web/blob/4205eb66a4da86bdee7835045e4bf28c35456e04/routes/web.php#L289)
// Currently all image in dev server (https://dev.ppy.sh/wiki/image/*) is 404
// So for now just replace "{api.WebsiteRootUrl}/wiki/*" to "https://osu.ppy.sh/wiki/images/*" for simplicity
var imageUrl = url.Replace($"{api.WebsiteRootUrl}/wiki", "https://osu.ppy.sh/wiki/images");
InternalChild = new DelayedLoadWrapper(CreateImageContainer(imageUrl));
}
}
}
| mit | C# |
2ea7313830ba807d68cdad7eb94489b1ce627777 | Update Installer.cs | architecture-building-systems/revitpythonshell,architecture-building-systems/revitpythonshell | Installer/Installer.cs | Installer/Installer.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WixSharp;
using WixSharp.CommonTasks;
using WixSharp.Controls;
const string installationDir = @"%AppDataFolder%\Autodesk\Revit\Addins\";
const string projectName = "RevitPythonShell";
const string outputName = "RevitPythonShell";
const string outputDir = "output";
const string version = "1.0.1";
var fileName = new StringBuilder().Append(outputName).Append("-").Append(version);
var project = new Project
{
Name = projectName,
OutDir = outputDir,
Platform = Platform.x64,
Description = "The RevitPythonShell adds an IronPython interpreter to Autodesk Revit and Vasari.",
UI = WUI.WixUI_InstallDir,
Version = new Version(version),
OutFileName = fileName.ToString(),
InstallScope = InstallScope.perUser,
MajorUpgrade = MajorUpgrade.Default,
GUID = new Guid("8A43E94C-B89C-4135-8D7C-B8E51DCE70D5"),
BackgroundImage = @"Installer\Resources\Icons\BackgroundImage.png",
BannerImage = @"Installer\Resources\Icons\BannerImage.png",
ControlPanelInfo =
{
Manufacturer = "architecture-building-systems",
HelpLink = "https://github.com/architecture-building-systems/revitpythonshell",
Comments = "The RevitPythonShell adds an IronPython interpreter to Autodesk Revit and Vasari.",
ProductIcon = @"Installer\Resources\Icons\ShellIcon.ico",
},
Dirs = new Dir[]
{
new InstallDir(installationDir, GenerateWixEntities())
}
};
MajorUpgrade.Default.AllowSameVersionUpgrades = true;
project.RemoveDialogsBetween(NativeDialogs.WelcomeDlg, NativeDialogs.InstallDirDlg);
project.BuildMsi();
WixEntity[] GenerateWixEntities()
{
var versionRegex = new Regex(@"\d+");
var versionStorages = new Dictionary<string, List<WixEntity>>();
foreach (var directory in args)
{
var directoryInfo = new DirectoryInfo(directory);
var fileVersion = versionRegex.Match(directoryInfo.Name).Value;
var files = new Files($@"{directory}\*.*");
if (versionStorages.ContainsKey(fileVersion))
versionStorages[fileVersion].Add(files);
else
versionStorages.Add(fileVersion, new List<WixEntity> { files });
var assemblies = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);
Console.WriteLine($"Added '{fileVersion}' version files: ");
foreach (var assembly in assemblies) Console.WriteLine($"'{assembly}'");
}
return versionStorages.Select(storage => new Dir(storage.Key, storage.Value.ToArray())).Cast<WixEntity>().ToArray();
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using WixSharp;
using WixSharp.CommonTasks;
using WixSharp.Controls;
const string installationDir = @"%AppDataFolder%\Autodesk\Revit\Addins\";
const string projectName = "RevitPythonShell";
const string outputName = "RevitPythonShell";
const string outputDir = "output";
const string version = "1.0.1";
var fileName = new StringBuilder().Append(outputName).Append("-").Append(version);
var project = new Project
{
Name = projectName,
OutDir = outputDir,
Platform = Platform.x64,
Description = "The RevitPythonShell adds an IronPython interpreter to Autodesk Revit and Vasari.",
UI = WUI.WixUI_InstallDir,
Version = new Version(),
OutFileName = fileName.ToString(),
InstallScope = InstallScope.perUser,
MajorUpgrade = MajorUpgrade.Default,
GUID = new Guid("8A43E94C-B89C-4135-8D7C-B8E51DCE70D5"),
BackgroundImage = @"Installer\Resources\Icons\BackgroundImage.png",
BannerImage = @"Installer\Resources\Icons\BannerImage.png",
ControlPanelInfo =
{
Manufacturer = "architecture-building-systems",
HelpLink = "https://github.com/architecture-building-systems/revitpythonshell",
Comments = "The RevitPythonShell adds an IronPython interpreter to Autodesk Revit and Vasari.",
ProductIcon = @"Installer\Resources\Icons\ShellIcon.ico",
},
Dirs = new Dir[]
{
new InstallDir(installationDir, GenerateWixEntities())
}
};
MajorUpgrade.Default.AllowSameVersionUpgrades = true;
project.RemoveDialogsBetween(NativeDialogs.WelcomeDlg, NativeDialogs.InstallDirDlg);
project.BuildMsi();
WixEntity[] GenerateWixEntities()
{
var versionRegex = new Regex(@"\d+");
var versionStorages = new Dictionary<string, List<WixEntity>>();
foreach (var directory in args)
{
var directoryInfo = new DirectoryInfo(directory);
var fileVersion = versionRegex.Match(directoryInfo.Name).Value;
var files = new Files($@"{directory}\*.*");
if (versionStorages.ContainsKey(fileVersion))
versionStorages[fileVersion].Add(files);
else
versionStorages.Add(fileVersion, new List<WixEntity> { files });
var assemblies = Directory.GetFiles(directory, "*", SearchOption.AllDirectories);
Console.WriteLine($"Added '{fileVersion}' version files: ");
foreach (var assembly in assemblies) Console.WriteLine($"'{assembly}'");
}
return versionStorages.Select(storage => new Dir(storage.Key, storage.Value.ToArray())).Cast<WixEntity>().ToArray();
} | mit | C# |
c5078bd0ff5fae5be7b67011ab50568ee0643c20 | Change this to a double so that we don't have to always cast. | lukedrury/super-market-kata | supermarketkata/engine/rules/PercentageDiscount.cs | supermarketkata/engine/rules/PercentageDiscount.cs | using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly double m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = -(int) Math.Ceiling(item.Price * (m_Percentage / 100));
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
}
}
return discountedBasket;
}
}
} | using System;
using engine.core;
namespace engine.rules
{
public class PercentageDiscount : Rule
{
private readonly string m_ApplicableItemName;
private readonly int m_Percentage;
public PercentageDiscount(string applicableItemName, int percentage)
{
m_ApplicableItemName = applicableItemName;
m_Percentage = percentage;
}
public override Basket Apply(Basket basket)
{
var discountedBasket = new Basket();
foreach (var item in basket)
{
discountedBasket.Add(item);
if (item.Name.Equals(m_ApplicableItemName) && !item.UsedInOffer)
{
var discountToApply = -(int) Math.Ceiling(item.Price * ((double) m_Percentage / 100));
discountedBasket.Add(string.Format("{0}:{1}% discount", m_ApplicableItemName, m_Percentage), discountToApply);
}
}
return discountedBasket;
}
}
} | mit | C# |
087f20cb6c09f92448b3e198715e1e98c381da70 | Fix small view error in logs (#392) | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Server/Logs.cshtml | BTCPayServer/Views/Server/Logs.cshtml | @model BTCPayServer.Models.ServerViewModels.LogsViewModel
@{
ViewData.SetActivePageAndTitle(ServerNavPages.Logs);
}
<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" for="StatusMessage"/>
<div class="row">
<ul>
@foreach (var file in Model.LogFiles)
{
<li>
<a asp-action="LogsView" asp-route-file="@file.Name">@file.Name</a>
</li>
}
<li>
@if (Model.LogFileOffset > 0)
{
<a asp-action="LogsView" asp-route-offset="@(Model.LogFileOffset - 5)"><<</a>
}
Showing @Model.LogFileOffset - (@(Model.LogFileOffset+Model.LogFiles.Count)) of @Model.LogFileCount
@if ((Model.LogFileOffset+ Model.LogFiles.Count) < Model.LogFileCount)
{
<a asp-action="LogsView" asp-route-offset="@(Model.LogFileOffset + Model.LogFiles.Count)">>></a>
}
</li>
</ul>
@if (!string.IsNullOrEmpty(Model.Log))
{
<pre>
@Model.Log
</pre>
}
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| @model BTCPayServer.Models.ServerViewModels.LogsViewModel
@{
ViewData.SetActivePageAndTitle(ServerNavPages.Logs);
}
<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" for="StatusMessage"/>
<div class="row">
<ul>
@foreach (var file in Model.LogFiles)
{
<li>
<a asp-action="LogsView" asp-route-file="@file.Name">@file.Name</a>
</li>
}
<li>
@if (Model.LogFileOffset > 0)
{
<a asp-action="LogsView" asp-route-offset="@(Model.LogFileOffset - 5)"><<</a>
}
Showing @Model.LogFileOffset - (@Model.LogFileOffset+@Model.LogFiles.Count) of @Model.LogFileCount
@if ((Model.LogFileOffset+ Model.LogFiles.Count) < Model.LogFileCount)
{
<a asp-action="LogsView" asp-route-offset="@(Model.LogFileOffset + Model.LogFiles.Count)">>></a>
}
</li>
</ul>
@if (!string.IsNullOrEmpty(Model.Log))
{
<pre>
@Model.Log
</pre>
}
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| mit | C# |
9917f73bab3bb4ba749f0140f004e6fd25c2870d | Improve logging in retry logic & increase to 5 tries | BlythMeister/Ensconce,15below/Ensconce,BlythMeister/Ensconce,15below/Ensconce | src/Ensconce.Console/Retry.cs | src/Ensconce.Console/Retry.cs | using System;
using System.Collections.Generic;
using System.Threading;
namespace Ensconce.Console
{
/// <summary>
/// Retry logic applied from this Stack Overflow thread
/// http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic
/// </summary>
public static class Retry
{
private static readonly int retryCount = 5;
public static void Do(Action action, TimeSpan retryInterval)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval);
}
public static T Do<T>(Func<T> action, TimeSpan retryInterval)
{
var exceptions = new List<Exception>();
for (var retry = 0; retry < retryCount; retry++)
{
try
{
return action();
}
catch (Exception ex) when (retry + 1 < retryCount)
{
System.Console.Out.WriteLine($"Something went wrong on attempt {retry + 1} of {retryCount}, but we're going to try again in {retryInterval.TotalMilliseconds}ms...");
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
catch (Exception ex)
{
exceptions.Add(ex);
System.Console.Out.WriteLine($"Something went wrong on attempt {retry + 1} of {retryCount}, throwing all {exceptions.Count} exceptions...");
}
}
throw new AggregateException(exceptions);
}
}
}
| using System;
using System.Collections.Generic;
using System.Threading;
namespace Ensconce.Console
{
/// <summary>
/// Retry logic applied from this Stack Overflow thread
/// http://stackoverflow.com/questions/1563191/c-sharp-cleanest-way-to-write-retry-logic
/// </summary>
public static class Retry
{
public static void Do(Action action, TimeSpan retryInterval, int retryCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, retryCount);
}
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
{
var exceptions = new List<Exception>();
for (var retry = 0; retry < retryCount; retry++)
{
try
{
return action();
}
catch (Exception ex)
{
System.Console.Out.WriteLine("Something went wrong, but we're going to try again...");
System.Console.Out.WriteLine(ex.Message);
exceptions.Add(ex);
Thread.Sleep(retryInterval);
}
}
throw new AggregateException(exceptions);
}
}
}
| mit | C# |
db87da9a31ff1e2c667fa98efedec310aa74e76e | Add EnumerableAccess Factory to Resolver in the constructor | Domysee/Pather.CSharp | src/Pather.CSharp/Resolver.cs | src/Pather.CSharp/Resolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Pather.CSharp.PathElements;
namespace Pather.CSharp
{
public class Resolver
{
private IList<IPathElementFactory> pathElementTypes;
public Resolver()
{
pathElementTypes = new List<IPathElementFactory>();
pathElementTypes.Add(new PropertyFactory());
pathElementTypes.Add(new EnumerableAccessFactory());
}
public object Resolve(object target, string path)
{
var pathElementStrings = path.Split('.');
var pathElements = pathElementStrings.Select(pe => createPathElement(pe));
var tempResult = target;
foreach(var pathElement in pathElements)
{
tempResult = pathElement.Apply(tempResult);
}
var result = tempResult;
return result;
}
private IPathElement createPathElement(string pathElement)
{
//get the first applicable path element type
var pathElementFactory = pathElementTypes.Where(f => isApplicable(f, pathElement)).FirstOrDefault();
if (pathElementFactory == null)
throw new InvalidOperationException($"There is no applicable path element type for {pathElement}");
IPathElement result = pathElementFactory.Create(pathElement);
return result;
}
private bool isApplicable(IPathElementFactory factory, string pathElement)
{
return factory.IsApplicable(pathElement);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Reflection;
using Pather.CSharp.PathElements;
namespace Pather.CSharp
{
public class Resolver
{
private IList<IPathElementFactory> pathElementTypes;
public Resolver()
{
pathElementTypes = new List<IPathElementFactory>();
pathElementTypes.Add(new PropertyFactory());
}
public object Resolve(object target, string path)
{
var pathElementStrings = path.Split('.');
var pathElements = pathElementStrings.Select(pe => createPathElement(pe));
var tempResult = target;
foreach(var pathElement in pathElements)
{
tempResult = pathElement.Apply(tempResult);
}
var result = tempResult;
return result;
}
private IPathElement createPathElement(string pathElement)
{
//get the first applicable path element type
var pathElementFactory = pathElementTypes.Where(f => isApplicable(f, pathElement)).FirstOrDefault();
if (pathElementFactory == null)
throw new InvalidOperationException($"There is no applicable path element type for {pathElement}");
IPathElement result = pathElementFactory.Create(pathElement);
return result;
}
private bool isApplicable(IPathElementFactory factory, string pathElement)
{
return factory.IsApplicable(pathElement);
}
}
}
| mit | C# |
8d39b69a3b60ae57e970862c8830162120ac168a | Update CommonHub.cs | Enttoi/enttoi-api-dotnet,Enttoi/enttoi-api-dotnet,Enttoi/enttoi-api,Enttoi/enttoi-api | src/WebHost/Hubs/CommonHub.cs | src/WebHost/Hubs/CommonHub.cs | using Autofac;
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using WebHost.Logger;
using WebHost.Services;
using WebHost.Models;
using System.Threading;
namespace WebHost.Hubs
{
public class CommonHub : Hub
{
private readonly ILifetimeScope _hubLifetimeScope;
private readonly ITableService _tableService;
private readonly IDocumentsService _documentService;
public CommonHub(ILifetimeScope lifetimeScope)
{
// Create a lifetime scope for the hub.
_hubLifetimeScope = lifetimeScope.BeginLifetimeScope();
// Resolve dependencies from the hub lifetime scope
_documentService = _hubLifetimeScope.Resolve<IDocumentsService>(); // singleton
_tableService = _hubLifetimeScope.Resolve<ITableService>(); // singleton
}
public async Task RequestInitialState()
{
var onlineClients = _documentService.GetClients(true);
var states = await _tableService.GetSensorsStateAsync(onlineClients);
await Task.WhenAll(
states.Select(async state => await Clients.Client(Context.ConnectionId).SensorStatePush(new SensorClientUpdate
{
ClientId = state.ClientId,
SensorId = state.SensorId,
SensorType = state.SensorType,
NewState = state.State,
Timestamp = state.StateUpdatedOn
})));
}
protected override void Dispose(bool disposing)
{
if (disposing && _hubLifetimeScope != null)
_hubLifetimeScope.Dispose();
base.Dispose(disposing);
}
}
}
| using Autofac;
using Microsoft.AspNet.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using WebHost.Logger;
using WebHost.Services;
using WebHost.Models;
using System.Threading;
namespace WebHost.Hubs
{
public class CommonHub : Hub
{
private readonly ILifetimeScope _hubLifetimeScope;
private readonly ITableService _tableService;
private readonly IDocumentsService _documentService;
public CommonHub(ILifetimeScope lifetimeScope)
{
// Create a lifetime scope for the hub.
_hubLifetimeScope = lifetimeScope.BeginLifetimeScope();
// Resolve dependencies from the hub lifetime scope
_documentService = _hubLifetimeScope.Resolve<IDocumentsService>(); // singleton
_tableService = _hubLifetimeScope.Resolve<ITableService>(); // singleton
}
public async Task RequestInitalState()
{
var onlineClients = _documentService.GetClients(true);
var states = await _tableService.GetSensorsStateAsync(onlineClients);
await Task.WhenAll(
states.Select(async state => await Clients.Client(Context.ConnectionId).SensorStatePush(new SensorClientUpdate
{
ClientId = state.ClientId,
SensorId = state.SensorId,
SensorType = state.SensorType,
NewState = state.State,
Timestamp = state.StateUpdatedOn
})));
}
protected override void Dispose(bool disposing)
{
if (disposing && _hubLifetimeScope != null)
_hubLifetimeScope.Dispose();
base.Dispose(disposing);
}
}
} | mit | C# |
bef529f48d7529265b8e0b344f003d26c63b895b | Make telemetry break execution if debugger is attached instead of pushing report | axodox/AxoTools,axodox/AxoTools | AxoCover/Models/TelemetryManager.cs | AxoCover/Models/TelemetryManager.cs | using AxoCover.Models.Extensions;
using AxoCover.Properties;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace AxoCover.Models
{
public abstract class TelemetryManager : ITelemetryManager
{
protected IEditorContext _editorContext;
public bool IsTelemetryEnabled
{
get { return Settings.Default.IsTelemetryEnabled; }
set { Settings.Default.IsTelemetryEnabled = value; }
}
public TelemetryManager(IEditorContext editorContext)
{
_editorContext = editorContext;
Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
}
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var description = e.Exception.GetDescription();
if (description.Contains(nameof(AxoCover)))
{
_editorContext.WriteToLog(Resources.ExceptionEncountered);
_editorContext.WriteToLog(description);
if (Debugger.IsAttached)
{
Debugger.Break();
}
else
{
UploadExceptionAsync(e.Exception);
}
e.Handled = true;
}
}
public abstract Task<bool> UploadExceptionAsync(Exception exception);
}
}
| using AxoCover.Models.Extensions;
using AxoCover.Properties;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace AxoCover.Models
{
public abstract class TelemetryManager : ITelemetryManager
{
protected IEditorContext _editorContext;
public bool IsTelemetryEnabled
{
get { return Settings.Default.IsTelemetryEnabled; }
set { Settings.Default.IsTelemetryEnabled = value; }
}
public TelemetryManager(IEditorContext editorContext)
{
_editorContext = editorContext;
Application.Current.DispatcherUnhandledException += OnDispatcherUnhandledException;
}
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var description = e.Exception.GetDescription();
if (description.Contains(nameof(AxoCover)))
{
_editorContext.WriteToLog(Resources.ExceptionEncountered);
_editorContext.WriteToLog(description);
UploadExceptionAsync(e.Exception);
e.Handled = true;
}
}
public abstract Task<bool> UploadExceptionAsync(Exception exception);
}
}
| mit | C# |
35899465e500e27a5f13ef9293aed4558269148b | Update copyright date | hybrid1969/RogueSharp | RogueSharp/Properties/AssemblyInfo.cs | RogueSharp/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "RogueSharp" )]
[assembly: AssemblyDescription( "A portable class library for roguelike developers to provide utilities frequently used in roguelikes or 2D tile based games. Inspired by libtcod" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "Dreamers Design" )]
[assembly: AssemblyProduct( "RogueSharp" )]
[assembly: AssemblyCopyright( "Copyright © Faron Bracy 2014-2015" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// 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.0" )]
[assembly: AssemblyFileVersion( "2.0.0.0" )] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle( "RogueSharp" )]
[assembly: AssemblyDescription( "A portable class library for roguelike developers to provide utilities frequently used in roguelikes or 2D tile based games. Inspired by libtcod" )]
[assembly: AssemblyConfiguration( "" )]
[assembly: AssemblyCompany( "Dreamers Design" )]
[assembly: AssemblyProduct( "RogueSharp" )]
[assembly: AssemblyCopyright( "Copyright © Faron Bracy 2014" )]
[assembly: AssemblyTrademark( "" )]
[assembly: AssemblyCulture( "" )]
// 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.0" )]
[assembly: AssemblyFileVersion( "2.0.0.0" )] | mit | C# |
098df531f032a5ffb77a21f799595240be9b90b4 | Fix a null ref error submitting MobileMiner stats without Network Devices | IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner | MultiMiner.Win/Data/Configuration/NetworkDevices.cs | MultiMiner.Win/Data/Configuration/NetworkDevices.cs | using MultiMiner.Engine;
using MultiMiner.Utility.Serialization;
using System.Collections.Generic;
using System.IO;
namespace MultiMiner.Win.Data.Configuration
{
public class NetworkDevices
{
public class NetworkDevice
{
public string IPAddress { get; set; }
public int Port { get; set; }
}
public List<NetworkDevice> Devices { get; set; }
public NetworkDevices()
{
//set a default - null ref errors if submitting MobileMiner stats before scan is completed
Devices = new List<NetworkDevice>();
}
private static string NetworkDevicesConfigurationFileName()
{
return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml");
}
public void SaveNetworkDevicesConfiguration()
{
ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName());
}
public void LoadNetworkDevicesConfiguration()
{
Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName());
}
}
}
| using MultiMiner.Engine;
using MultiMiner.Utility.Serialization;
using System.Collections.Generic;
using System.IO;
namespace MultiMiner.Win.Data.Configuration
{
public class NetworkDevices
{
public class NetworkDevice
{
public string IPAddress { get; set; }
public int Port { get; set; }
}
public List<NetworkDevice> Devices { get; set; }
private static string NetworkDevicesConfigurationFileName()
{
return Path.Combine(ApplicationPaths.AppDataPath(), "NetworkDevicesConfiguration.xml");
}
public void SaveNetworkDevicesConfiguration()
{
ConfigurationReaderWriter.WriteConfiguration(Devices, NetworkDevicesConfigurationFileName());
}
public void LoadNetworkDevicesConfiguration()
{
Devices = ConfigurationReaderWriter.ReadConfiguration<List<NetworkDevice>>(NetworkDevicesConfigurationFileName());
}
}
}
| mit | C# |
2814c41d8d5a538bcaa9c7c4d748c69cdc6e1a05 | fix block pos overflow | noto0648/OrangeNBT | OrangeNBT.Data/BlockPos.cs | OrangeNBT.Data/BlockPos.cs | namespace OrangeNBT.Data
{
public struct BlockPos
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public BlockPos(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public override int GetHashCode()
{
return X ^ Y ^ Z;
}
public override bool Equals(object obj)
{
BlockPos pos = (BlockPos)obj;
return (pos.X == X && pos.Y == Y && pos.Z == Z);
}
public override string ToString()
{
return "(" + X + "," + Y + "," + Z + ")";
}
public static BlockPos operator +(BlockPos left, BlockPos right)
{
return new BlockPos(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
public static bool operator ==(BlockPos a, BlockPos b)
{
return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
}
public static bool operator !=(BlockPos a, BlockPos b)
{
return !(a == b);
}
}
}
| namespace OrangeNBT.Data
{
public class BlockPos
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
public BlockPos() { }
public BlockPos(int x, int y, int z)
{
X = x;
Y = y;
Z = z;
}
public override int GetHashCode()
{
return X ^ Y ^ Z;
}
public override bool Equals(object obj)
{
BlockPos pos = obj as BlockPos;
return pos == null ? false : (pos.X == X && pos.Y == Y && pos.Z == Z);
}
public override string ToString()
{
return "(" + X + "," + Y + "," + Z + ")";
}
public static BlockPos operator +(BlockPos left, BlockPos right)
{
return new BlockPos(left.X + right.X, left.Y + right.Y, left.Z + right.Z);
}
public static bool operator ==(BlockPos a, BlockPos b)
{
if (a == null || b == null) return false;
return a.X == b.X && a.Y == b.Y && a.Z == b.Z;
}
public static bool operator !=(BlockPos a, BlockPos b)
{
return !(a == b);
}
}
}
| mit | C# |
5c66bd33159ce4b581b243c9831bd19462570bf8 | prepare release | anonymousthing/ListenMoeClient | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Listen.moe Client")]
[assembly: AssemblyProduct("Listen.moe Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("Copyright 2017 Listen.moe. All rights reserved.")]
// 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("88b02799-425e-4622-a849-202adb19601b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Listen.moe Client")]
[assembly: AssemblyProduct("Listen.moe Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCopyright("Copyright 2017 Listen.moe. All rights reserved.")]
// 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("88b02799-425e-4622-a849-202adb19601b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.19.0")]
[assembly: AssemblyFileVersion("1.2.19.0")]
| mit | C# |
4508ad4915b4caaf73430fcd6a8183b8dee6f8a1 | Fix a nullability warning in AliasingVisitor | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/Framework/Framework/Compilation/AliasingVisitor.cs | src/Framework/Framework/Compilation/AliasingVisitor.cs | using System.Linq;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
namespace DotVVM.Framework.Compilation
{
public class AliasingVisitor : ResolvedControlTreeVisitor
{
public override void VisitControl(ResolvedControl control)
{
base.VisitControl(control);
// create a copy so that the aliases can be removed
var props = control.Properties.ToList();
foreach(var pair in props)
{
if (pair.Key is DotvvmPropertyAlias alias)
{
if (pair.Value.DothtmlNode is not null && control.TryGetProperty(alias.Aliased, out _))
{
pair.Value.DothtmlNode.AddError($"'{pair.Key.FullName}' is an alias for "
+ $"'{alias.Aliased.FullName}'. Both cannot be set at once.");
}
else
{
pair.Value.Property = alias.Aliased;
control.SetProperty(pair.Value);
control.RemoveProperty(pair.Key);
}
}
}
}
}
}
| using System.Linq;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
namespace DotVVM.Framework.Compilation
{
public class AliasingVisitor : ResolvedControlTreeVisitor
{
public override void VisitControl(ResolvedControl control)
{
base.VisitControl(control);
// create a copy so that the aliases can be removed
var props = control.Properties.ToList();
foreach(var pair in props)
{
if (pair.Key is DotvvmPropertyAlias alias)
{
if (control.TryGetProperty(alias.Aliased, out _))
{
pair.Value.DothtmlNode.AddError($"'{pair.Key.FullName}' is an alias for "
+ $"'{alias.Aliased.FullName}'. Both cannot be set at once.");
}
else
{
pair.Value.Property = alias.Aliased;
control.SetProperty(pair.Value);
control.RemoveProperty(pair.Key);
}
}
}
}
}
}
| apache-2.0 | C# |
5972fa000436d68a2ffe4758e9f601efb48e553f | Update EmailTokenProvider.cs | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Identity/Extensions.Core/src/EmailTokenProvider.cs | src/Identity/Extensions.Core/src/EmailTokenProvider.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// TokenProvider that generates tokens from the user's security stamp and notifies a user via email.
/// </summary>
/// <typeparam name="TUser">The type used to represent a user.</typeparam>
public class EmailTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser>
where TUser : class
{
/// <summary>
/// Checks if a two-factor authentication token can be generated for the specified <paramref name="user"/>.
/// </summary>
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param>
/// <param name="user">The <typeparamref name="TUser"/> to check for the possibility of generating a two-factor authentication token.</param>
/// <returns>True if the user has an email address set, otherwise false.</returns>
public override async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{
var email = await manager.GetEmailAsync(user);
return !string.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user);
}
/// <summary>
/// Returns the a value for the user used as entropy in the generated token.
/// </summary>
/// <param name="purpose">The purpose of the two-factor authentication token.</param>
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param>
/// <param name="user">The <typeparamref name="TUser"/> to check for the possibility of generating a two-factor authentication token.</param>
/// <returns>A string suitable for use as entropy in token generation.</returns>
public override async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager,
TUser user)
{
var email = await manager.GetEmailAsync(user);
return $"{Email}:{purpose}:{email}";
}
}
}
| using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// TokenProvider that generates tokens from the user's security stamp and notifies a user via email.
/// </summary>
/// <typeparam name="TUser">The type used to represent a user.</typeparam>
public class EmailTokenProvider<TUser> : TotpSecurityStampBasedTokenProvider<TUser>
where TUser : class
{
/// <summary>
/// Checks if a two factor authentication token can be generated for the specified <paramref name="user"/>.
/// </summary>
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param>
/// <param name="user">The <typeparamref name="TUser"/> to check for the possibility of generating a two factor authentication token.</param>
/// <returns>True if the user has an email address set, otherwise false.</returns>
public override async Task<bool> CanGenerateTwoFactorTokenAsync(UserManager<TUser> manager, TUser user)
{
var email = await manager.GetEmailAsync(user);
return !string.IsNullOrWhiteSpace(email) && await manager.IsEmailConfirmedAsync(user);
}
/// <summary>
/// Returns the a value for the user used as entropy in the generated token.
/// </summary>
/// <param name="purpose">The purpose of the two factor authentication token.</param>
/// <param name="manager">The <see cref="UserManager{TUser}"/> to retrieve the <paramref name="user"/> from.</param>
/// <param name="user">The <typeparamref name="TUser"/> to check for the possibility of generating a two factor authentication token.</param>
/// <returns>A string suitable for use as entropy in token generation.</returns>
public override async Task<string> GetUserModifierAsync(string purpose, UserManager<TUser> manager,
TUser user)
{
var email = await manager.GetEmailAsync(user);
return "Email:" + purpose + ":" + email;
}
}
} | apache-2.0 | C# |
22d91d7976f500e674ec222803a7994a3af01a27 | Handle null user agent in statistics collector | n2cms/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,bussemac/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,DejanMilicic/n2cms,bussemac/n2cms,SntsDev/n2cms,DejanMilicic/n2cms,nimore/n2cms,n2cms/n2cms,bussemac/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,bussemac/n2cms,nimore/n2cms,nimore/n2cms,DejanMilicic/n2cms,DejanMilicic/n2cms,EzyWebwerkstaden/n2cms,nimore/n2cms,bussemac/n2cms,SntsDev/n2cms,n2cms/n2cms | src/Mvc/MvcTemplates/N2/Statistics/StatisticsLogger.cs | src/Mvc/MvcTemplates/N2/Statistics/StatisticsLogger.cs | using N2.Engine;
using N2.Plugin;
using N2.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace N2.Management.Statistics
{
[Service]
public class StatisticsLogger : IAutoStart
{
private EventBroker broker;
private IWebContext context;
private Collector filler;
private StatisticsRepository repository;
static Logger<StatisticsLogger> log;
public StatisticsLogger(EventBroker broker, IWebContext context, Collector collector, StatisticsRepository repository)
{
this.broker = broker;
this.context = context;
this.filler = collector;
this.repository = repository;
}
void OnDomainUnload(object sender, EventArgs e)
{
try
{
var buckets = filler.CheckoutBuckets();
repository.Save(buckets);
}
catch (Exception ex)
{
log.Error(ex);
}
}
static Regex crawlerExpression = new Regex(@"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google", RegexOptions.IgnoreCase);
private void OnEndRequest(object sender, EventArgs e)
{
if (context.HttpContext.GetViewPreference(Edit.ViewPreference.None) == Edit.ViewPreference.None)
if (context.HttpContext.Request.UserAgent != null && !crawlerExpression.IsMatch(context.HttpContext.Request.UserAgent))
filler.RegisterView(context.CurrentPath);
}
public void Start()
{
broker.EndRequest += OnEndRequest;
try
{
AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
}
catch (Exception ex)
{
log.Error(ex);
}
}
public void Stop()
{
broker.EndRequest -= OnEndRequest;
try
{
AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload;
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
} | using N2.Engine;
using N2.Plugin;
using N2.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace N2.Management.Statistics
{
[Service]
public class StatisticsLogger : IAutoStart
{
private EventBroker broker;
private IWebContext context;
private Collector filler;
private StatisticsRepository repository;
static Logger<StatisticsLogger> log;
public StatisticsLogger(EventBroker broker, IWebContext context, Collector collector, StatisticsRepository repository)
{
this.broker = broker;
this.context = context;
this.filler = collector;
this.repository = repository;
}
void OnDomainUnload(object sender, EventArgs e)
{
try
{
var buckets = filler.CheckoutBuckets();
repository.Save(buckets);
}
catch (Exception ex)
{
log.Error(ex);
}
}
static Regex crawlerExpression = new Regex(@"bot|crawler|baiduspider|80legs|ia_archiver|voyager|curl|wget|yahoo! slurp|mediapartners-google", RegexOptions.IgnoreCase);
private void OnEndRequest(object sender, EventArgs e)
{
if (context.HttpContext.GetViewPreference(Edit.ViewPreference.None) == Edit.ViewPreference.None)
if (!crawlerExpression.IsMatch(context.HttpContext.Request.UserAgent))
filler.RegisterView(context.CurrentPath);
}
public void Start()
{
broker.EndRequest += OnEndRequest;
try
{
AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;
}
catch (Exception ex)
{
log.Error(ex);
}
}
public void Stop()
{
broker.EndRequest -= OnEndRequest;
try
{
AppDomain.CurrentDomain.DomainUnload -= OnDomainUnload;
}
catch (Exception ex)
{
log.Error(ex);
}
}
}
} | lgpl-2.1 | C# |
a4ea697425009460e515b9a656b44dfeaa1a25e3 | Update copyright | chkn/Tempest | Desktop/Tempest/Properties/AssemblyInfo.cs | Desktop/Tempest/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle ("Tempest")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Eric Maupin")]
[assembly: AssemblyProduct ("Tempest")]
[assembly: AssemblyCopyright ("Copyright © Eric Maupin 2010-2013")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
[assembly: ComVisible (false)]
[assembly: Guid ("a4bdac1c-a9d5-4be2-8fb5-14d7210d602f")]
[assembly: AssemblyVersion ("0.8.0.0")]
[assembly: AssemblyFileVersion ("0.8.0.0")]
[assembly: InternalsVisibleTo ("Tempest.Tests")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle ("Tempest")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Eric Maupin")]
[assembly: AssemblyProduct ("Tempest")]
[assembly: AssemblyCopyright ("Copyright © Eric Maupin 2010")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
[assembly: ComVisible (false)]
[assembly: Guid ("a4bdac1c-a9d5-4be2-8fb5-14d7210d602f")]
[assembly: AssemblyVersion ("0.8.0.0")]
[assembly: AssemblyFileVersion ("0.8.0.0")]
[assembly: InternalsVisibleTo ("Tempest.Tests")] | mit | C# |
cc8f898a84c18b47a8e20c3d30b38aa6cf41f7d4 | Use a ReadOnlySpanList for JsonBackgroundSyntax.BackgroundSymbols. | PenguinF/sandra-three | Eutherion/Shared/Text/Json/JsonBackgroundSyntax.cs | Eutherion/Shared/Text/Json/JsonBackgroundSyntax.cs | #region License
/*********************************************************************************
* JsonBackgroundSyntax.cs
*
* Copyright (c) 2004-2019 Henk Nicolai
*
* 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;
namespace Eutherion.Text.Json
{
/// <summary>
/// Represents a node with background symbols in an abstract json syntax tree.
/// </summary>
public sealed class JsonBackgroundSyntax : ISpan
{
/// <summary>
/// Gets the empty <see cref="JsonBackgroundSyntax"/>.
/// </summary>
public static readonly JsonBackgroundSyntax Empty = new JsonBackgroundSyntax(ReadOnlySpanList<JsonSymbol>.Empty);
/// <summary>
/// Initializes a new instance of <see cref="JsonBackgroundSyntax"/>.
/// </summary>
/// <param name="source">
/// The source enumeration of <see cref="JsonSymbol"/>.
/// </param>
/// <returns>
/// The new <see cref="JsonBackgroundSyntax"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is null.
/// </exception>
public static JsonBackgroundSyntax Create(IEnumerable<JsonSymbol> source)
{
var readOnlyBackground = ReadOnlySpanList<JsonSymbol>.Create(source);
if (readOnlyBackground.Count == 0) return Empty;
return new JsonBackgroundSyntax(readOnlyBackground);
}
/// <summary>
/// Gets the read-only list with background symbols.
/// </summary>
public ReadOnlySpanList<JsonSymbol> BackgroundSymbols { get; }
/// <summary>
/// Gets the length of the text span corresponding with this syntax.
/// </summary>
public int Length => BackgroundSymbols.Length;
private JsonBackgroundSyntax(ReadOnlySpanList<JsonSymbol> backgroundSymbols) => BackgroundSymbols = backgroundSymbols;
}
}
| #region License
/*********************************************************************************
* JsonBackgroundSyntax.cs
*
* Copyright (c) 2004-2019 Henk Nicolai
*
* 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 Eutherion.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Eutherion.Text.Json
{
/// <summary>
/// Represents a node with background symbols in an abstract json syntax tree.
/// </summary>
public sealed class JsonBackgroundSyntax : ISpan
{
/// <summary>
/// Gets the empty <see cref="JsonBackgroundSyntax"/>.
/// </summary>
public static readonly JsonBackgroundSyntax Empty = new JsonBackgroundSyntax(ReadOnlyList<JsonSymbol>.Empty, 0);
/// <summary>
/// Initializes a new instance of <see cref="JsonBackgroundSyntax"/>.
/// </summary>
/// <param name="source">
/// The source enumeration of <see cref="JsonSymbol"/>.
/// </param>
/// <returns>
/// The new <see cref="JsonBackgroundSyntax"/>.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is null.
/// </exception>
public static JsonBackgroundSyntax Create(IEnumerable<JsonSymbol> source)
{
var readOnlyBackground = ReadOnlyList<JsonSymbol>.Create(source);
if (readOnlyBackground.Count == 0) return Empty;
return new JsonBackgroundSyntax(readOnlyBackground, readOnlyBackground.Sum(x => x.Length));
}
/// <summary>
/// Gets the read-only list with background symbols.
/// </summary>
public ReadOnlyList<JsonSymbol> BackgroundSymbols { get; }
/// <summary>
/// Gets the length of the text span corresponding with this syntax.
/// </summary>
public int Length { get; }
private JsonBackgroundSyntax(ReadOnlyList<JsonSymbol> backgroundSymbols, int length)
{
BackgroundSymbols = ReadOnlyList<JsonSymbol>.Create(backgroundSymbols);
Length = length;
}
}
}
| apache-2.0 | C# |
8aa0df7720ba91c1309584a375e48b8ec329add3 | test fix build | jezzay/Test-Travis-CI,jezzay/Test-Travis-CI | TestWebApp/TestWebApp/Controllers/HomeController.cs | TestWebApp/TestWebApp/Controllers/HomeController.cs | using System.Web.Mvc;
namespace TestWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page test";
return View();
}
}
}
| using System.Web.Mvc;
namespace TestWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page test"
return View();
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.