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 |
|---|---|---|---|---|---|---|---|---|
7e4450ecea8c16f852ff6f88689a8fe9afbb1145 | Update ServiceProviderFixture.cs | tiksn/TIKSN-Framework | TIKSN.Framework.IntegrationTests/ServiceProviderFixture.cs | TIKSN.Framework.IntegrationTests/ServiceProviderFixture.cs | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using TIKSN.Data.Mongo;
using TIKSN.DependencyInjection;
using TIKSN.Framework.IntegrationTests.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests
{
public class ServiceProviderFixture : IDisposable
{
private readonly IHost host;
public ServiceProviderFixture()
{
host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddFrameworkPlatform();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<CoreModule>();
builder.RegisterModule<PlatformModule>();
builder.RegisterType<TestMongoRepository>().As<ITestMongoRepository>().InstancePerLifetimeScope();
builder.RegisterType<TestMongoDatabaseProvider>().As<IMongoDatabaseProvider>().SingleInstance();
builder.RegisterType<TestMongoClientProvider>().As<IMongoClientProvider>().SingleInstance();
})
.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(GetInMemoryConfiguration()); })
.Build();
static Dictionary<string, string> GetInMemoryConfiguration()
{
return new()
{
{"ConnectionStrings:Mongo", "mongodb://localhost:27017/TIKSN_Framework_IntegrationTests?w=majority"}
};
}
}
public IServiceProvider Services => host.Services;
public void Dispose()
{
host?.Dispose();
}
}
} | using System;
using System.Collections.Generic;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using TIKSN.Data.Mongo;
using TIKSN.DependencyInjection;
using TIKSN.Framework.IntegrationTests.Data.Mongo;
namespace TIKSN.Framework.IntegrationTests
{
public class ServiceProviderFixture : IDisposable
{
private readonly IHost host;
public ServiceProviderFixture()
{
host = Host.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services.AddFrameworkPlatform();
})
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<CoreModule>();
builder.RegisterModule<PlatformModule>();
builder.RegisterType<TestMongoRepository>().As<ITestMongoRepository>().InstancePerLifetimeScope();
builder.RegisterType<TestMongoDatabaseProviderBase>().As<IMongoDatabaseProvider>().SingleInstance();
builder.RegisterType<TestMongoClientProvider>().As<IMongoClientProvider>().SingleInstance();
})
.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(GetInMemoryConfiguration()); })
.Build();
static Dictionary<string, string> GetInMemoryConfiguration()
{
return new()
{
{"ConnectionStrings:Mongo", "mongodb://localhost:27017/TIKSN_Framework_IntegrationTests?w=majority"}
};
}
}
public IServiceProvider Services => host.Services;
public void Dispose()
{
host?.Dispose();
}
}
} | mit | C# |
80a1f2044ecf77d02a9f02576ed58608e18c77fa | Add UserAsyncTest | ats124/backlog4net | src/Backlog4net.Test/UserMethodsTest.cs | src/Backlog4net.Test/UserMethodsTest.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Remoting;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Backlog4net.Test
{
using Api;
using Api.Option;
using Backlog4net.Internal.Json;
using Backlog4net.Internal.Json.Activities;
using Conf;
using Newtonsoft.Json;
using TestConfig;
[TestClass]
public class UserMethodsTest
{
private static BacklogClient client;
private static GeneralConfig generalConfig;
private static string projectKey;
private static long projectId;
[ClassInitialize]
public static async Task SetupClient(TestContext context)
{
generalConfig = GeneralConfig.Instance.Value;
var conf = new BacklogJpConfigure(generalConfig.SpaceKey);
conf.ApiKey = generalConfig.ApiKey;
client = new BacklogClientFactory(conf).NewClient();
var users = await client.GetUsersAsync();
projectKey = generalConfig.ProjectKey;
var project = await client.GetProjectAsync(projectKey);
projectId = project.Id;
}
[TestMethod]
public async Task UserAsyncTest()
{
var testUser1 = await client.CreateUserAsync(new CreateUserParams("testuser1", "password", "tesetuser1name", "testuser1@exsample.com", UserRoleType.Admin));
Assert.AreNotEqual(testUser1.Id, 0L);
Assert.AreEqual(testUser1.UserId, "testuser1");
Assert.AreEqual(testUser1.Name, "tesetuser1name");
Assert.AreEqual(testUser1.MailAddress, "testuser1@exsample.com");
Assert.AreEqual(testUser1.RoleType, UserRoleType.Admin);
var testUser1Get = await client.GetUserAsync(testUser1.Id);
Assert.AreEqual(testUser1Get.Id, testUser1.Id);
Assert.AreEqual(testUser1Get.UserId, testUser1.UserId);
Assert.AreEqual(testUser1Get.Name, testUser1.Name);
Assert.AreEqual(testUser1Get.MailAddress, testUser1.MailAddress);
Assert.AreEqual(testUser1Get.RoleType, testUser1.RoleType);
var users = await client.GetUsersAsync();
Assert.IsTrue(users.Any(x => x.Id == testUser1.Id && x.UserId == testUser1.UserId));
var userDeleted = await client.DeleteUserAsync(testUser1.Id);
Assert.AreEqual(userDeleted.Id, testUser1.Id);
Assert.AreEqual(userDeleted.UserId, testUser1.UserId);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Remoting;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Backlog4net.Test
{
using Api;
using Api.Option;
using Backlog4net.Internal.Json;
using Backlog4net.Internal.Json.Activities;
using Conf;
using Newtonsoft.Json;
using TestConfig;
[TestClass]
public class UserMethodsTest
{
private static BacklogClient client;
private static GeneralConfig generalConfig;
private static string projectKey;
private static long projectId;
[ClassInitialize]
public static async Task SetupClient(TestContext context)
{
generalConfig = GeneralConfig.Instance.Value;
var conf = new BacklogJpConfigure(generalConfig.SpaceKey);
conf.ApiKey = generalConfig.ApiKey;
client = new BacklogClientFactory(conf).NewClient();
var users = await client.GetUsersAsync();
projectKey = generalConfig.ProjectKey;
var project = await client.GetProjectAsync(projectKey);
projectId = project.Id;
}
}
}
| mit | C# |
fc573a6975446a5ce282de392a7a836a07ff44f5 | Fix contract, closes #2933 | quails4Eva/NSwag,RSuter/NSwag,RSuter/NSwag,quails4Eva/NSwag,RSuter/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,RSuter/NSwag | src/NSwag.Core/OpenApiServerVariable.cs | src/NSwag.Core/OpenApiServerVariable.cs | //-----------------------------------------------------------------------
// <copyright file="OpenApiServerVariable.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace NSwag
{
/// <summary>Describes an OpenAPI server variable.</summary>
public class OpenApiServerVariable
{
/// <summary>Gets or sets the enum of the server.</summary>
[JsonProperty(PropertyName = "enum", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public ICollection<string> Enum { get; } = new Collection<string>();
/// <summary>Gets or sets the variables of the server.</summary>
[JsonProperty(PropertyName = "default", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string Default { get; set; }
/// <summary>Gets or sets the description of the server.</summary>
[JsonProperty(PropertyName = "description", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string Description { get; set; }
}
} | //-----------------------------------------------------------------------
// <copyright file="OpenApiServerVariable.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/RicoSuter/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace NSwag
{
/// <summary>Describes an OpenAPI server variable.</summary>
public class OpenApiServerVariable
{
/// <summary>Gets or sets the URL of the server.</summary>
[JsonProperty(PropertyName = "url", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public ICollection<string> Enum { get; } = new Collection<string>();
/// <summary>Gets or sets the variables of the server.</summary>
[JsonProperty(PropertyName = "default", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string Default { get; set; }
/// <summary>Gets or sets the description of the server.</summary>
[JsonProperty(PropertyName = "description", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public string Description { get; set; }
}
} | mit | C# |
511e152c672a9665569d29906f1ef1b524ab755b | Hide post link if not "writer" | mattgwagner/alert-roster | alert-roster.web/Views/Shared/_Layout.cshtml | alert-roster.web/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/libs")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Alert Roster", "Index", "Home", null, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("About", "About", "Home")</li>
<!-- <li>@Html.ActionLink("Subscribe", "Subscribe", "Home")</li> -->
@if (alert_roster.web.Models.Authentication.ReadWriteRole == User.Identity.Name)
{
<li>@Html.ActionLink("Post New Message", "New", "Home")</li>
<li>@Html.ActionLink("Subscriptions", "Subscriptions", "Home")</li>
}
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<footer>
<small>© @DateTime.Now.Year - <a href="http://github.com/mattgwagner/alert-roster">Alert Roster</a></small>
</footer>
</div>
@RenderSection("scripts", required: false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/libs")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Alert Roster", "Index", "Home", null, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("About", "About", "Home")</li>
<!-- <li>@Html.ActionLink("Subscribe", "Subscribe", "Home")</li> -->
<li>@Html.ActionLink("Post New Message", "New", "Home")</li>
</ul>
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<footer>
<small>© @DateTime.Now.Year - <a href="http://github.com/mattgwagner/alert-roster">Alert Roster</a></small>
</footer>
</div>
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
29be14e8daf07e020f4b6638f93a72c359ab79c9 | add text analysis | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string product_quantity { get; set; }
public string product_type { get; set; }
public string code_info { get; set; }
public string reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string recall_number { get; set; }
public string recalling_firm { get; set; }
public string voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string status { get; set; }
public DateTime date_last_indexed { get; set; }
//ICitations
public string act_cfr { get; set; }
public string program_area { get; set; }
public string description_short { get; set; }
public string description_long { get; set; }
public DateTime end_date { get; set; }
//IClassification
public string district_decision { get; set; }
public string district { get; set; }
public DateTime inspection_end_date { get; set; }
public string center { get; set; }
public string project_area { get; set; }
public string legal_name { get; set; }
//IRefusal
public string fei_number { get; set; }
public string product_code { get; set; }
public string product_code_description { get; set; }
public DateTime refusal_date { get; set; }
public string entry_number { get; set; }
public string rfrnc_doc_id { get; set; }
public string line_number { get; set; }
public string line_sfx_id { get; set; }
public string fda_sample_analysis { get; set; }
public string private_lab_analysis { get; set; }
public string refusal_charges { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string product_quantity { get; set; }
public string product_type { get; set; }
public string code_info { get; set; }
public string reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string recall_number { get; set; }
public string recalling_firm { get; set; }
public string voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string status { get; set; }
public DateTime date_last_indexed { get; set; }
//ICitations
public string act_cfr { get; set; }
public string program_area { get; set; }
public string description_short { get; set; }
public string description_long { get; set; }
public DateTime end_date { get; set; }
//IClassification
public string district_decision { get; set; }
public string district { get; set; }
public DateTime inspection_end_date { get; set; }
public string center { get; set; }
public string project_area { get; set; }
public string legal_name { get; set; }
//IRefusal
public string fei_number { get; set; }
public string product_code { get; set; }
public string product_code_description { get; set; }
public DateTime refusal_date { get; set; }
public string entry_number { get; set; }
public string rfrnc_doc_id { get; set; }
public string line_number { get; set; }
public string line_sfx_id { get; set; }
}
}
| apache-2.0 | C# |
b89c3817e9d79b7af5c8b19cd2c952cdc50ef46c | Add command work | Julien-Mialon/XamarinStore.Forms | XamarinStore.Forms/XamarinStore.Forms/XamarinStore.Forms/ViewModels/BasketPageViewModel.cs | XamarinStore.Forms/XamarinStore.Forms/XamarinStore.Forms/ViewModels/BasketPageViewModel.cs | using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Acr.XamForms.UserDialogs;
using Xamarin.Forms;
using XamarinStore.Forms.Data;
using XamarinStore.Forms.Helpers;
using XamarinStore.Forms.UIModels;
using XamarinStore.Forms.Views;
using XLabs.Ioc;
namespace XamarinStore.Forms.ViewModels
{
public class BasketPageViewModel : BaseViewModel
{
private List<ProductUIModel> _products;
private bool _isBasketEmpty;
public bool IsBasketEmpty
{
get { return _isBasketEmpty; }
set { SetProperty<bool>(ref _isBasketEmpty, value); }
}
public List<ProductUIModel> Products
{
get { return _products; }
set { SetProperty<List<ProductUIModel>>(ref _products, value); }
}
public ICommand CheckoutCommand { get; private set; }
public BasketPageViewModel()
{
IsBasketEnabled = false;
CheckoutCommand = new Command(CheckoutAction);
Products = WebService.Shared.CurrentOrder.Products.Select(x =>
{
ProductUIModel result = new ProductUIModel(x)
{
ProductName = x.Name,
ProductPrice = x.PriceDescription.ToUpperInvariant(),
};
#pragma warning disable 4014
ImageHelper.SetImageSource(result, (p, source) => p.ProductImage = source, x.ImageForSize(320));
#pragma warning restore 4014
return result;
}).ToList();
IsBasketEmpty = Products.Count == 0;
}
private void CheckoutAction()
{
IUserDialogService dialogService = Resolver.Resolve<IUserDialogService>();
dialogService.Toast("CheckoutAction !");
// Maybe it should redirect you to the LoginPage hm ?
// Navigation.PushAsync(NavigationHelper.GetPage<LoginPage>());
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinStore.Forms.Data;
using XamarinStore.Forms.Helpers;
using XamarinStore.Forms.UIModels;
using XamarinStore.Forms.Views;
namespace XamarinStore.Forms.ViewModels
{
public class BasketPageViewModel : BaseViewModel
{
private List<ProductUIModel> _products;
private bool _isBasketEmpty;
public bool IsBasketEmpty
{
get { return _isBasketEmpty; }
set { SetProperty<bool>(ref _isBasketEmpty, value); }
}
public List<ProductUIModel> Products
{
get { return _products; }
set { SetProperty<List<ProductUIModel>>(ref _products, value); }
}
public ICommand CheckoutCommand { get; private set; }
public BasketPageViewModel()
{
IsBasketEnabled = false;
// Maybe you should link the checkout button with a real action ?
// CheckoutCommand = new Command(CheckoutAction);
Products = WebService.Shared.CurrentOrder.Products.Select(x =>
{
ProductUIModel result = new ProductUIModel(x)
{
ProductName = x.Name,
ProductPrice = x.PriceDescription.ToUpperInvariant(),
};
#pragma warning disable 4014
ImageHelper.SetImageSource(result, (p, source) => p.ProductImage = source, x.ImageForSize(320));
#pragma warning restore 4014
return result;
}).ToList();
IsBasketEmpty = Products.Count == 0;
}
private void CheckoutAction()
{
Navigation.PushAsync(NavigationHelper.GetPage<LoginPage>());
}
}
} | mit | C# |
64b834686ebf680373919499e1e12651a81fc530 | test for no denominations | dgg/nmoneys,dgg/nmoneys | src/NMoneys.Tests/Change/ChangeCountTester.cs | src/NMoneys.Tests/Change/ChangeCountTester.cs | using System.Linq;
using NMoneys.Change;
using NMoneys.Extensions;
using NUnit.Framework;
namespace NMoneys.Tests.Change
{
[TestFixture]
public class ChangeCountTester
{
[Test]
public void ChangeCount_Zero_OneWayOfChoosingNoDenominations()
{
var zero = Money.Zero();
Denomination[] any = { new Denomination(1) };
Assert.That(zero.ChangeCount(any), Is.EqualTo(1u));
}
[Test]
public void ChangeCount_NotPossibleToChange_Zero()
{
Money notCompletelyChangeable = 7m.Xxx();
Denomination[] denominations = { new Denomination(4m), new Denomination(2m) };
Assert.That(notCompletelyChangeable.ChangeCount(denominations), Is.EqualTo(0u));
}
private static readonly object[] changeCountSamples =
{
new object[] {4m, new decimal[]{1, 2, 3}, 4u},
new object[] {10m, new decimal[]{2, 5, 3, 6}, 5u},
new object[] {6m, new decimal[]{1, 3, 4}, 4u},
new object[] {5m, new decimal[]{1, 2, 3}, 5u},
};
[Test, TestCaseSource(nameof(changeCountSamples))]
public void ChangeCount_PossibleChange_AccordingToSamples(decimal amount, decimal[] denominationValues, uint count)
{
Money money = new Money(amount);
Denomination[] denominations = denominationValues.Select(d => new Denomination(d)).ToArray();
Assert.That(money.ChangeCount(denominations), Is.EqualTo(count));
}
[Test]
public void ChangeCount_NoDenominations_Zero()
{
Assert.That(5m.Usd().ChangeCount(), Is.EqualTo(0));
}
}
} | using System.Linq;
using NMoneys.Change;
using NMoneys.Extensions;
using NUnit.Framework;
namespace NMoneys.Tests.Change
{
[TestFixture]
public class ChangeCountTester
{
[Test]
public void ChangeCount_Zero_OneWayOfChoosingNoDenominations()
{
var zero = Money.Zero();
Denomination[] any = { new Denomination(1) };
Assert.That(zero.ChangeCount(any), Is.EqualTo(1u));
}
[Test]
public void ChangeCount_NotPossibleToChange_Zero()
{
Money notCompletelyChangeable = 7m.Xxx();
Denomination[] denominations = { new Denomination(4m), new Denomination(2m) };
Assert.That(notCompletelyChangeable.ChangeCount(denominations), Is.EqualTo(0u));
}
private static readonly object[] changeCountSamples =
{
new object[] {4m, new decimal[]{1, 2, 3}, 4u},
new object[] {10m, new decimal[]{2, 5, 3, 6}, 5u},
new object[] {6m, new decimal[]{1, 3, 4}, 4u},
new object[] {5m, new decimal[]{1, 2, 3}, 5u},
};
[Test, TestCaseSource(nameof(changeCountSamples))]
public void ChangeCount_PossibleChange_AccordingToSamples(decimal amount, decimal[] denominationValues, uint count)
{
Money money = new Money(amount);
Denomination[] denominations = denominationValues.Select(d => new Denomination(d)).ToArray();
Assert.That(money.ChangeCount(denominations), Is.EqualTo(count));
}
}
} | bsd-3-clause | C# |
ef13ae484ed88fb30d9904bd61314fcecb832d56 | fix fragmented error message | DefactoSoftware/JSONAPI.NET,SathishN/JSONAPI.NET,SphtKr/JSONAPI.NET,danshapir/JSONAPI.NET,JSONAPIdotNET/JSONAPI.NET | JSONAPI/Core/JsonApiConfiguration.cs | JSONAPI/Core/JsonApiConfiguration.cs | using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using JSONAPI.ActionFilters;
using JSONAPI.Http;
using JSONAPI.Json;
using JSONAPI.Payload;
namespace JSONAPI.Core
{
/// <summary>
/// Configuration API for JSONAPI.NET
/// </summary>
public class JsonApiConfiguration
{
private readonly IModelManager _modelManager;
private Func<IQueryablePayloadBuilder> _payloadBuilderFactory;
/// <summary>
/// Creates a new configuration
/// </summary>
public JsonApiConfiguration(IModelManager modelManager)
{
if (modelManager == null) throw new Exception("You must provide a model manager to begin configuration.");
_modelManager = modelManager;
_payloadBuilderFactory = () => new DefaultQueryablePayloadBuilderConfiguration().GetBuilder(modelManager);
}
/// <summary>
/// Allows configuring the default queryable payload builder
/// </summary>
/// <param name="configurationAction">Provides access to a fluent DefaultQueryablePayloadBuilderConfiguration object</param>
/// <returns>The same configuration object the method was called on.</returns>
public JsonApiConfiguration UsingDefaultQueryablePayloadBuilder(Action<DefaultQueryablePayloadBuilderConfiguration> configurationAction)
{
_payloadBuilderFactory = () =>
{
var configuration = new DefaultQueryablePayloadBuilderConfiguration();
configurationAction(configuration);
return configuration.GetBuilder(_modelManager);
};
return this;
}
/// <summary>
/// Applies the running configuration to an HttpConfiguration instance
/// </summary>
/// <param name="httpConfig">The HttpConfiguration to apply this JsonApiConfiguration to</param>
public void Apply(HttpConfiguration httpConfig)
{
var formatter = new JsonApiFormatter(_modelManager);
httpConfig.Formatters.Clear();
httpConfig.Formatters.Add(formatter);
var queryablePayloadBuilder = _payloadBuilderFactory();
httpConfig.Filters.Add(new JsonApiQueryableAttribute(queryablePayloadBuilder));
httpConfig.Services.Replace(typeof (IHttpControllerSelector),
new PascalizedControllerSelector(httpConfig));
}
}
}
| using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using JSONAPI.ActionFilters;
using JSONAPI.Http;
using JSONAPI.Json;
using JSONAPI.Payload;
namespace JSONAPI.Core
{
/// <summary>
/// Configuration API for JSONAPI.NET
/// </summary>
public class JsonApiConfiguration
{
private readonly IModelManager _modelManager;
private Func<IQueryablePayloadBuilder> _payloadBuilderFactory;
/// <summary>
/// Creates a new configuration
/// </summary>
public JsonApiConfiguration(IModelManager modelManager)
{
if (modelManager == null) throw new Exception("You must provide ");
_modelManager = modelManager;
_payloadBuilderFactory = () => new DefaultQueryablePayloadBuilderConfiguration().GetBuilder(modelManager);
}
/// <summary>
/// Allows configuring the default queryable payload builder
/// </summary>
/// <param name="configurationAction">Provides access to a fluent DefaultQueryablePayloadBuilderConfiguration object</param>
/// <returns>The same configuration object the method was called on.</returns>
public JsonApiConfiguration UsingDefaultQueryablePayloadBuilder(Action<DefaultQueryablePayloadBuilderConfiguration> configurationAction)
{
_payloadBuilderFactory = () =>
{
var configuration = new DefaultQueryablePayloadBuilderConfiguration();
configurationAction(configuration);
return configuration.GetBuilder(_modelManager);
};
return this;
}
/// <summary>
/// Applies the running configuration to an HttpConfiguration instance
/// </summary>
/// <param name="httpConfig">The HttpConfiguration to apply this JsonApiConfiguration to</param>
public void Apply(HttpConfiguration httpConfig)
{
var formatter = new JsonApiFormatter(_modelManager);
httpConfig.Formatters.Clear();
httpConfig.Formatters.Add(formatter);
var queryablePayloadBuilder = _payloadBuilderFactory();
httpConfig.Filters.Add(new JsonApiQueryableAttribute(queryablePayloadBuilder));
httpConfig.Services.Replace(typeof (IHttpControllerSelector),
new PascalizedControllerSelector(httpConfig));
}
}
}
| mit | C# |
8dde7054db39ffb9a212a8d0fc7e7b8e2d0e6523 | Remove "New" string from asset name | bartlomiejwolk/AnimationPathAnimator | Libraries/ScriptableObjectUtility.cs | Libraries/ScriptableObjectUtility.cs | using UnityEngine;
using UnityEditor;
using System.IO;
namespace ATP.AnimationPathTools {
public static class ScriptableObjectUtility
{
/// <summary>
// This makes it easy to create, name and place unique new ScriptableObject asset files.
/// </summary>
public static void CreateAsset<T> () where T : ScriptableObject
{
T asset = ScriptableObject.CreateInstance<T> ();
string path = AssetDatabase.GetAssetPath (Selection.activeObject);
if (path == "")
{
path = "Assets";
}
else if (Path.GetExtension (path) != "")
{
path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), "");
}
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/" + typeof(T).ToString() + ".asset");
AssetDatabase.CreateAsset (asset, assetPathAndName);
AssetDatabase.SaveAssets ();
AssetDatabase.Refresh();
EditorUtility.FocusProjectWindow ();
Selection.activeObject = asset;
}
}
} | using UnityEngine;
using UnityEditor;
using System.IO;
namespace ATP.AnimationPathTools {
public static class ScriptableObjectUtility
{
/// <summary>
// This makes it easy to create, name and place unique new ScriptableObject asset files.
/// </summary>
public static void CreateAsset<T> () where T : ScriptableObject
{
T asset = ScriptableObject.CreateInstance<T> ();
string path = AssetDatabase.GetAssetPath (Selection.activeObject);
if (path == "")
{
path = "Assets";
}
else if (Path.GetExtension (path) != "")
{
path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), "");
}
string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath (path + "/New " + typeof(T).ToString() + ".asset");
AssetDatabase.CreateAsset (asset, assetPathAndName);
AssetDatabase.SaveAssets ();
AssetDatabase.Refresh();
EditorUtility.FocusProjectWindow ();
Selection.activeObject = asset;
}
}
} | mit | C# |
82d9c9a7e05132f2146e911f7c34c18dd9802f67 | Update ArrayEntity.cs | dimmpixeye/Unity3dTools | Runtime/LibMisc/ArrayEntity.cs | Runtime/LibMisc/ArrayEntity.cs | // Project : ecs
// Contacts : Pix - ask@pixeye.games
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.IL2CPP.CompilerServices;
using UnityEngine;
namespace Pixeye.Framework
{
[Serializable]
public struct ArrayEntity
{
public int length;
public ent[] source;
public ref ent this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref source[index];
}
public ArrayEntity(int size)
{
source = new ent[size];
length = 0;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public bool TryAdd(in ent entity)
{
for (var i = 0; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
return false;
}
}
Add(entity);
return true;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public bool Has(in ent entity)
{
for (var i = 0; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
return false;
}
}
return true;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public void Add(in ent entity)
{
if (length >= source.Length)
{
Array.Resize(ref source, length << 1);
}
source[length++] = entity;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public void Remove(in ent entity)
{
var i = 0;
for (; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
val.id = -1;
break;
}
}
if (i < --length)
Array.Copy(source, i + 1, source, i, length - i);
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Removed(in ent entity)
{
var i = 0;
for (; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
val.id = -1;
break;
}
}
if (i < --length){
Array.Copy(source, i + 1, source, i, length - i);
return true;
}
else return false;
}
}
} | // Project : ecs
// Contacts : Pix - ask@pixeye.games
using System;
using System.Runtime.CompilerServices;
using Unity.IL2CPP.CompilerServices;
namespace Pixeye.Framework
{
[Serializable]
public struct ArrayEntity
{
public int length;
public ent[] source;
public ref ent this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref source[index];
}
public ArrayEntity(int size)
{
source = new ent[size];
length = 0;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public bool TryAdd(in ent entity)
{
for (var i = 0; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
return false;
}
}
Add(entity);
return true;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public bool Has(in ent entity)
{
for (var i = 0; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
return false;
}
}
return true;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public void Add(in ent entity)
{
if (length >= source.Length)
{
Array.Resize(ref source, length << 1);
}
source[length++] = entity;
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
public void Remove(in ent entity)
{
var i = 0;
for (; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
val.id = -1;
break;
}
}
Array.Copy(source, i + 1, source, i, length-- - i);
}
[Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks, false)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Removed(in ent entity)
{
var i = 0;
for (; i < length; i++)
{
ref var val = ref source[i];
if (entity.id == val.id && entity.age == val.age)
{
val.id = -1;
break;
}
}
if (i != length)
{
Array.Copy(source, i + 1, source, i, length-- - i);
return true;
}
else return false;
}
}
} | mit | C# |
228e43af265f8964767593ce89dff94bf135d514 | clean up | edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk | tests/InMemoryDataStoreTest.cs | tests/InMemoryDataStoreTest.cs | using System.IO;
using FHSDK.Services;
using FHSDK.Services.Data;
using FHSDK.Sync;
using FHSDKPortable;
using Newtonsoft.Json.Linq;
using Xunit;
namespace tests
{
public class InMemoryDataStoreTest
{
private readonly string _dataPersistFile;
private readonly IIOService _ioService;
public InMemoryDataStoreTest()
{
FHClient.Init();
_ioService = ServiceFinder.Resolve<IIOService>();
var dataDir = _ioService.GetDataPersistDir();
var dataPersistDir = Path.Combine(dataDir, "syncTestDir");
_dataPersistFile = Path.Combine(dataPersistDir, ".test_data_file");
}
[Fact]
public void TestInsertIntoDataStore()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("key1", obj);
dataStore.Insert("key2", obj);
//then
var list = dataStore.List();
Assert.Equal(2, list.Count);
Assert.NotNull(list["key1"]);
var result = dataStore.Get("key1");
Assert.Equal(obj, result);
}
[Fact]
public void TestSaveDataStoreToJson()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
dataStore.PersistPath = _dataPersistFile;
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("main-key", obj);
dataStore.Save();
//then
Assert.True(_ioService.Exists(_dataPersistFile));
var content = _ioService.ReadFile(_dataPersistFile);
Assert.Equal("{\"main-key\":{\"key\":\"value\"}}", content);
}
}
}
| using System.IO;
using FHSDK.Services;
using FHSDK.Services.Data;
using FHSDK.Sync;
using FHSDKPortable;
using Newtonsoft.Json.Linq;
using Xunit;
namespace tests
{
public class InMemoryDataStoreTest
{
private string _dataPersistDir;
private string _dataPersistFile;
private IIOService _ioService;
public InMemoryDataStoreTest()
{
FHClient.Init();
_ioService = ServiceFinder.Resolve<IIOService>();
var dataDir = _ioService.GetDataPersistDir();
_dataPersistDir = Path.Combine(dataDir, "syncTestDir");
_dataPersistFile = Path.Combine(_dataPersistDir, ".test_data_file");
}
[Fact]
public void TestInsertIntoDataStore()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("key1", obj);
dataStore.Insert("key2", obj);
//then
var list = dataStore.List();
Assert.Equal(2, list.Count);
Assert.NotNull(list["key1"]);
var result = dataStore.Get("key1");
Assert.Equal(obj, result);
}
[Fact]
public void TestSaveDataStoreToJson()
{
//given
IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>();
dataStore.PersistPath = _dataPersistFile;
var obj = new JObject();
obj["key"] = "value";
//when
dataStore.Insert("main-key", obj);
dataStore.Save();
//then
Assert.True(_ioService.Exists(_dataPersistFile));
var content = _ioService.ReadFile(_dataPersistFile);
Assert.Equal("{\"main-key\":{\"key\":\"value\"}}", content);
}
}
}
| apache-2.0 | C# |
8766e4abfab5e670bf77dd946fc2cb031536a211 | Fix test name | peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework | osu.Framework.Tests/Visual/Testing/TestSceneDerivedTestWithDerivedMethodsWithAttributes.cs | osu.Framework.Tests/Visual/Testing/TestSceneDerivedTestWithDerivedMethodsWithAttributes.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.Testing
{
public class TestSceneDerivedTestWithDerivedMethodsWithAttributes : TestSceneTest
{
[SetUp]
public override void SetUp() => base.SetUp();
[SetUpSteps]
public override void SetUpSteps() => base.SetUpSteps();
[TearDownSteps]
public override void TearDownSteps() => base.TearDownSteps();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual.Testing
{
public class TestSceneDerivedTestWithOverriddenTestMethodsWithCustomAttributes : TestSceneTest
{
[SetUp]
public override void SetUp() => base.SetUp();
[SetUpSteps]
public override void SetUpSteps() => base.SetUpSteps();
[TearDownSteps]
public override void TearDownSteps() => base.TearDownSteps();
}
}
| mit | C# |
90f7c0e039dbbaccae91f6968eb8e10c0e4959f8 | Update ModelManager.cs | wangyaron/VRProject | TestGit/Assets/ModelManager.cs | TestGit/Assets/ModelManager.cs | using UnityEngine;
using System.Collections;
public class ModelManager : MonoBehaviour
{
private int tag = 8;
private bool isShow = false;
private string model_name = "hello";
void Start () {
Debug.Log("git测试");
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, Time.deltaTime * 280);
}
private void PrintMsg()
{
Debug.Log("小郭提交的一个方法");
}
public void SetVisible(bool visible){
gameObject.SetActive(visible);
}
}
| using UnityEngine;
using System.Collections;
public class ModelManager : MonoBehaviour
{
private int tag = 5;
private string model_name = "hello";
void Start () {
Debug.Log("git测试");
}
// Update is called once per frame
void Update () {
transform.Rotate(Vector3.up, Time.deltaTime * 280);
}
private void PrintMsg()
{
Debug.Log("小郭提交的一个方法");
}
public void SetVisible(bool visible){
gameObject.SetActive(visible);
}
}
| apache-2.0 | C# |
620c2311ac887eebf82c8c31583661bfe0aba517 | Add test | johnneijzen/osu,NeoAdonis/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,EVAST9919/osu,ppy/osu,ZLima12/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,ZLima12/osu,2yangk23/osu,peppy/osu | osu.Game.Tests/Visual/Online/TestSceneFullscreenOverlay.cs | osu.Game.Tests/Visual/Online/TestSceneFullscreenOverlay.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Overlays;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Online
{
[TestFixture]
public class TestSceneFullscreenOverlay : OsuTestScene
{
private FullscreenOverlay overlay;
protected override void LoadComplete()
{
base.LoadComplete();
int fireCount = 0;
Add(overlay = new TestFullscreenOverlay());
overlay.State.ValueChanged += _ => fireCount++;
AddStep(@"show", overlay.Show);
AddAssert("fire count 1", () => fireCount == 1);
AddStep(@"show again", overlay.Show);
// this logic is specific to FullscreenOverlay
AddAssert("fire count 2", () => fireCount == 2);
AddStep(@"hide", overlay.Hide);
AddAssert("fire count 3", () => fireCount == 3);
}
private class TestFullscreenOverlay : FullscreenOverlay
{
public TestFullscreenOverlay()
{
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
};
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Shapes;
using osu.Game.Overlays;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Online
{
[TestFixture]
public class TestSceneFullscreenOverlay : OsuTestScene
{
private FullscreenOverlay overlay;
protected override void LoadComplete()
{
base.LoadComplete();
Add(overlay = new TestFullscreenOverlay());
AddStep(@"toggle", overlay.ToggleVisibility);
}
private class TestFullscreenOverlay : FullscreenOverlay
{
public TestFullscreenOverlay()
{
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
};
}
}
}
}
| mit | C# |
f9edc57f6f2325c97d4324b439104498be249943 | Comment update. | bogosoft/Maybe | Bogosoft.Maybe/ObjectExtensions.cs | Bogosoft.Maybe/ObjectExtensions.cs | namespace Bogosoft.Maybe
{
/// <summary>
/// Provides a set of static methods for conversions between objects and <see cref="MayBe{T}"/> objects.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Convert the current object to an instance of the <see cref="MayBe{T}"/> class.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="object">The current object.</param>
/// <returns>
/// An instance of the <see cref="MayBe{T}"/> class.
/// </returns>
public static MayBe<T> Maybe<T>(this T @object)
{
return new MayBe<T>(@object);
}
}
} | namespace Bogosoft.Maybe
{
/// <summary>
/// Provides a set of static methods for conversions between objects and may bes.
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Convert the current object to an instance of the <see cref="MayBe{T}"/> class.
/// </summary>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="object">The current object.</param>
/// <returns>
/// An instance of the <see cref="MayBe{T}"/> class.
/// </returns>
public static MayBe<T> Maybe<T>(this T @object)
{
return new MayBe<T>(@object);
}
}
} | mit | C# |
ecc7fac6e5397d93402bb7cceed73d01ce3744d4 | Initialize MassTransit logger with TopShelf during host startup | jacobpovar/MassTransit,SanSYS/MassTransit,phatboyg/MassTransit,MassTransit/MassTransit,phatboyg/MassTransit,MassTransit/MassTransit,SanSYS/MassTransit,jacobpovar/MassTransit | src/MassTransit.Host/Program.cs | src/MassTransit.Host/Program.cs | // Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Host
{
using System;
using System.IO;
using log4net.Config;
using Log4NetIntegration.Logging;
using Topshelf;
using Topshelf.Logging;
class Program
{
static int Main()
{
SetupLogger();
return (int)HostFactory.Run(x =>
{
var configurator = new MassTransitHostConfigurator<MassTransitHostServiceBootstrapper>
{
Description = "MassTransit Host - A service host for MassTransit endpoints",
DisplayName = "MassTransit Host",
ServiceName = "MassTransitHost"
};
configurator.Configure(x);
});
}
static void SetupLogger()
{
var configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MassTransit.Host.log4net.config"));
if (configFile.Exists)
XmlConfigurator.ConfigureAndWatch(configFile);
Log4NetLogWriterFactory.Use();
Log4NetLogger.Use();
}
}
} | // Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Host
{
using System;
using System.IO;
using log4net.Config;
using Topshelf;
using Topshelf.Logging;
class Program
{
static int Main()
{
SetupLogger();
return (int)HostFactory.Run(x =>
{
var configurator = new MassTransitHostConfigurator<MassTransitHostServiceBootstrapper>
{
Description = "MassTransit Host - A service host for MassTransit endpoints",
DisplayName = "MassTransit Host",
ServiceName = "MassTransitHost"
};
configurator.Configure(x);
});
}
static void SetupLogger()
{
var configFile = new FileInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MassTransit.Host.log4net.config"));
if (configFile.Exists)
XmlConfigurator.ConfigureAndWatch(configFile);
Log4NetLogWriterFactory.Use();
}
}
} | apache-2.0 | C# |
a13b4bb1ff070614c18ac9547b189a31f7837598 | Make InheritedAreMarkedSerializable() produce a more informative failure message. | gliljas/nhibernate-core,alobakov/nhibernate-core,lnu/nhibernate-core,ngbrown/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,RogerKratz/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,gliljas/nhibernate-core,ngbrown/nhibernate-core,livioc/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,ManufacturingIntelligence/nhibernate-core,livioc/nhibernate-core,nkreipke/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,gliljas/nhibernate-core,alobakov/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core | src/NHibernate.Test/NHAssert.cs | src/NHibernate.Test/NHAssert.cs | using System;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
namespace NHibernate.Test
{
public class NHAssert
{
#region Serializable
public static void HaveSerializableAttribute(System.Type clazz)
{
HaveSerializableAttribute(clazz, null, null);
}
public static void HaveSerializableAttribute(System.Type clazz, string message, params object[] args)
{
Assert.That(clazz, Has.Attribute<SerializableAttribute>(), message, args);
}
public static void InheritedAreMarkedSerializable(System.Type clazz)
{
InheritedAreMarkedSerializable(clazz, null, null);
}
public static void InheritedAreMarkedSerializable(System.Type clazz, string message, params object[] args)
{
var faulty = new List<System.Type>();
Assembly nhbA = Assembly.GetAssembly(clazz);
IList<System.Type> types = ClassList(nhbA, clazz);
foreach (System.Type tp in types)
{
object[] atts = tp.GetCustomAttributes(typeof(SerializableAttribute), false);
if (atts.Length == 0)
faulty.Add(tp);
}
if (faulty.Count > 0)
{
var classes = string.Join(Environment.NewLine, faulty.Select(t => " " + t.FullName).ToArray());
Assert.Fail("The following classes was expected to be marked as Serializable:" + Environment.NewLine + classes);
}
}
public static void IsSerializable(object obj)
{
IsSerializable(obj, null, null);
}
public static void IsSerializable(object obj, string message, params object[] args)
{
Assert.That(obj, Is.BinarySerializable, message, args);
}
#endregion
private static IList<System.Type> ClassList(Assembly assembly, System.Type type)
{
IList<System.Type> result = new List<System.Type>();
if (assembly != null)
{
System.Type[] types = assembly.GetTypes();
foreach (System.Type tp in types)
{
if (tp != type && type.IsAssignableFrom(tp) && !tp.IsInterface)
result.Add(tp);
}
}
return result;
}
}
} | using System;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using System.Collections.Generic;
namespace NHibernate.Test
{
public class NHAssert
{
#region Serializable
public static void HaveSerializableAttribute(System.Type clazz)
{
HaveSerializableAttribute(clazz, null, null);
}
public static void HaveSerializableAttribute(System.Type clazz, string message, params object[] args)
{
Assert.That(clazz, Has.Attribute<SerializableAttribute>(), message, args);
}
public static void InheritedAreMarkedSerializable(System.Type clazz)
{
InheritedAreMarkedSerializable(clazz, null, null);
}
public static void InheritedAreMarkedSerializable(System.Type clazz, string message, params object[] args)
{
var sb = new StringBuilder();
int failedCount = 0;
Assembly nhbA = Assembly.GetAssembly(clazz);
IList<System.Type> types = ClassList(nhbA, clazz);
foreach (System.Type tp in types)
{
object[] atts = tp.GetCustomAttributes(typeof(SerializableAttribute), false);
if (atts.Length == 0)
{
sb.AppendLine(string.Format(" class {0} is not marked as Serializable", tp.FullName));
failedCount++;
}
}
Assert.That(failedCount, Is.EqualTo(0));
}
public static void IsSerializable(object obj)
{
IsSerializable(obj, null, null);
}
public static void IsSerializable(object obj, string message, params object[] args)
{
Assert.That(obj, Is.BinarySerializable, message, args);
}
#endregion
private static IList<System.Type> ClassList(Assembly assembly, System.Type type)
{
IList<System.Type> result = new List<System.Type>();
if (assembly != null)
{
System.Type[] types = assembly.GetTypes();
foreach (System.Type tp in types)
{
if (tp != type && type.IsAssignableFrom(tp) && !tp.IsInterface)
result.Add(tp);
}
}
return result;
}
}
} | lgpl-2.1 | C# |
f885840e05067f7aa48362712e9909717d8b187d | Set default Options value to null for UsageRecordService | stripe/stripe-dotnet | src/Stripe.net/Services/UsageRecords/UsageRecordService.cs | src/Stripe.net/Services/UsageRecords/UsageRecordService.cs | namespace Stripe
{
using System.Threading;
using System.Threading.Tasks;
public class UsageRecordService : ServiceNested<UsageRecord>,
INestedCreatable<UsageRecord, UsageRecordCreateOptions>
{
public UsageRecordService()
: base(null)
{
}
public UsageRecordService(IStripeClient client)
: base(client)
{
}
public override string BasePath => "/v1/subscription_items/{PARENT_ID}/usage_records";
public virtual UsageRecord Create(string parentId, UsageRecordCreateOptions options = null, RequestOptions requestOptions = null)
{
return this.CreateNestedEntity(parentId, options, requestOptions);
}
public virtual Task<UsageRecord> CreateAsync(string parentId, UsageRecordCreateOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
{
return this.CreateNestedEntityAsync(parentId, options, requestOptions, cancellationToken);
}
}
}
| namespace Stripe
{
using System.Threading;
using System.Threading.Tasks;
public class UsageRecordService : ServiceNested<UsageRecord>,
INestedCreatable<UsageRecord, UsageRecordCreateOptions>
{
public UsageRecordService()
: base(null)
{
}
public UsageRecordService(IStripeClient client)
: base(client)
{
}
public override string BasePath => "/v1/subscription_items/{PARENT_ID}/usage_records";
public virtual UsageRecord Create(string parentId, UsageRecordCreateOptions options, RequestOptions requestOptions = null)
{
return this.CreateNestedEntity(parentId, options, requestOptions);
}
public virtual Task<UsageRecord> CreateAsync(string parentId, UsageRecordCreateOptions options, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
{
return this.CreateNestedEntityAsync(parentId, options, requestOptions, cancellationToken);
}
}
}
| apache-2.0 | C# |
a72928ddbd6636ea6248884ef7530e2cb9f8f46d | Implement SendBackspace and SentHotstring on Windows frontend | yatsek/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,yatsek/IronAHK,yatsek/IronAHK,polyethene/IronAHK,michaltakac/IronAHK,yatsek/IronAHK,polyethene/IronAHK,polyethene/IronAHK,michaltakac/IronAHK,michaltakac/IronAHK,polyethene/IronAHK,michaltakac/IronAHK | Rusty/Windows/KeyboardHook.cs | Rusty/Windows/KeyboardHook.cs | using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;
namespace IronAHK.Rusty
{
partial class Windows
{
public class KeyboardHook : Core.KeyboardHook
{
// credit to http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx for saving me time
const int WM_HOTKEY = 0x0312;
const int WH_KEYBOARD_LL = 13;
const int WM_KEYDOWN = 0x0100;
const int WM_KEYUP = 0x0101;
LowLevelKeyboardProc proc;
IntPtr hookId = IntPtr.Zero;
const string backspace = "{BS}";
protected override void RegisterHook()
{
proc = HookCallback;
hookId = SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
}
protected override void DeregisterHook()
{
UnhookWindowsHookEx(hookId);
}
protected override void SendBackspace (int length)
{
StringBuilder Buf = new StringBuilder(backspace.Length * length);
for(int i = 0; i < length; i++)
Buf.Append("{BS}");
SendHotstring(Buf.ToString());
}
protected internal override void SendHotstring (string keys)
{
SendKeys.SendWait(keys);
}
IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
bool block = false;
bool pressed = wParam == (IntPtr)WM_KEYDOWN;
if (nCode >= 0 && pressed || wParam == (IntPtr)WM_KEYUP)
{
int vkCode = Marshal.ReadInt32(lParam);
block = KeyReceived((Keys)vkCode, pressed);
}
var next = CallNextHookEx(hookId, nCode, wParam, lParam);
return block ? new IntPtr(1) : next;
}
}
}
}
| using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace IronAHK.Rusty
{
partial class Windows
{
public class KeyboardHook : Core.KeyboardHook
{
// credit to http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx for saving me time
const int WM_HOTKEY = 0x0312;
const int WH_KEYBOARD_LL = 13;
const int WM_KEYDOWN = 0x0100;
const int WM_KEYUP = 0x0101;
LowLevelKeyboardProc proc;
IntPtr hookId = IntPtr.Zero;
protected override void RegisterHook()
{
proc = HookCallback;
hookId = SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(Process.GetCurrentProcess().MainModule.ModuleName), 0);
}
protected override void DeregisterHook()
{
UnhookWindowsHookEx(hookId);
}
IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
bool block = false;
bool pressed = wParam == (IntPtr)WM_KEYDOWN;
if (nCode >= 0 && pressed || wParam == (IntPtr)WM_KEYUP)
{
int vkCode = Marshal.ReadInt32(lParam);
block = KeyReceived((Keys)vkCode, pressed);
}
var next = CallNextHookEx(hookId, nCode, wParam, lParam);
return block ? new IntPtr(1) : next;
}
}
}
}
| bsd-2-clause | C# |
5204fc88a4f6dd781d4ce30d02699f76a6ba322f | Clean up attacher | andrew-vant/dragalt | dragnavball.cs | dragnavball.cs | using KSP.UI.Screens.Flight;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[KSPAddon(KSPAddon.Startup.Flight, false)]
public class NavBallAttacher : MonoBehaviour
{
void Start()
{
print("Starting draggable navball");
// We want to drag the navball's frame around. The frame is
// the grandparent of the ball itself.
GameObject ball = FindObjectOfType<NavBall>().gameObject;
GameObject frame = ball.transform.parent.gameObject.transform.parent.gameObject;
frame.AddComponent<NavBallDrag>();
}
}
public class NavBallDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler
{
float ptrstart;
float ballstart;
public void OnBeginDrag(PointerEventData evtdata)
{
print("Navball drag start");
print(transform.position);
ptrstart = evtdata.position.x;
ballstart = transform.position.x;
}
public void OnDrag(PointerEventData evtdata)
{
float x = ballstart + (evtdata.position.x - ptrstart);
float y = transform.position.y;
float z = transform.position.z;
transform.position = new Vector3(x, y, z);
print(transform.position);
}
public void OnEndDrag(PointerEventData evtdata)
{
print("Drag finished");
print(transform.position);
}
public void OnDrop(PointerEventData evtdata)
{
print("Navball dropped");
print(transform.position);
}
}
| using KSP.UI.Screens.Flight;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
[KSPAddon(KSPAddon.Startup.Flight, false)]
public class NavBallAttacher : MonoBehaviour
{
void Start()
{
print("Starting draggable navball");
GameObject ball = FindObjectOfType<NavBall>().gameObject;
GameObject frame = ball.transform.parent.gameObject.transform.parent.gameObject;
// Not sure which of these is actually doing the work.
// ball.AddComponent<NavBallDrag>();
frame.AddComponent<NavBallDrag>();
// Show the object tree while I work out which object actually
// needs to be dragged...
string path = "/";
for (GameObject obj = ball.gameObject; obj != null; obj = obj.transform.parent.gameObject)
{
print(obj.GetType().Name + ":" + obj.name);
path = "/" + obj.GetType().Name + ":" + obj.name + path;
}
print("Done");
}
}
public class NavBallDrag : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler, IDropHandler
{
float ptrstart;
float ballstart;
public void OnBeginDrag(PointerEventData evtdata)
{
print("Navball drag start");
print(transform.position);
ptrstart = evtdata.position.x;
ballstart = transform.position.x;
}
public void OnDrag(PointerEventData evtdata)
{
float x = ballstart + (evtdata.position.x - ptrstart);
float y = transform.position.y;
float z = transform.position.z;
transform.position = new Vector3(x, y, z);
print(transform.position);
}
public void OnEndDrag(PointerEventData evtdata)
{
print("Drag finished");
print(transform.position);
}
public void OnDrop(PointerEventData evtdata)
{
print("Navball dropped");
print(transform.position);
}
}
| mit | C# |
f6953f7c44ab12d228aa15ec254303ffa57c5c80 | Add tests consuming ReactiveBuilder | inputfalken/Sharpy | tests/Sharpy.ReactiveBuilder.Tests/ReactiveBuilderTests.cs | tests/Sharpy.ReactiveBuilder.Tests/ReactiveBuilderTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using NUnit.Framework;
namespace Sharpy.ReactiveBuilder.Tests {
[TestFixture]
internal class ReactiveBuilderTests {
[Test]
public void Not_Null() => Assert.NotNull(new Builder.Builder().Observable(b => b.Integer()));
[Test]
public void Not_Null_With_Counter() => Assert.NotNull(new Builder.Builder().Observable((b, i) => b.Integer()));
[Test]
public void Null_Builder_Throws() {
Builder.Builder builder = null;
Assert.Throws<ArgumentNullException>(() => builder.Observable(b => b.Integer()));
}
[Test]
public void Null_Selector_Throws() {
Func<Builder.Builder, int> selector = null;
Assert.Throws<ArgumentNullException>(() => new Builder.Builder().Observable(selector));
}
[Test]
public void Null_Selector_With_Counter_Throws() {
Func<Builder.Builder, int, int> selector = null;
Assert.Throws<ArgumentNullException>(() => new Builder.Builder().Observable(selector));
}
[Test]
public void Building_Integers() {
const int seed = 20;
var builder = new Builder.Builder(seed);
var expected = new List<int>();
const int total = 2000;
const int max = 1000;
const int min = 100;
for (var i = 0; i < total; i++) expected.Add(builder.Integer(min, max));
var result = new Builder.Builder(seed)
.Observable(b => b.Integer(min, max))
.Take(total)
.ToListObservable();
Assert.IsTrue(result.SequenceEqual(expected));
}
[Test]
public void Building_Dates() {
DateTime TrimMilliseconds(DateTime dt) =>
new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
const int seed = 20;
var builder = new Builder.Builder(seed);
var expected = new List<DateTime>();
const int total = 2000;
for (var i = 0; i < total; i++) expected.Add(TrimMilliseconds(builder.Date()));
var result = new Builder.Builder(seed)
.Observable(b => TrimMilliseconds(b.Date()))
.Take(total)
.ToListObservable();
Assert.IsTrue(result.SequenceEqual(expected));
}
[Test]
public void Building_Booleans() {
const int seed = 20;
var builder = new Builder.Builder(seed);
var expected = new List<bool>();
const int total = 2000;
for (var i = 0; i < total; i++) expected.Add(builder.Bool());
var result = new Builder.Builder(seed)
.Observable(b => b.Bool())
.Take(total)
.ToListObservable();
Assert.IsTrue(result.SequenceEqual(expected));
}
}
} | using System;
using NUnit.Framework;
namespace Sharpy.ReactiveBuilder.Tests {
[TestFixture]
internal class ReactiveBuilderTests {
[Test]
public void Not_Null() => Assert.NotNull(new Builder.Builder().Observable(b => b.Integer()));
[Test]
public void Not_Null_With_Counter() => Assert.NotNull(new Builder.Builder().Observable((b, i) => b.Integer()));
[Test]
public void Null_Builder_Throws() {
Builder.Builder builder = null;
Assert.Throws<ArgumentNullException>(() => builder.Observable(b => b.Integer()));
}
[Test]
public void Null_Selector_Throws() {
Func<Builder.Builder, int> selector = null;
Assert.Throws<ArgumentNullException>(() => new Builder.Builder().Observable(selector));
}
[Test]
public void Null_Selector_With_Counter_Throws() {
Func<Builder.Builder, int, int> selector = null;
Assert.Throws<ArgumentNullException>(() => new Builder.Builder().Observable(selector));
}
}
} | mit | C# |
d6a5bc2130e99a22dc9c6f89f30ae3f044e1738c | Add TODO for later review | larsbrubaker/agg-sharp,MatterHackers/agg-sharp,jlewin/agg-sharp | DataConverters3D/Object3D/Json/IObject3DContractResolver.cs | DataConverters3D/Object3D/Json/IObject3DContractResolver.cs | /*
Copyright (c) 2017, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Reflection;
using MatterHackers.Agg;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace MatterHackers.DataConverters3D
{
public class IObject3DContractResolver : DefaultContractResolver
{
private static Type IObject3DType = typeof(IObject3D);
private static Type RGBA_BtyesType = typeof(RGBA_Bytes);
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
// Conditionally serialize .Children only if .MeshPath is empty. Currently having a Mesh precludes having children - looks like a
// feature for AMF that needs to be reconsidered or constrained to specific scenarios
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName == "Children" && IObject3DType.IsAssignableFrom(property.DeclaringType))
{
// TODO: Needs review - clipping the Children property when MeshPath is non-null works for AMF but isn't appropriate for many use cases
property.ShouldSerialize = instance => {
IObject3D item = (IObject3D)instance;
return string.IsNullOrEmpty(item.MeshPath);
};
}
if (property.PropertyName == "Color" && RGBA_BtyesType.IsAssignableFrom(property.PropertyType))
{
property.ShouldSerialize = instance => {
return instance is IObject3D object3D && object3D.Color != RGBA_Bytes.Transparent;
};
}
return property;
}
}
} | /*
Copyright (c) 2017, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Reflection;
using MatterHackers.Agg;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace MatterHackers.DataConverters3D
{
public class IObject3DContractResolver : DefaultContractResolver
{
private static Type IObject3DType = typeof(IObject3D);
private static Type RGBA_BtyesType = typeof(RGBA_Bytes);
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
// Conditionally serialize .Children only if .MeshPath is empty. Currently having a Mesh precludes having children - looks like a
// feature for AMF that needs to be reconsidered or constrained to specific scenarios
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyName == "Children" && IObject3DType.IsAssignableFrom(property.DeclaringType))
{
property.ShouldSerialize = instance => {
IObject3D item = (IObject3D)instance;
return string.IsNullOrEmpty(item.MeshPath);
};
}
if (property.PropertyName == "Color" && RGBA_BtyesType.IsAssignableFrom(property.PropertyType))
{
property.ShouldSerialize = instance => {
return instance is IObject3D object3D && object3D.Color != RGBA_Bytes.Transparent;
};
}
return property;
}
}
} | bsd-2-clause | C# |
ebc0ecfebdfa1fdeb518c71a831c409e6cc26685 | Fix overlay layout measure | helix-toolkit/helix-toolkit,holance/helix-toolkit,chrkon/helix-toolkit,JeremyAnsel/helix-toolkit,Iluvatar82/helix-toolkit | Source/HelixToolkit.Wpf.SharpDX/Model/Elements2D/Overlay.cs | Source/HelixToolkit.Wpf.SharpDX/Model/Elements2D/Overlay.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
namespace HelixToolkit.Wpf.SharpDX.Elements2D
{
internal sealed class Overlay : ContentElement2D
{
protected override bool OnHitTest(ref Vector2 mousePoint, out HitTest2DResult hitResult)
{
hitResult = null;
if (LayoutBoundWithTransform.Contains(mousePoint))
{
foreach (var item in Items.Reverse())
{
if (item is IHitable2D && (item as IHitable2D).HitTest(mousePoint, out hitResult))
{
return true;
}
}
}
return false;
}
protected override Size2F MeasureOverride(Size2F availableSize)
{
foreach (var item in Items)
{
if (item is Element2D e)
{
e.Measure(availableSize);
}
}
return availableSize;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
namespace HelixToolkit.Wpf.SharpDX.Elements2D
{
internal sealed class Overlay : ContentElement2D
{
protected override bool OnHitTest(ref Vector2 mousePoint, out HitTest2DResult hitResult)
{
hitResult = null;
if (LayoutBoundWithTransform.Contains(mousePoint))
{
foreach (var item in Items.Reverse())
{
if (item is IHitable2D && (item as IHitable2D).HitTest(mousePoint, out hitResult))
{
return true;
}
}
}
return false;
}
}
}
| mit | C# |
80e7ecc9a2c3b2536054b015bb7fa1773fff3ded | Refactor Subtract Doubles Operation to use GetValues and CloneWithValues | ajlopez/TensorSharp | Src/TensorSharp/Operations/SubtractDoubleDoubleOperation.cs | Src/TensorSharp/Operations/SubtractDoubleDoubleOperation.cs | namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class SubtractDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
double[] values1 = tensor1.GetValues();
int l = values1.Length;
double[] values2 = tensor2.GetValues();
double[] newvalues = new double[l];
for (int k = 0; k < l; k++)
newvalues[k] = values1[k] - values2[k];
return tensor1.CloneWithNewValues(newvalues);
}
}
}
| namespace TensorSharp.Operations
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class SubtractDoubleDoubleOperation : IBinaryOperation<double, double, double>
{
public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2)
{
Tensor<double> result = new Tensor<double>();
result.SetValue(tensor1.GetValue() - tensor2.GetValue());
return result;
}
}
}
| mit | C# |
1f018c59b47034a0480ea7fa025a6f90d119c01d | Fix for Crashing commands. | rrampersad/TestAppMobileCenter | TestAppMobilecenter/TestAppMobilecenter/Commands/Command.cs | TestAppMobilecenter/TestAppMobilecenter/Commands/Command.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Windows.Input;
namespace TestAppMobilecenter.Commands
{
//https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/Command.cs
public class Command : ICommand
{
readonly Func<object, bool> _canExecute;
readonly Action<object> _execute;
public Command(Action<object> execute)
{
if (execute == null)
{
throw new ArgumentNullException(nameof(execute));
}
_execute = execute;
}
public Command(Action execute) : this(o => execute())
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
}
public Command(Action<object> execute, Func<object, bool> canExecute) : this(execute)
{
if (execute == null)
{
throw new ArgumentNullException(nameof(canExecute));
}
_canExecute = canExecute;
}
public Command(Action execute, Func<bool> canExecute) : this(o => execute(), o => canExecute())
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
if (canExecute == null)
throw new ArgumentNullException(nameof(canExecute));
}
public bool CanExecute(object parameter)
{
if (_canExecute != null)
return _canExecute(parameter);
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_execute(parameter);
}
public void ChangeCanExecute()
{
EventHandler changed = CanExecuteChanged;
changed?.Invoke(this, EventArgs.Empty);
}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Windows.Input;
namespace TestAppMobilecenter.Commands
{
//https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/Command.cs
public class Command : ICommand
{
readonly Func<object, bool> _canExecute;
readonly Action<object> _execute;
public Command(Action<object> execute)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
}
public Command(Action execute) : this(o => execute())
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
}
public Command(Action<object> execute, Func<object, bool> canExecute) : this(execute)
{
_canExecute = canExecute ?? throw new ArgumentNullException(nameof(canExecute));
}
public Command(Action execute, Func<bool> canExecute) : this(o => execute(), o => canExecute())
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
if (canExecute == null)
throw new ArgumentNullException(nameof(canExecute));
}
public bool CanExecute(object parameter)
{
if (_canExecute != null)
return _canExecute(parameter);
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_execute(parameter);
}
public void ChangeCanExecute()
{
EventHandler changed = CanExecuteChanged;
changed?.Invoke(this, EventArgs.Empty);
}
}
}
| apache-2.0 | C# |
8b59db6988557561c6655cdf21946364baed1da5 | Update AssemblyFileVersion to 2.0.2.0 | dominiqa/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shipram/azure-sdk-for-net,scottrille/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,AzCiS/azure-sdk-for-net,robertla/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,nathannfan/azure-sdk-for-net,cwickham3/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,mumou/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,pattipaka/azure-sdk-for-net,bgold09/azure-sdk-for-net,btasdoven/azure-sdk-for-net,kagamsft/azure-sdk-for-net,ogail/azure-sdk-for-net,rohmano/azure-sdk-for-net,gubookgu/azure-sdk-for-net,zaevans/azure-sdk-for-net,hallihan/azure-sdk-for-net,mabsimms/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,ailn/azure-sdk-for-net,kagamsft/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,atpham256/azure-sdk-for-net,lygasch/azure-sdk-for-net,guiling/azure-sdk-for-net,xindzhan/azure-sdk-for-net,yoreddy/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,amarzavery/azure-sdk-for-net,jamestao/azure-sdk-for-net,jtlibing/azure-sdk-for-net,AuxMon/azure-sdk-for-net,juvchan/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,shutchings/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,yoreddy/azure-sdk-for-net,begoldsm/azure-sdk-for-net,atpham256/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,r22016/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,oburlacu/azure-sdk-for-net,Nilambari/azure-sdk-for-net,pankajsn/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,mabsimms/azure-sdk-for-net,yoreddy/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,nacaspi/azure-sdk-for-net,pilor/azure-sdk-for-net,nemanja88/azure-sdk-for-net,tpeplow/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,btasdoven/azure-sdk-for-net,shuainie/azure-sdk-for-net,olydis/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,marcoippel/azure-sdk-for-net,alextolp/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,nacaspi/azure-sdk-for-net,olydis/azure-sdk-for-net,nathannfan/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,djyou/azure-sdk-for-net,abhing/azure-sdk-for-net,makhdumi/azure-sdk-for-net,oaastest/azure-sdk-for-net,gubookgu/azure-sdk-for-net,pattipaka/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,shuagarw/azure-sdk-for-net,shutchings/azure-sdk-for-net,naveedaz/azure-sdk-for-net,stankovski/azure-sdk-for-net,scottrille/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,djyou/azure-sdk-for-net,pattipaka/azure-sdk-for-net,stankovski/azure-sdk-for-net,hyonholee/azure-sdk-for-net,herveyw/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,abhing/azure-sdk-for-net,shutchings/azure-sdk-for-net,guiling/azure-sdk-for-net,Nilambari/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,shuagarw/azure-sdk-for-net,begoldsm/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,samtoubia/azure-sdk-for-net,jianghaolu/azure-sdk-for-net,oburlacu/azure-sdk-for-net,jtlibing/azure-sdk-for-net,lygasch/azure-sdk-for-net,AuxMon/azure-sdk-for-net,vhamine/azure-sdk-for-net,btasdoven/azure-sdk-for-net,oburlacu/azure-sdk-for-net,cwickham3/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,makhdumi/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,smithab/azure-sdk-for-net,olydis/azure-sdk-for-net,peshen/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,hallihan/azure-sdk-for-net,markcowl/azure-sdk-for-net,naveedaz/azure-sdk-for-net,bgold09/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,jamestao/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,samtoubia/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,amarzavery/azure-sdk-for-net,vladca/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,AzCiS/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,pankajsn/azure-sdk-for-net,begoldsm/azure-sdk-for-net,mihymel/azure-sdk-for-net,akromm/azure-sdk-for-net,mumou/azure-sdk-for-net,vhamine/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,arijitt/azure-sdk-for-net,namratab/azure-sdk-for-net,AuxMon/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,shipram/azure-sdk-for-net,r22016/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,bgold09/azure-sdk-for-net,guiling/azure-sdk-for-net,xindzhan/azure-sdk-for-net,namratab/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,pilor/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,pilor/azure-sdk-for-net,marcoippel/azure-sdk-for-net,samtoubia/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,mihymel/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,ailn/azure-sdk-for-net,smithab/azure-sdk-for-net,pomortaz/azure-sdk-for-net,hovsepm/azure-sdk-for-net,nemanja88/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,huangpf/azure-sdk-for-net,jamestao/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,akromm/azure-sdk-for-net,shuagarw/azure-sdk-for-net,pinwang81/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,atpham256/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,zaevans/azure-sdk-for-net,alextolp/azure-sdk-for-net,enavro/azure-sdk-for-net,abhing/azure-sdk-for-net,xindzhan/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,tpeplow/azure-sdk-for-net,dominiqa/azure-sdk-for-net,cwickham3/azure-sdk-for-net,oaastest/azure-sdk-for-net,juvchan/azure-sdk-for-net,dominiqa/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,r22016/azure-sdk-for-net,shuainie/azure-sdk-for-net,arijitt/azure-sdk-for-net,shipram/azure-sdk-for-net,oaastest/azure-sdk-for-net,relmer/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,akromm/azure-sdk-for-net,pinwang81/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,djoelz/azure-sdk-for-net,jtlibing/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,rohmano/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,vladca/azure-sdk-for-net,rohmano/azure-sdk-for-net,ogail/azure-sdk-for-net,robertla/azure-sdk-for-net,mabsimms/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,herveyw/azure-sdk-for-net,jamestao/azure-sdk-for-net,dasha91/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,ailn/azure-sdk-for-net,nemanja88/azure-sdk-for-net,naveedaz/azure-sdk-for-net,ogail/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,kagamsft/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,alextolp/azure-sdk-for-net,AzCiS/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,gubookgu/azure-sdk-for-net,pinwang81/azure-sdk-for-net,smithab/azure-sdk-for-net,Nilambari/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,robertla/azure-sdk-for-net,relmer/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,hovsepm/azure-sdk-for-net,juvchan/azure-sdk-for-net,nathannfan/azure-sdk-for-net,namratab/azure-sdk-for-net,pankajsn/azure-sdk-for-net,hovsepm/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,scottrille/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,mihymel/azure-sdk-for-net,marcoippel/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,enavro/azure-sdk-for-net,peshen/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,enavro/azure-sdk-for-net,herveyw/azure-sdk-for-net,amarzavery/azure-sdk-for-net,peshen/azure-sdk-for-net,dasha91/azure-sdk-for-net,relmer/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,pomortaz/azure-sdk-for-net,tpeplow/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,hyonholee/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,pomortaz/azure-sdk-for-net,lygasch/azure-sdk-for-net,hyonholee/azure-sdk-for-net,samtoubia/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,travismc1/azure-sdk-for-net,djyou/azure-sdk-for-net,makhdumi/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,dasha91/azure-sdk-for-net,vladca/azure-sdk-for-net,djoelz/azure-sdk-for-net,zaevans/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net | microsoft-azure-api/Configuration/Microsoft.WindowsAzure.Configuration/Properties/AssemblyInfo.cs | microsoft-azure-api/Configuration/Microsoft.WindowsAzure.Configuration/Properties/AssemblyInfo.cs | //
// Copyright Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: AssemblyTitle("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyDescription("Configuration API for Windows Azure services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a4d8eda-db18-4c6f-9f84-4576bb255f30")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| //
// Copyright Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: AssemblyTitle("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyDescription("Configuration API for Windows Azure services.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft.WindowsAzure.Configuration")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3a4d8eda-db18-4c6f-9f84-4576bb255f30")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]
| apache-2.0 | C# |
9a4913063d843776b6d15fcf7c67e654dfe36e3a | clean up: remove unused import | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Yaml/Psi/DeferredCaches/AnimatorUsages/IAnimatorScriptUsage.cs | resharper/resharper-unity/src/Yaml/Psi/DeferredCaches/AnimatorUsages/IAnimatorScriptUsage.cs | using JetBrains.Annotations;
using JetBrains.Serialization;
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AnimatorUsages
{
public interface IAnimatorScriptUsage : IScriptUsage
{
[NotNull]
string Name { get; }
void WriteTo([NotNull] UnsafeWriter writer);
}
} | using System;
using JetBrains.Annotations;
using JetBrains.Serialization;
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AnimatorUsages
{
public interface IAnimatorScriptUsage : IScriptUsage
{
[NotNull]
string Name { get; }
void WriteTo([NotNull] UnsafeWriter writer);
}
} | apache-2.0 | C# |
3a72ba64d196fbe0fae4d4403c679edb3eb634c9 | Hide ffmpeg banner | Yuisbean/WebMConverter,o11c/WebMConverter,nixxquality/WebMConverter | Components/FFmpeg.cs | Components/FFmpeg.cs | using System;
using System.Diagnostics;
using System.IO;
namespace WebMConverter
{
class FFmpeg : Process //Refactoring, faggots.
{
public string FFmpegPath;
public FFmpeg(string argument, bool win32 = false)
{
string folder;
if (win32)
folder = "Win32";
else
if (Environment.Is64BitOperatingSystem)
folder = "Win64";
else
folder = "Win32";
FFmpegPath = Path.Combine(Environment.CurrentDirectory, "Binaries", folder, "ffmpeg.exe");
this.StartInfo.FileName = FFmpegPath;
this.StartInfo.Arguments = "-hide_banner " + argument;
this.StartInfo.RedirectStandardInput = true;
this.StartInfo.RedirectStandardOutput = true;
this.StartInfo.RedirectStandardError = true;
this.StartInfo.UseShellExecute = false; //Required to redirect IO streams
this.StartInfo.CreateNoWindow = true; //Hide console
this.EnableRaisingEvents = true;
}
new public void Start()
{
Start(true);
}
public void Start(bool OutputReadLine)
{
base.Start();
this.BeginErrorReadLine();
if (OutputReadLine)
this.BeginOutputReadLine();
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
namespace WebMConverter
{
class FFmpeg : Process //Refactoring, faggots.
{
public string FFmpegPath;
public FFmpeg(string argument, bool win32 = false)
{
string folder;
if (win32)
folder = "Win32";
else
if (Environment.Is64BitOperatingSystem)
folder = "Win64";
else
folder = "Win32";
FFmpegPath = Path.Combine(Environment.CurrentDirectory, "Binaries", folder, "ffmpeg.exe");
this.StartInfo.FileName = FFmpegPath;
this.StartInfo.Arguments = argument;
this.StartInfo.RedirectStandardInput = true;
this.StartInfo.RedirectStandardOutput = true;
this.StartInfo.RedirectStandardError = true;
this.StartInfo.UseShellExecute = false; //Required to redirect IO streams
this.StartInfo.CreateNoWindow = true; //Hide console
this.EnableRaisingEvents = true;
}
new public void Start()
{
Start(true);
}
public void Start(bool OutputReadLine)
{
base.Start();
this.BeginErrorReadLine();
if (OutputReadLine)
this.BeginOutputReadLine();
}
}
}
| mit | C# |
a1199a52d97aea1dce7f360c265ff271a390ec3a | Update App.cs | TorbenK/TK.CustomMap | Sample/TK.CustomMap.Sample/TK.CustomMap.Sample/App.cs | Sample/TK.CustomMap.Sample/TK.CustomMap.Sample/App.cs | using TK.CustomMap.Api.Google;
using Xamarin.Forms;
namespace TK.CustomMap.Sample
{
public class App : Application
{
public App()
{
GmsPlace.Init("YOUR API KEY");
GmsDirection.Init("YOUR API KEY");
// The root page of your application
MainPage = new SamplePage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| using TK.CustomMap.Api.Google;
using Xamarin.Forms;
namespace TK.CustomMap.Sample
{
public class App : Application
{
public App()
{
GmsPlace.Init("YOUR API KEY");
GmsDirection.Init("AIzaSyCpAu6gru_MOol9M3Kg4ZNIMrEnRl9JS6A");
// The root page of your application
MainPage = new SamplePage();
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| mit | C# |
8cad3ea5a6a745ffad6d1414a7391bdd9b936347 | Fix to be able to load unmanaged dlls in the carna-runner. | averrunci/Carna | Source/CarnaConsoleRunner/CarnaAssemblyLoadContext.cs | Source/CarnaConsoleRunner/CarnaAssemblyLoadContext.cs | // Copyright (C) 2020 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Reflection;
using System.Runtime.Loader;
namespace Carna.ConsoleRunner
{
internal class CarnaAssemblyLoadContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver assemblyDependencyResolver;
public CarnaAssemblyLoadContext(string assemblyPath)
{
assemblyDependencyResolver = new AssemblyDependencyResolver(assemblyPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
var assemblyPath = assemblyDependencyResolver.ResolveAssemblyToPath(assemblyName);
return assemblyPath == null ? null : LoadFromAssemblyPath(assemblyPath);
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
var unmanagedDllPath = assemblyDependencyResolver.ResolveUnmanagedDllToPath(unmanagedDllName);
return unmanagedDllPath == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(unmanagedDllPath);
}
}
}
| // Copyright (C) 2020 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Reflection;
using System.Runtime.Loader;
namespace Carna.ConsoleRunner
{
internal class CarnaAssemblyLoadContext : AssemblyLoadContext
{
private readonly AssemblyDependencyResolver assemblyDependencyResolver;
public CarnaAssemblyLoadContext(string assemblyPath)
{
assemblyDependencyResolver = new AssemblyDependencyResolver(assemblyPath);
}
protected override Assembly Load(AssemblyName assemblyName)
{
var assemblyPath = assemblyDependencyResolver.ResolveAssemblyToPath(assemblyName);
return assemblyPath == null ? null : LoadFromAssemblyPath(assemblyPath);
}
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
{
var unmanagedDllPath = assemblyDependencyResolver.ResolveUnmanagedDllToPath(unmanagedDllName);
return unmanagedDllPath == null ? IntPtr.Zero : LoadUnmanagedDllFromPath(unmanagedDllName);
}
}
}
| mit | C# |
52de2d548fd8b175d28e65a28dee7608701664aa | Remove superfulous new line | sbennett1990/signify.cs | SignifyCS/Main.cs | SignifyCS/Main.cs | /*
* Copyright (c) 2017 Scott Bennett <scottb@fastmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System;
using System.IO;
using libcmdline;
namespace SignifyCS {
public enum FileType {
Signiture,
PublicKey
};
public class Signify {
public static void Main(string[] args) {
PubKey pub_key = default(PubKey);
Signature sig = default(Signature);
byte[] message = new byte[0];
try {
CommandLineArgs cmd_args = new CommandLineArgs();
cmd_args.PrefixRegexPatternList.Add("-{1}");
cmd_args.registerSpecificSwitchMatchHandler("p", (sender, e) => {
using (FileStream pub_key_file = readFile(e.Value)) {
pub_key = PubKeyCryptoFile.ParsePubKeyFile(pub_key_file);
}
});
cmd_args.registerSpecificSwitchMatchHandler("x", (sender, e) => {
using (FileStream sig_file = readFile(e.Value)) {
sig = SigCryptoFile.ParseSigFile(sig_file);
}
});
cmd_args.registerSpecificSwitchMatchHandler("m", (sender, e) => {
message = File.ReadAllBytes(e.Value);
});
cmd_args.processCommandLineArgs(args);
if (cmd_args.ArgCount < 3) {
Console.WriteLine("usage: signify -p pubkey -x sigfile -m message");
throw new Exception();
}
bool success = Verify.VerifyMessage(pub_key, sig, message);
if (success) {
Console.WriteLine("\nSignature Verified");
} else {
Console.WriteLine("\nsignature verification failed");
}
} catch (Exception e) {
Console.WriteLine(e.Message);
#if DEBUG
Console.WriteLine(e.StackTrace);
#endif
}
}
private static FileStream readFile(string file_name) {
if (!File.Exists(file_name)) {
throw new Exception($"File not found: {file_name}");
}
return new FileStream(file_name, FileMode.Open, FileAccess.Read, FileShare.Read);
}
}
}
| /*
* Copyright (c) 2017 Scott Bennett <scottb@fastmail.com>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
using System;
using System.IO;
using libcmdline;
namespace SignifyCS {
public enum FileType {
Signiture,
PublicKey
};
public class Signify {
public static void Main(string[] args) {
PubKey pub_key = default(PubKey);
Signature sig = default(Signature);
byte[] message = new byte[0];
try {
CommandLineArgs cmd_args = new CommandLineArgs();
cmd_args.PrefixRegexPatternList.Add("-{1}");
cmd_args.registerSpecificSwitchMatchHandler("p", (sender, e) => {
using (FileStream pub_key_file = readFile(e.Value)) {
pub_key = PubKeyCryptoFile.ParsePubKeyFile(pub_key_file);
}
});
cmd_args.registerSpecificSwitchMatchHandler("x", (sender, e) => {
using (FileStream sig_file = readFile(e.Value)) {
sig = SigCryptoFile.ParseSigFile(sig_file);
}
});
cmd_args.registerSpecificSwitchMatchHandler("m", (sender, e) => {
message = File.ReadAllBytes(e.Value);
});
cmd_args.processCommandLineArgs(args);
if (cmd_args.ArgCount < 3) {
Console.WriteLine("usage: signify -p pubkey -x sigfile -m message");
throw new Exception();
}
bool success = Verify.VerifyMessage(pub_key, sig, message);
if (success) {
Console.WriteLine("\nSignature Verified");
} else {
Console.WriteLine("\nsignature verification failed");
}
} catch (Exception e) {
Console.WriteLine(e.Message);
#if DEBUG
Console.WriteLine(e.StackTrace);
#endif
}
Console.WriteLine();
}
private static FileStream readFile(string file_name) {
if (!File.Exists(file_name)) {
throw new Exception($"File not found: {file_name}");
}
return new FileStream(file_name, FileMode.Open, FileAccess.Read, FileShare.Read);
}
}
}
| isc | C# |
01c4ec39c024e6301783354eb136eac116e20b7c | Fix issue with multi-selected checkboxes within a group not being posted properly. | abhaypsingh/SimpleBrowser,abhaypsingh/SimpleBrowser | SimpleBrowser/Internal/StringUtil.cs | SimpleBrowser/Internal/StringUtil.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
namespace SimpleBrowser
{
internal static class StringUtil
{
private static readonly Random Randomizer = new Random(Convert.ToInt32(DateTime.UtcNow.Ticks % int.MaxValue));
public static string GenerateRandomString(int chars)
{
string s = "";
for (int i = 0; i < chars; i++)
{
int x = Randomizer.Next(2);
switch (x)
{
case 0: s += (char)(Randomizer.Next(10) + 48); break; // 0-9
case 1: s += (char)(Randomizer.Next(26) + 65); break; // A-Z
case 2: s += (char)(Randomizer.Next(26) + 97); break; // a-z
}
}
return s;
}
public class LowerCaseComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return string.Compare(x, y, true) == 0;
}
public int GetHashCode(string obj)
{
return obj.ToLower().GetHashCode();
}
}
public static string MakeQueryString(IDictionary values)
{
if (values == null)
return string.Empty;
List<string> list = new List<string>();
foreach (object key in values.Keys)
list.Add(HttpUtility.UrlEncode(key.ToString()) + "=" + HttpUtility.UrlEncode(values[key].ToString()));
return list.Concat("&");
}
public static string MakeQueryString(NameValueCollection values)
{
if (values == null)
return string.Empty;
List<string> list = new List<string>();
foreach (string key in values.Keys)
{
foreach (string value in values.GetValues(key))
list.Add(HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(value));
}
return list.Concat("&");
}
public static string MakeQueryString(params KeyValuePair<string, string>[] values)
{
Dictionary<string, string> v = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> kvp in values)
v[kvp.Key] = kvp.Value;
return MakeQueryString(v);
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web;
namespace SimpleBrowser
{
internal static class StringUtil
{
private static readonly Random Randomizer = new Random(Convert.ToInt32(DateTime.UtcNow.Ticks % int.MaxValue));
public static string GenerateRandomString(int chars)
{
string s = "";
for (int i = 0; i < chars; i++)
{
int x = Randomizer.Next(2);
switch (x)
{
case 0: s += (char)(Randomizer.Next(10) + 48); break; // 0-9
case 1: s += (char)(Randomizer.Next(26) + 65); break; // A-Z
case 2: s += (char)(Randomizer.Next(26) + 97); break; // a-z
}
}
return s;
}
public class LowerCaseComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return string.Compare(x, y, true) == 0;
}
public int GetHashCode(string obj)
{
return obj.ToLower().GetHashCode();
}
}
public static string MakeQueryString(IDictionary values)
{
if (values == null)
return string.Empty;
List<string> list = new List<string>();
foreach (object key in values.Keys)
list.Add(HttpUtility.UrlEncode(key.ToString()) + "=" + HttpUtility.UrlEncode(values[key].ToString()));
return list.Concat("&");
}
public static string MakeQueryString(NameValueCollection values)
{
if (values == null)
return string.Empty;
List<string> list = new List<string>();
foreach (string key in values.Keys)
list.Add(HttpUtility.UrlEncode(key) + "=" + HttpUtility.UrlEncode(values[key]));
return list.Concat("&");
}
public static string MakeQueryString(params KeyValuePair<string, string>[] values)
{
Dictionary<string, string> v = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> kvp in values)
v[kvp.Key] = kvp.Value;
return MakeQueryString(v);
}
}
} | bsd-3-clause | C# |
e2320c81d5c5ab68a786432753241fccbce3aa74 | Make obsoletE | mavasani/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn | src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDiagnosticData.cs | src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/VSTypeScriptDiagnosticData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal readonly struct VSTypeScriptDiagnosticData
{
private readonly DiagnosticData _data;
internal VSTypeScriptDiagnosticData(DiagnosticData data)
{
_data = data;
}
public DiagnosticSeverity Severity
=> _data.Severity;
public string? Message
=> _data.Message;
public string Id
=> _data.Id;
public ImmutableArray<string> CustomTags
=> _data.CustomTags;
/// <summary>
/// Note: the <paramref name="useMapped"/> parameter is ignored.
/// </summary>
[Obsolete("Use overload that only takes a SourceText")]
public LinePositionSpan GetLinePositionSpan(SourceText sourceText, bool useMapped)
{
// TypeScript has no concept of mapped spans, so this should never be passed 'true'.
Contract.ThrowIfTrue(useMapped);
return DiagnosticData.GetUnmappedLinePositionSpan(_data.DataLocation, sourceText);
}
public LinePositionSpan GetLinePositionSpan(SourceText sourceText)
=> DiagnosticData.GetUnmappedLinePositionSpan(_data.DataLocation, sourceText);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api
{
internal readonly struct VSTypeScriptDiagnosticData
{
private readonly DiagnosticData _data;
internal VSTypeScriptDiagnosticData(DiagnosticData data)
{
_data = data;
}
public DiagnosticSeverity Severity
=> _data.Severity;
public string? Message
=> _data.Message;
public string Id
=> _data.Id;
public ImmutableArray<string> CustomTags
=> _data.CustomTags;
/// <summary>
/// Note: the <paramref name="useMapped"/> parameter is ignored.
/// </summary>
public LinePositionSpan GetLinePositionSpan(SourceText sourceText, bool useMapped)
{
// TypeScript has no concept of mapped spans, so this should never be passed 'true'.
Contract.ThrowIfTrue(useMapped);
return DiagnosticData.GetUnmappedLinePositionSpan(_data.DataLocation, sourceText);
}
}
}
| mit | C# |
c602b6cff382ba1d139ef074a196316d3f29723f | FIx issue looking up property aliases for built-in datatypes | imulus/census,imulus/census | Src/Census/UmbracoObject/Property.cs | Src/Census/UmbracoObject/Property.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Census.Interfaces;
namespace Census.UmbracoObject
{
public class Property : IUmbracoObject
{
public string Name { get { return "Document Type"; } }
public List<string> BackofficePages
{
get { return new List<string>() {"/settings/editNodeTypeNew.aspx"}; }
}
DataTable IUmbracoObject.ToDataTable(object usages)
{
return ToDataTable(usages);
}
public static DataTable ToDataTable(object usages, int propertyId = 0)
{
var documentTypes = (IEnumerable<global::umbraco.cms.businesslogic.web.DocumentType>) usages;
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Alias");
dt.Columns.Add("Property");
foreach (var documentType in documentTypes)
{
var row = dt.NewRow();
row["Name"] = Helper.GenerateLink(documentType.Text, "settings", "/settings/editNodeTypeNew.aspx?id=" + documentType.Id, "settingMasterDataType.gif");
row["Alias"] = documentType.Alias;
if (propertyId != 0)
{
var prop = documentType.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.Id == propertyId);
if (prop != null)
row["Property"] = prop.Name;
}
dt.Rows.Add(row);
row.AcceptChanges();
}
return dt;
}
}
} | using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Census.Interfaces;
namespace Census.UmbracoObject
{
public class Property : IUmbracoObject
{
public string Name { get { return "Document Type"; } }
public List<string> BackofficePages
{
get { return new List<string>() {"/settings/editNodeTypeNew.aspx"}; }
}
DataTable IUmbracoObject.ToDataTable(object usages)
{
return ToDataTable(usages);
}
public static DataTable ToDataTable(object usages, int propertyId = 0)
{
var documentTypes = (IEnumerable<global::umbraco.cms.businesslogic.web.DocumentType>) usages;
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Alias");
dt.Columns.Add("Property");
foreach (var documentType in documentTypes)
{
var row = dt.NewRow();
row["Name"] = Helper.GenerateLink(documentType.Text, "settings", "/settings/editNodeTypeNew.aspx?id=" + documentType.Id, "settingMasterDataType.gif");
row["Alias"] = documentType.Alias;
if (propertyId > 0)
{
var prop = documentType.PropertyTypes.FirstOrDefault(x => x.DataTypeDefinition.Id == propertyId);
if (prop != null)
row["Property"] = prop.Name;
}
dt.Rows.Add(row);
row.AcceptChanges();
}
return dt;
}
}
} | mit | C# |
f85717ed16cecca47162b22ee4841ff8db809bcc | Make Page handle edit summary | Skalman/svwikt-suite | SvwiktSuite/SvwiktSuite/Core/Page.cs | SvwiktSuite/SvwiktSuite/Core/Page.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace SvwiktSuite
{
public class Page
{
public Page(JToken json)
: this(
title: (string)json ["title"],
text: (string)json ["revisions"] [0] ["*"] + "\n",
timestamp: (string)json ["revisions"] [0] ["timestamp"])
{
}
public Page(string title, string text, string timestamp = "")
{
Text = text;
OriginalText = text;
Title = title;
Timestamp = timestamp;
Summary = new SummaryBuilder();
}
public string Text { get; set; }
public string OriginalText { get; private set; }
public string Title { get; private set; }
public string Timestamp { get; private set; }
public bool Changed
{
get
{
return Text != OriginalText;
}
}
public SummaryBuilder Summary { get; private set; }
public override string ToString()
{
return Title;
}
public class SummaryBuilder
{
protected IList<string> Parts, MinorParts;
public SummaryBuilder()
{
Parts = new List<string>();
MinorParts = new List<string>();
}
public void Add(string summary)
{
Parts.Add(summary);
}
public void AddMinor(string summary)
{
MinorParts.Add(summary);
}
public string Text
{
get
{
var l = new List<string>(Parts);
l.AddRange(MinorParts);
return string.Join("; ", l.Distinct());
}
set
{
MinorParts.Clear();
Parts.Clear();
if (value != null)
Parts.Add(value);
}
}
public override string ToString()
{
return Text;
}
}
}
}
| using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace SvwiktSuite
{
public class Page
{
public Page(JToken json)
: this(
title: (string)json ["title"],
text: (string)json ["revisions"] [0] ["*"] + "\n",
timestamp: (string)json ["revisions"] [0] ["timestamp"])
{
}
public Page(string title, string text, string timestamp = "")
{
Text = text;
Title = title;
Timestamp = timestamp;
}
public string Text { get; set; }
public string Title { get; private set; }
public string Timestamp { get; private set; }
public override string ToString()
{
return Title;
}
}
}
| mpl-2.0 | C# |
92fadd748469605f33d5b67824fda44888a6211e | fix locked file in peverify test | GeertvanHorrik/Fody,Fody/Fody | Tests/FodyHelpers/PeVerifierTests.cs | Tests/FodyHelpers/PeVerifierTests.cs | using System;
using System.IO;
using Fody;
using Mono.Cecil;
using Xunit;
#pragma warning disable 618
public class PeVerifierTests : TestBase
{
[Fact]
public void StaticPathResolution()
{
Assert.True(PeVerifier.FoundPeVerify);
}
[Fact]
public void Should_verify_current_assembly()
{
var verify = PeVerifier.Verify(GetAssemblyPath(), GetIgnoreCodes(), out var output);
Assert.True(verify);
Assert.NotNull(output);
Assert.NotEmpty(output);
}
[Fact]
public void Same_assembly_should_not_throw()
{
var assemblyPath = GetAssemblyPath().ToLowerInvariant();
Directory.CreateDirectory("temp");
var newAssemblyPath = Path.GetFullPath("temp/temp.dll");
File.Copy(assemblyPath, newAssemblyPath, true);
PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath,
ignoreCodes: GetIgnoreCodes());
File.Delete(newAssemblyPath);
}
static string[] GetIgnoreCodes()
{
return new[] { "0x80070002", "0x80131869" };
}
[Fact]
public void Invalid_assembly_should_throw()
{
var assemblyPath = GetAssemblyPath().ToLowerInvariant();
Directory.CreateDirectory("temp");
var newAssemblyPath = Path.GetFullPath("temp/temp.dll");
File.Copy(assemblyPath, newAssemblyPath, true);
using (var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath))
{
moduleDefinition.AssemblyReferences.Clear();
moduleDefinition.Write(newAssemblyPath);
}
Assert.Throws<Exception>(() => PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath));
File.Delete(newAssemblyPath);
}
static string GetAssemblyPath()
{
var assembly = typeof(TestBase).Assembly;
var uri = new UriBuilder(assembly.CodeBase);
return Uri.UnescapeDataString(uri.Path);
}
} | using System;
using System.IO;
using Fody;
using Mono.Cecil;
using Xunit;
#pragma warning disable 618
public class PeVerifierTests : TestBase
{
[Fact]
public void StaticPathResolution()
{
Assert.True(PeVerifier.FoundPeVerify);
}
[Fact]
public void Should_verify_current_assembly()
{
#if (NET46)
var verify = PeVerifier.Verify(GetAssemblyPath(), System.Linq.Enumerable.Empty<string>(), out var output);
#else
var verify = PeVerifier.Verify(GetAssemblyPath(), GetNetCoreIgnoreCodes(), out var output);
#endif
Assert.True(verify);
Assert.NotNull(output);
Assert.NotEmpty(output);
}
[Fact]
public void Same_assembly_should_not_throw()
{
var assemblyPath = GetAssemblyPath().ToLowerInvariant();
var newAssemblyPath = assemblyPath.Replace(".dll", "2.dll");
File.Copy(assemblyPath, newAssemblyPath, true);
#if (NET46)
PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath);
#else
PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath,
ignoreCodes: GetNetCoreIgnoreCodes());
#endif
File.Delete(newAssemblyPath);
}
private static string[] GetNetCoreIgnoreCodes()
{
return new[] {"0x80070002", "0x80131869"};
}
[Fact]
public void Invalid_assembly_should_throw()
{
var assemblyPath = GetAssemblyPath().ToLowerInvariant();
var newAssemblyPath = assemblyPath.Replace(".dll", "2.dll");
File.Copy(assemblyPath, newAssemblyPath, true);
using (var moduleDefinition = ModuleDefinition.ReadModule(assemblyPath))
{
moduleDefinition.AssemblyReferences.Clear();
moduleDefinition.Write(newAssemblyPath);
}
Assert.Throws<Exception>(() => PeVerifier.ThrowIfDifferent(assemblyPath, newAssemblyPath));
File.Delete(newAssemblyPath);
}
static string GetAssemblyPath()
{
var assembly = typeof(TestBase).Assembly;
var uri = new UriBuilder(assembly.CodeBase);
return Uri.UnescapeDataString(uri.Path);
}
} | mit | C# |
8f57bf2498f628b0b751390714e4554faeb7617b | Add choices of hover sample sets | UselessToucan/osu,UselessToucan/osu,ZLima12/osu,Frontear/osuKyzer,DrabWeb/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,peppy/osu,naoey/osu,ppy/osu,2yangk23/osu,Nabile-Rahmani/osu,smoogipoo/osu,naoey/osu,peppy/osu,ppy/osu,johnneijzen/osu,johnneijzen/osu,DrabWeb/osu,peppy/osu-new,naoey/osu,DrabWeb/osu,ZLima12/osu,2yangk23/osu,smoogipooo/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Graphics/UserInterface/OsuButton.cs | osu.Game/Graphics/UserInterface/OsuButton.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A button with added default sound effects.
/// </summary>
public class OsuButton : Button
{
private SampleChannel sampleClick;
private SampleChannel sampleHover;
protected HoverSampleSet SampleSet = HoverSampleSet.Normal;
protected override bool OnClick(InputState state)
{
sampleClick?.Play();
return base.OnClick(state);
}
protected override bool OnHover(InputState state)
{
sampleHover?.Play();
return base.OnHover(state);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Sample.Get($@"UI/generic-select{SampleSet.GetDescription()}");
sampleHover = audio.Sample.Get($@"UI/generic-hover{SampleSet.GetDescription()}");
}
public enum HoverSampleSet
{
[Description("")]
Normal,
[Description("-soft")]
Soft,
[Description("-softer")]
Softer
}
}
}
| // Copyright (c) 2007-2017 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.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// A button with added default sound effects.
/// </summary>
public class OsuButton : Button
{
private SampleChannel sampleClick;
private SampleChannel sampleHover;
protected override bool OnClick(InputState state)
{
sampleClick?.Play();
return base.OnClick(state);
}
protected override bool OnHover(InputState state)
{
sampleHover?.Play();
return base.OnHover(state);
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, AudioManager audio)
{
sampleClick = audio.Sample.Get(@"UI/generic-select");
sampleHover = audio.Sample.Get(@"UI/generic-hover");
}
}
}
| mit | C# |
4266ed9d4a6de5d04289d00b74c85c18dd389463 | Update Strings.cs | gerco/duplicati,sitofabi/duplicati,gerco/duplicati,duplicati/duplicati,agrajaghh/duplicati,sitofabi/duplicati,sitofabi/duplicati,duplicati/duplicati,mnaiman/duplicati,mnaiman/duplicati,klammbueddel/duplicati,sitofabi/duplicati,agrajaghh/duplicati,klammbueddel/duplicati,duplicati/duplicati,agrajaghh/duplicati,sitofabi/duplicati,klammbueddel/duplicati,duplicati/duplicati,mnaiman/duplicati,gerco/duplicati,gerco/duplicati,agrajaghh/duplicati,mnaiman/duplicati,duplicati/duplicati,mnaiman/duplicati,gerco/duplicati,klammbueddel/duplicati,agrajaghh/duplicati,klammbueddel/duplicati | Duplicati/Library/Compression/Strings.cs | Duplicati/Library/Compression/Strings.cs | using Duplicati.Library.Localization.Short;
namespace Duplicati.Library.Compression.Strings {
internal static class FileArchiveZip {
public static string CompressionlevelDeprecated(string optionname) { return LC.L(@"Please use the {0} option instead", optionname); }
public static string CompressionlevelLong { get { return LC.L(@"This option controls the compression level used. A setting of zero gives no compression, and a setting of 9 gives maximum compression."); } }
public static string CompressionlevelShort { get { return LC.L(@"Sets the Zip compression level"); } }
public static string CompressionmethodLong(string optionname) { return LC.L(@"This option can be used to set an alternative compressor method, such as LZMA. Note that using another value then Deflate will cause the {0} option to be ignored.", optionname); }
public static string CompressionmethodShort { get { return LC.L(@"Sets the Zip compression method"); } }
public static string Description { get { return LC.L(@"This module provides the industry standard Zip compression. Files created with this module can be read by any standard compliant zip application."); } }
public static string DisplayName { get { return LC.L(@"Zip compression"); } }
public static string FileNotFoundError(string filename) { return LC.L(@"File not found: {0}", filename); }
}
internal static class SevenZipCompression {
public static string NoWriterError { get { return LC.L(@"Archive not opened for writing"); } }
public static string NoReaderError { get { return LC.L(@"Archive not opened for reading"); } }
public static string FileNotFoundError { get { return LC.L(@"The given file is not part of this archive"); } }
public static string Description { get { return LC.L(@"7z Archive with LZMA2 support."); } }
public static string DisplayName { get { return LC.L(@"7z Archive"); } }
public static string ThreadcountLong { get { return LC.L(@"The number of threads used in LZMA 2 compression. Defaults to the number of processor cores.."); } }
public static string ThreadcountShort { get { return LC.L(@"Number of threads used in compression"); } }
public static string CompressionlevelLong { get { return LC.L(@"This option controls the compression level used. A setting of zero gives no compression, and a setting of 9 gives maximum compression."); } }
public static string CompressionlevelShort { get { return LC.L(@"Sets the 7z compression level"); } }
public static string FastalgoLong { get { return LC.L(@"This option controls the compression algorithm used. Enabling this option will cause 7z to use the fast algorithm, which produces slightly less compression."); } }
public static string FastalgoShort { get { return LC.L(@"Sets the 7z fast algorithm usage"); } }
}
}
| using Duplicati.Library.Localization.Short;
namespace Duplicati.Library.Compression.Strings {
internal static class FileArchiveZip {
public static string CompressionlevelDeprecated(string optionname) { return LC.L(@"Please use the {0} option instead", optionname); }
public static string CompressionlevelLong { get { return LC.L(@"This option controls the compression level used. A setting of zero gives no compression, and a setting of 9 gives maximum compression."); } }
public static string CompressionlevelShort { get { return LC.L(@"Sets the Zip compression level"); } }
public static string CompressionmethodLong(string optionname) { return LC.L(@"This option can be used to set an alternative compressor method, such as LZMA. Note that using another value than Deflate will cause the {0} option to be ignored.", optionname); }
public static string CompressionmethodShort { get { return LC.L(@"Sets the Zip compression method"); } }
public static string Description { get { return LC.L(@"This module provides the industry standard Zip compression. Files created with this module can be read by any standard compliant zip application."); } }
public static string DisplayName { get { return LC.L(@"Zip compression"); } }
public static string FileNotFoundError(string filename) { return LC.L(@"File not found: {0}", filename); }
}
internal static class SevenZipCompression {
public static string NoWriterError { get { return LC.L(@"Archive not opened for writing"); } }
public static string NoReaderError { get { return LC.L(@"Archive not opened for reading"); } }
public static string FileNotFoundError { get { return LC.L(@"The given file is not part of this archive"); } }
public static string Description { get { return LC.L(@"7z Archive with LZMA2 support."); } }
public static string DisplayName { get { return LC.L(@"7z Archive"); } }
public static string ThreadcountLong { get { return LC.L(@"The number of threads used in LZMA 2 compression. Defaults to the number of processor cores.."); } }
public static string ThreadcountShort { get { return LC.L(@"Number of threads used in compression"); } }
public static string CompressionlevelLong { get { return LC.L(@"This option controls the compression level used. A setting of zero gives no compression, and a setting of 9 gives maximum compression."); } }
public static string CompressionlevelShort { get { return LC.L(@"Sets the 7z compression level"); } }
public static string FastalgoLong { get { return LC.L(@"This option controls the compression algorithm used. Enabling this option will cause 7z to use the fast algorithm, which produces slightly less compression."); } }
public static string FastalgoShort { get { return LC.L(@"Sets the 7z fast algorithm usage"); } }
}
}
| lgpl-2.1 | C# |
115cbe11ae71b0c2667653ee7d649316e24bc3ca | Remove IEquatable<T> inheritance from ITabsterDocument. | GetTabster/Tabster | Tabster.Core/FileTypes/ITabsterDocument.cs | Tabster.Core/FileTypes/ITabsterDocument.cs | #region
using System;
using System.IO;
#endregion
namespace Tabster.Core.FileTypes
{
public interface ITabsterDocument
{
Version FileVersion { get; }
FileInfo FileInfo { get; }
void Load(string filename);
void Save();
void Save(string fileName);
void Update();
}
} | #region
using System;
using System.IO;
#endregion
namespace Tabster.Core.FileTypes
{
public interface ITabsterDocument : IEquatable<ITabsterDocument>
{
Version FileVersion { get; }
FileInfo FileInfo { get; }
void Load(string filename);
void Save();
void Save(string fileName);
void Update();
}
} | apache-2.0 | C# |
d2cad3895a14f0f68d42251b63a63d66a900e1ae | use %domain%+url when redirecting to search instead of %current% + url | joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net | Joinrpg/Views/Shared/SuperSearchPartial.cshtml | Joinrpg/Views/Shared/SuperSearchPartial.cshtml | <span class="input-group input-group-xs">
<script>
function getRefToSearchResultsPage() {
var searchString = document.getElementById('SearchRequest').value;
return '/search?searchString=' + encodeURIComponent(searchString);
}
</script>
<input type="text" id="SearchRequest" name="SearchRequest" data-val-required="Требуется поле Искать." data-val="true" class="form-control"/>
<span class="input-group-btn">
<button class="btn btn-default" onclick="window.location.href = getRefToSearchResultsPage()"><span class="glyphicon glyphicon-search"></span></button>
</span>
</span>
| <span class="input-group input-group-xs">
<script>
function getRefToSearchResultsPage() {
var searchString = document.getElementById('SearchRequest').value;
return 'search?searchString=' + encodeURIComponent(searchString);
}
</script>
<input type="text" id="SearchRequest" name="SearchRequest" data-val-required="Требуется поле Искать." data-val="true" class="form-control"/>
<span class="input-group-btn">
<button class="btn btn-default" onclick="window.location.href = getRefToSearchResultsPage()"><span class="glyphicon glyphicon-search"></span></button>
</span>
</span>
| mit | C# |
c8e0d29bdb2596e847b01233d3155d5238624ac0 | Remove trailing whistespace | aloisdg/edx-csharp | edX/Module3/Program.cs | edX/Module3/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Module3
{
public class Program
{
public static void Main()
{
try
{
HandlePeople();
// ToDo
// course
//string courseName = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("We are going to exit the program.");
Console.WriteLine("See you next time.");
Console.ReadLine();
}
}
private static void HandlePeople()
{
const string studentStatus = "student";
const string teacherStatus = "teacher";
HandlePerson(studentStatus);
HandlePerson(teacherStatus);
}
private static void HandlePerson(string status)
{
string firstName = null;
string lastName = null;
ushort? age = null;
SetPersonDetails(status, ref firstName, ref lastName, ref age);
PrintPersonDetails(status, firstName, lastName, age);
Console.WriteLine();
}
private static void PrintPersonDetails(string status, string firstName, string lastName, ushort? age)
{
Console.WriteLine("{1}'s detail{0}" +
"{1}'s first name :\t{2}{0}" +
"{1}'s last name :\t{3}{0}" +
"{1}'s age :\t\t{4}",
Environment.NewLine, status, firstName, lastName, age);
}
private static void SetPersonDetails(string status, ref string firstName, ref string lastName, ref ushort? age)
{
const string output = "the {0}'s {1} ";
const ushort ageMax = 200;
ushort num;
firstName = HandleInputOutput(String.Format(output, status, "first name"));
lastName = HandleInputOutput(String.Format(output, status, "last name"));
if (!UInt16.TryParse(HandleInputOutput(String.Format(output, status, "age")).Trim(), out num) || num > ageMax)
throw new Exception("Age invalid!");
age = num;
}
private static string HandleInputOutput(string output)
{
Console.WriteLine("Enter {0}:", output);
return ReadInput();
}
private static string ReadInput()
{
string input;
if (IsNotNullNorWhiteSpace(Console.ReadLine(), out input))
return input;
throw new Exception("Input is null, empty or consists exclusively of white-space characters.");
}
public static bool IsNotNullNorWhiteSpace(string value, out string result)
{
result = String.Empty;
if (String.IsNullOrWhiteSpace(value))
return false;
result = value;
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Module3
{
public class Program
{
public static void Main()
{
try
{
HandlePeople();
// ToDo
// course
//string courseName = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("We are going to exit the program.");
Console.WriteLine("See you next time.");
Console.ReadLine();
}
}
private static void HandlePeople()
{
const string studentStatus = "student";
const string teacherStatus = "teacher";
HandlePerson(studentStatus);
HandlePerson(teacherStatus);
}
private static void HandlePerson(string status)
{
string firstName = null;
string lastName = null;
ushort? age = null;
SetPersonDetails(status, ref firstName, ref lastName, ref age);
PrintPersonDetails(status, firstName, lastName, age);
Console.WriteLine();
}
private static void PrintPersonDetails(string status, string firstName, string lastName, ushort? age)
{
Console.WriteLine("{1}'s detail{0}" +
"{1}'s first name :\t{2}{0}" +
"{1}'s last name :\t{3}{0}" +
"{1}'s age :\t\t{4}",
Environment.NewLine, status, firstName, lastName, age);
}
private static void SetPersonDetails(string status, ref string firstName, ref string lastName, ref ushort? age)
{
const string output = "the {0}'s {1} ";
const ushort ageMax = 200;
ushort num;
firstName = HandleInputOutput(String.Format(output, status, "first name"));
lastName = HandleInputOutput(String.Format(output, status, "last name"));
if (!UInt16.TryParse(HandleInputOutput(String.Format(output, status, "age")).Trim(), out num) || num > ageMax)
throw new Exception("Age invalid!");
age = num;
}
private static string HandleInputOutput(string output)
{
Console.WriteLine("Enter {0}: ", output);
return ReadInput();
}
private static string ReadInput()
{
string input;
if (IsNotNullNorWhiteSpace(Console.ReadLine(), out input))
return input;
throw new Exception("Input is null, empty or consists exclusively of white-space characters.");
}
public static bool IsNotNullNorWhiteSpace(string value, out string result)
{
result = String.Empty;
if (String.IsNullOrWhiteSpace(value))
return false;
result = value;
return true;
}
}
}
| mit | C# |
6ab28bd0bb998e89dcdfe70c16aa8ef1911d74b8 | optimize leastsquares | dkackman/LinqStatistics | LinqStatisticsTests/LeastSquaresTests.cs | LinqStatisticsTests/LeastSquaresTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LinqStatistics;
namespace LinqStatisticsTests
{
[TestClass]
public class LeastSquaresTests
{
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void LSExceptsAppropriately()
{
var data = new List<Tuple<double, double>>()
{
new Tuple<double, double>(1, 10)
};
var ls = data.LeastSquares();
}
[TestMethod]
public void SimpleLinearTrend()
{
var data = new List<Tuple<int, int>>()
{
new Tuple<int, int>(0, 0),
new Tuple<int, int>(1, 1),
new Tuple<int, int>(2, 2),
new Tuple<int, int>(3, 3)
};
var ls = data.LeastSquares();
Assert.AreEqual(ls.M, 1.0);
Assert.AreEqual(ls.B, 0.0);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using LinqStatistics;
namespace LinqStatisticsTests
{
[TestClass]
public class LeastSquaresTests
{
[TestMethod]
[ExpectedException(typeof(InvalidOperationException))]
public void LSExceptsAppropriately()
{
var data = new List<Tuple<double, double>>()
{
new Tuple<double, double>(1, 10)
};
var ls = data.LeastSquares();
}
}
}
| apache-2.0 | C# |
0ed0f1e392eb3a0c0c12691060c25b391dc7da43 | Optimize further | xPaw/adventofcode-solutions,xPaw/adventofcode-solutions,xPaw/adventofcode-solutions | 2021/Answers/Solutions/Day13.cs | 2021/Answers/Solutions/Day13.cs | using System;
using System.Linq;
using System.Text;
namespace AdventOfCode2021;
[Answer(13)]
class Day13 : IAnswer
{
public (string Part1, string Part2) Solve(string input)
{
var inputs = input.Split("\n\n");
var numbers = inputs[0]
.Split('\n')
.Select(l => l
.Split(',', 2)
.Select(n => int.Parse(n))
.ToArray()
)
.ToArray();
var maxX = 0;
var maxY = 0;
var part1 = 0;
foreach (var line in inputs[1].Split('\n'))
{
var fold = int.Parse(line[13..]);
var isY = line[11] == 'y';
if (isY)
{
foreach (var number in numbers)
{
var y = number[1];
if (y > fold)
{
number[1] = 2 * fold - y;
}
}
maxY = fold;
}
else
{
foreach (var number in numbers)
{
var x = number[0];
if (x > fold)
{
number[0] = 2 * fold - x;
}
}
maxX = fold;
}
if (part1 == 0)
{
part1 = numbers.DistinctBy(x => x[1] * 10000 + x[0]).Count();
}
}
var grid = new bool[maxY * maxX + maxX];
foreach (var coord in numbers)
{
grid[coord[1] * maxX + coord[0]] = true;
}
var part2 = new StringBuilder(maxY * maxX + maxY + 1);
part2.Append('\n');
for (int y = 0; y < maxY; y++)
{
for (int x = 0; x < maxX; x++)
{
part2.Append(grid[y * maxX + x] ? '#' : ' ');
}
part2.Append('\n');
}
return (part1.ToString(), part2.ToString());
}
}
| using System;
using System.Linq;
using System.Text;
namespace AdventOfCode2021;
[Answer(13)]
class Day13 : IAnswer
{
public (string Part1, string Part2) Solve(string input)
{
var inputs = input.Split("\n\n");
var numbers = inputs[0]
.Split('\n')
.Select(l => l
.Split(',', 2)
.Select(n => int.Parse(n))
.ToArray()
)
.ToArray();
var maxX = numbers.Max(x => x[0]) + 2;
var maxY = numbers.Max(y => y[1]) + 2;
var part1 = 0;
foreach (var line in inputs[1].Split('\n'))
{
var fold = int.Parse(line[13..]);
var isY = line[11] == 'y';
if (isY)
{
foreach (var number in numbers)
{
var y = number[1];
if (y > fold)
{
number[1] = 2 * fold - y;
}
}
maxY = fold;
}
else
{
foreach (var number in numbers)
{
var x = number[0];
if (x > fold)
{
number[0] = 2 * fold - x;
}
}
maxX = fold;
}
if (part1 == 0)
{
part1 = numbers.DistinctBy(x => x[1] * maxY + x[0]).Count();
}
}
var grid = new bool[maxY][];
for (var i = 0; i < maxY; i++)
{
grid[i] = new bool[maxX];
}
foreach (var coord in numbers)
{
grid[coord[1]][coord[0]] = true;
}
var part2 = new StringBuilder(maxY * maxX + maxY + 1);
part2.Append('\n');
for (int y = 0; y < maxY; y++)
{
for (int x = 0; x < maxX; x++)
{
part2.Append(grid[y][x] ? '#' : ' ');
}
part2.Append('\n');
}
return (part1.ToString(), part2.ToString());
}
}
| unlicense | C# |
9989b36029d609abc8cc29653c06f5223936b8fa | Remove extra blank lines | mattherman/MbDotNet,mattherman/MbDotNet,SuperDrew/MbDotNet | MbDotNet/Models/Imposters/RetrievedImposter.cs | MbDotNet/Models/Imposters/RetrievedImposter.cs | using Newtonsoft.Json;
namespace MbDotNet.Models.Imposters
{
public class RetrievedImposter
{
/// <summary>
/// The port the imposter is set up to accept requests on.
/// </summary>
[JsonProperty("port")]
public int Port { get; private set; }
/// <summary>
/// The protocol the imposter is set up to accept requests through.
/// </summary>
[JsonProperty("protocol")]
public string Protocol { get; private set; }
/// <summary>
/// Optional name for the imposter, used in the logs.
/// </summary>
[JsonProperty("name")]
public string Name { get; private set; }
[JsonProperty("numberOfRequests")]
public int NumberOfRequests { get; private set; }
[JsonProperty("requests")]
public Request[] Requests { get; private set; }
}
} | using Newtonsoft.Json;
namespace MbDotNet.Models.Imposters
{
public class RetrievedImposter
{
/// <summary>
/// The port the imposter is set up to accept requests on.
/// </summary>
[JsonProperty("port")]
public int Port { get; private set; }
/// <summary>
/// The protocol the imposter is set up to accept requests through.
/// </summary>
[JsonProperty("protocol")]
public string Protocol { get; private set; }
/// <summary>
/// Optional name for the imposter, used in the logs.
/// </summary>
[JsonProperty("name")]
public string Name { get; private set; }
[JsonProperty("numberOfRequests")]
public int NumberOfRequests { get; private set; }
[JsonProperty("requests")]
public Request[] Requests { get; private set; }
}
} | mit | C# |
a02b3fe01536ecb8584e7ce3fc1a7fcf74f80d49 | refactor of InventoryCollection for good measure | BogusCurry/arribasim-dev,justinccdev/opensim,intari/OpenSimMirror,zekizeki/agentservice,rryk/omp-server,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,N3X15/VoxelSim,allquixotic/opensim-autobackup,ft-/arribasim-dev-tests,ft-/arribasim-dev-extras,RavenB/opensim,QuillLittlefeather/opensim-1,bravelittlescientist/opensim-performance,rryk/omp-server,AlphaStaxLLC/taiga,AlphaStaxLLC/taiga,allquixotic/opensim-autobackup,Michelle-Argus/ArribasimExtract,bravelittlescientist/opensim-performance,rryk/omp-server,ft-/opensim-optimizations-wip,TechplexEngineer/Aurora-Sim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,zekizeki/agentservice,RavenB/opensim,cdbean/CySim,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,ft-/arribasim-dev-tests,AlexRa/opensim-mods-Alex,AlexRa/opensim-mods-Alex,justinccdev/opensim,TomDataworks/opensim,OpenSimian/opensimulator,cdbean/CySim,zekizeki/agentservice,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip,TomDataworks/opensim,intari/OpenSimMirror,AlexRa/opensim-mods-Alex,rryk/omp-server,ft-/opensim-optimizations-wip-tests,zekizeki/agentservice,M-O-S-E-S/opensim,bravelittlescientist/opensim-performance,N3X15/VoxelSim,M-O-S-E-S/opensim,allquixotic/opensim-autobackup,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip,AlexRa/opensim-mods-Alex,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-tests,RavenB/opensim,Michelle-Argus/ArribasimExtract,cdbean/CySim,allquixotic/opensim-autobackup,allquixotic/opensim-autobackup,rryk/omp-server,RavenB/opensim,bravelittlescientist/opensim-performance,N3X15/VoxelSim,zekizeki/agentservice,AlphaStaxLLC/taiga,OpenSimian/opensimulator,cdbean/CySim,ft-/arribasim-dev-tests,Michelle-Argus/ArribasimExtract,justinccdev/opensim,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,AlphaStaxLLC/taiga,N3X15/VoxelSim,justinccdev/opensim,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,N3X15/VoxelSim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,AlphaStaxLLC/taiga,AlphaStaxLLC/taiga,N3X15/VoxelSim,Michelle-Argus/ArribasimExtract,AlphaStaxLLC/taiga,justinccdev/opensim,TechplexEngineer/Aurora-Sim,ft-/opensim-optimizations-wip-tests,bravelittlescientist/opensim-performance,TechplexEngineer/Aurora-Sim,intari/OpenSimMirror,N3X15/VoxelSim,M-O-S-E-S/opensim,rryk/omp-server,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,RavenB/opensim,Michelle-Argus/ArribasimExtract,RavenB/opensim,OpenSimian/opensimulator,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,AlexRa/opensim-mods-Alex,cdbean/CySim,bravelittlescientist/opensim-performance,QuillLittlefeather/opensim-1,justinccdev/opensim,AlexRa/opensim-mods-Alex,BogusCurry/arribasim-dev,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip,ft-/arribasim-dev-extras,TomDataworks/opensim,intari/OpenSimMirror,TechplexEngineer/Aurora-Sim,OpenSimian/opensimulator,ft-/arribasim-dev-tests,TomDataworks/opensim,BogusCurry/arribasim-dev,QuillLittlefeather/opensim-1,RavenB/opensim,ft-/arribasim-dev-tests,AlphaStaxLLC/taiga,intari/OpenSimMirror,cdbean/CySim,intari/OpenSimMirror,zekizeki/agentservice,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,OpenSimian/opensimulator | OpenSim/Framework/InventoryCollection.cs | OpenSim/Framework/InventoryCollection.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 OpenSim 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 System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using libsecondlife;
namespace OpenSim.Framework
{
public class InventoryCollection
{
public List<InventoryFolderBase> _folders;
public List<InventoryItemBase> _allItems;
public LLUUID _userID;
public List<InventoryFolderBase> Folders {
get {
return _folders;
}
set {
_folders = value;
}
}
public List<InventoryItemBase> AllItems {
get {
return _allItems;
}
set {
_allItems = value;
}
}
public LLUUID UserID {
get {
return _userID;
}
set {
_userID = value;
}
}
public InventoryCollection()
{
_folders = new List<InventoryFolderBase>();
_allItems = new List<InventoryItemBase>();
}
public InventoryCollection(List<InventoryFolderBase> folders, List<InventoryItemBase> allItems)
{
_folders = folders;
_allItems = allItems;
}
}
}
| /*
* 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 OpenSim 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 System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using libsecondlife;
namespace OpenSim.Framework
{
public class InventoryCollection
{
public List<InventoryFolderBase> Folders;
public List<InventoryItemBase> AllItems;
public LLUUID UserID;
public InventoryCollection()
{
Folders = new List<InventoryFolderBase>();
AllItems = new List<InventoryItemBase>();
}
public InventoryCollection(List<InventoryFolderBase> folders, List<InventoryItemBase> allItems)
{
Folders = folders;
AllItems = allItems;
}
}
}
| bsd-3-clause | C# |
9d3acaa5843ee0f71a3d70314f944ee36235b2c0 | Add drink alone action | Guityyo/minerparty,Guityyo/minerparty | Assets/AI/Actions/drinkAlone.cs | Assets/AI/Actions/drinkAlone.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using RAIN.Action;
using RAIN.Core;
[RAINAction]
public class drinkAlone : RAINAction
{
private Thief thief;
public override void Start(RAIN.Core.AI ai){
base.Start(ai);
thief = GameObject.Find("Thief").GetComponent<Thief>();
}
public override ActionResult Execute(RAIN.Core.AI ai){
thief.drinkBeer();
Debug.Log ("THIEF: Mmmm this beer is sooo tasty");
return ActionResult.SUCCESS;
}
public override void Stop(RAIN.Core.AI ai){
base.Stop(ai);
}
} | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using RAIN.Action;
using RAIN.Core;
[RAINAction]
public class drinkAlone : RAINAction
{
private Thief thief;
public override void Start(RAIN.Core.AI ai){
base.Start(ai);
thief = GameObject.Find("Thief").GetComponent<Thief>();
}
public override ActionResult Execute(RAIN.Core.AI ai){
thief.drinkBeer();
return ActionResult.SUCCESS;
}
public override void Stop(RAIN.Core.AI ai){
base.Stop(ai);
}
} | apache-2.0 | C# |
0f2407277defdffe39231647ba54a61279816593 | disable app-insights in debug builds | akatakritos/Landmine.Web,JakeLunn/Landmine.Web,JakeLunn/Landmine.Web,JakeLunn/Landmine.Web,akatakritos/Landmine.Web,akatakritos/Landmine.Web,akatakritos/Landmine.Web,JakeLunn/Landmine.Web | LandmineWeb/Global.asax.cs | LandmineWeb/Global.asax.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Landmine.Domain.Concrete;
using Microsoft.ApplicationInsights.Extensibility;
namespace LandmineWeb
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
#if DEBUG
System.Web.Optimization.BundleTable.EnableOptimizations = false;
TelemetryConfiguration.Active.DisableTelemetry = true;
#endif
AutofacConfig.Register();
}
}
public static class AutofacConfig
{
public static void Register()
{
var builder = new ContainerBuilder();
RegisterServices(builder);
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
// OPTIONAL: Register model binders that require DI.
//builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
//builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
//builder.RegisterModule<AutofacWebTypesModule>();
// OPTIONAL: Enable property injection in view pages.
//builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
//builder.RegisterFilterProvider();
// Set the dependency resolver to be Autofac.
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
private static void RegisterServices(ContainerBuilder builder)
{
builder.RegisterType<ScoreRepository>().AsImplementedInterfaces();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using Landmine.Domain.Concrete;
namespace LandmineWeb
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
#if DEBUG
System.Web.Optimization.BundleTable.EnableOptimizations = false;
#endif
AutofacConfig.Register();
}
}
public static class AutofacConfig
{
public static void Register()
{
var builder = new ContainerBuilder();
RegisterServices(builder);
// Register your MVC controllers.
builder.RegisterControllers(typeof(MvcApplication).Assembly);
builder.RegisterApiControllers(typeof(MvcApplication).Assembly);
// OPTIONAL: Register model binders that require DI.
//builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
//builder.RegisterModelBinderProvider();
// OPTIONAL: Register web abstractions like HttpContextBase.
//builder.RegisterModule<AutofacWebTypesModule>();
// OPTIONAL: Enable property injection in view pages.
//builder.RegisterSource(new ViewRegistrationSource());
// OPTIONAL: Enable property injection into action filters.
//builder.RegisterFilterProvider();
// Set the dependency resolver to be Autofac.
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
private static void RegisterServices(ContainerBuilder builder)
{
builder.RegisterType<ScoreRepository>().AsImplementedInterfaces();
}
}
} | mit | C# |
0b0f586375853c46ce44a19c457761a17f0cde0d | Fix the paths for a few libraries | PlayScriptRedux/monomac,dlech/monomac,kangaroo/monomac | src/Constants.cs | src/Constants.cs | //
// Copyright 2010, Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoMac {
public static partial class Constants {
public const string AppKitLibrary = "/System/Library/Frameworks/AppKit.framework/AppKit";
public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
public const string CoreGraphicsLibrary = "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/CoreGraphics";
public const string CoreTextLibrary = "/System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreText.framework/CoreText";
public const string FoundationLibrary = "/System/Library/Frameworks/Foundation.framework/Foundation";
public const string ObjectiveCLibrary = "/usr/lib/libobjc.dylib";
public const string SystemLibrary = "/usr/lib/libSystem.dylib";
public const string QuartzLibrary = "/System/Library/Frameworks/QuartzCore.framework/QuartzCore";
public const string AudioToolboxLibrary = "/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox";
public const string WebKitLibrary = "/System/Library/Frameworks/WebKit.framework/WebKit";
public const string AudioUnitLibrary = "/System/Library/Frameworks/AudioUnit.framework/AudioUnit";
public const string CoreAudioLibrary = "/System/Library/Frameworks/CoreAudio.framework/CoreAudio";
public const string CoreAnimationLibrary = "/System/Library/Frameworks/QuartzCore.framework/QuartzCore";
public const string ImageIOLibrary = "/System/Library/Frameworks/ApplicationServices.framework/Frameworks/ImageIO.framework/ImageIO";
}
}
| //
// Copyright 2010, Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoMac {
public static partial class Constants {
public const string AppKitLibrary = "/System/Library/Frameworks/AppKit.framework/AppKit";
public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
public const string CoreGraphicsLibrary = "/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/CoreGraphics";
public const string CoreTextLibrary = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices";
public const string FoundationLibrary = "/System/Library/Frameworks/Foundation.framework/Foundation";
public const string ObjectiveCLibrary = "/usr/lib/libobjc.dylib";
public const string SystemLibrary = "/usr/lib/libSystem.dylib";
public const string QuartzLibrary = "/System/Library/Frameworks/QuartzCore.framework/QuartzCore";
public const string AudioToolboxLibrary = "/System/Library/Frameworks/AudioToolbox.framework/AudioToolbox";
public const string WebKitLibrary = "/System/Library/Frameworks/WebKit.framework/WebKit";
public const string AudioUnitLibrary = "/System/Library/Frameworks/AudioUnit.framework/AudioUnit";
public const string CoreAudioLibrary = "/System/Library/Frameworks/CoreAudio.framework/CoreAudio";
public const string CoreAnimationLibrary = "/System/Library/Frameworks/QuartzCore.framework/QuartzCore";
}
}
| apache-2.0 | C# |
5db523cf0873b4e6d8020e4784be9b30a4c2111e | Read pages and break them down into streams If file stream was not owned by us, rewind it after reading | paszczi/MLabs.Ogg | Mlabs.Ogg/src/OggReader.cs | Mlabs.Ogg/src/OggReader.cs | using System;
using System.IO;
using System.Linq;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IOggInfo Read()
{
long originalOffset = m_fileStream.Position;
var p = new PageReader();
//read pages and break them down to streams
var pages = p.ReadPages(m_fileStream).GroupBy(e => e.StreamSerialNumber);
if (m_owns)
{
m_fileStream.Dispose();
}
else
{
//if we didn't create stream rewind it, so that user won't get any surprise :)
m_fileStream.Seek(originalOffset, SeekOrigin.Begin);
}
return null;
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Mlabs.Ogg.Metadata;
namespace Mlabs.Ogg
{
public class OggReader
{
private readonly Stream m_fileStream;
private readonly bool m_owns;
public OggReader(string fileName)
{
if (fileName == null) throw new ArgumentNullException("fileName");
m_fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
m_owns = true;
}
public OggReader(Stream fileStream)
{
if (fileStream == null) throw new ArgumentNullException("fileStream");
m_fileStream = fileStream;
m_owns = false;
}
public IStreamInfo Read()
{
var p = new PageReader();
var pages = p.ReadPages(m_fileStream).ToList();
if (m_owns)
m_fileStream.Dispose();
return null;
}
}
} | mit | C# |
156745ba000432a4c6954fe2c91b55f723d079d3 | Add method for NyaaBang descriptions | IvionSauce/MeidoBot | NyaaSpam/BangShorthands.cs | NyaaSpam/BangShorthands.cs | using System;
using System.Collections.Generic;
static class BangShorthands
{
static readonly Dictionary<string, string[]> bangs;
const char prefix = '!';
static BangShorthands()
{
var shortHand = new string[] {
"HS",
"HS480",
"HS720",
"HS1080"
};
var expanded = new string[] {
"[HorribleSubs]",
"[HorribleSubs] [480p]",
"[HorribleSubs] [720p]",
"[HorribleSubs] [1080p]"
};
bangs = new Dictionary<string, string[]>(
shortHand.Length,
StringComparer.Ordinal
);
for (int i = 0; i < shortHand.Length && i < expanded.Length; i++)
{
string key = prefix + shortHand[i];
bangs[key] = expanded[i].Split(' ');
}
}
public static IEnumerable<string> ExpandPattern(string[] pattern)
{
foreach (string patternPart in pattern)
{
string[] expandedBang;
// If the word (pattern part) is a bang shorthand expand it and return each constituent.
if (Shorthand(patternPart, out expandedBang))
{
foreach (string bangPart in expandedBang)
yield return bangPart;
}
// Otherwise just return the word as is.
else
yield return patternPart;
}
}
static bool Shorthand(string part, out string[] expanded)
{
expanded = null;
return part.Length > 0 &&
part[0] == prefix &&
bangs.TryGetValue(part, out expanded);
}
public static string[] GetDescriptions()
{
// Get and sort keys.
var sortedKeys = new string[bangs.Count];
bangs.Keys.CopyTo(sortedKeys, 0);
Array.Sort(sortedKeys);
// Use sorted keys to create a sorted list of descriptions.
var sortedDescs = new string[sortedKeys.Length];
for (int i = 0; i < sortedKeys.Length; i++)
{
var key = sortedKeys[i];
sortedDescs[i] = string.Format("{0} -> {1}", key, bangs[key]);
}
return sortedDescs;
}
} | using System;
using System.Collections.Generic;
static class BangShorthands
{
static readonly Dictionary<string, string[]> bangs;
const char prefix = '!';
static BangShorthands()
{
var shortHand = new string[] {
"HS",
"HS480",
"HS720",
"HS1080"
};
var expanded = new string[] {
"[HorribleSubs]",
"[HorribleSubs] [480p]",
"[HorribleSubs] [720p]",
"[HorribleSubs] [1080p]"
};
bangs = new Dictionary<string, string[]>(
shortHand.Length,
StringComparer.Ordinal
);
for (int i = 0; i < shortHand.Length && i < expanded.Length; i++)
{
string key = prefix + shortHand[i];
bangs[key] = expanded[i].Split(' ');
}
}
public static IEnumerable<string> ExpandPattern(string[] pattern)
{
foreach (string patternPart in pattern)
{
string[] expandedBang;
// If the word (pattern part) is a bang shorthand expand it and return each constituent.
if (Shorthand(patternPart, out expandedBang))
{
foreach (string bangPart in expandedBang)
yield return bangPart;
}
// Otherwise just return the word as is.
else
yield return patternPart;
}
}
static bool Shorthand(string part, out string[] expanded)
{
expanded = null;
return part.Length > 0 &&
part[0] == prefix &&
bangs.TryGetValue(part, out expanded);
}
} | bsd-2-clause | C# |
2af3d87c45a7eb6f4c2a8ac8d9542a357aa7b8b0 | Bump version | nixxquality/WebMConverter,o11c/WebMConverter,Yuisbean/WebMConverter | Properties/AssemblyInfo.cs | 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// 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.10.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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// 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.9.0")]
| mit | C# |
7f126578476e3e07b9cb30d78f7cc31dc0bff767 | Update version | transistor1/SQLFormatterPlugin | Properties/AssemblyInfo.cs | 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("SQLFormatterPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQLFormatterPlugin")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("22247641-9910-4c24-9a9d-dd295a749d41")]
// 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.9999.0")]
[assembly: AssemblyFileVersion("1.0.9999.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("SQLFormatterPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SQLFormatterPlugin")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("22247641-9910-4c24-9a9d-dd295a749d41")]
// 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.9998.0")]
[assembly: AssemblyFileVersion("1.0.9998.0")]
| bsd-3-clause | C# |
a85b7579f4d895e0df7720bbe20bd74e1450378b | Use managed sha256 explicitly | detunized/lastpass-sharp,rottenorange/lastpass-sharp,detunized/lastpass-sharp | src/FetcherHelper.cs | src/FetcherHelper.cs | using System;
using System.Security.Cryptography;
using System.Text;
namespace LastPass
{
static class FetcherHelper
{
public static byte[] MakeKey(string username, string password, int iterationCount)
{
// TODO: Check for invalid interationCount
if (iterationCount == 1)
{
using (var sha = new SHA256Managed())
{
return sha.ComputeHash(Encoding.UTF8.GetBytes(username + password));
}
}
using (var hmac = new HMACSHA256())
{
return new Pbkdf2(hmac, password, username, iterationCount).GetBytes(32);
}
}
public static string MakeHash(string username, string password, int iterationCount)
{
// TODO: Check for invalid interationCount
var key = MakeKey(username, password, iterationCount);
if (iterationCount == 1)
{
using (var sha = new SHA256Managed())
{
return ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(ToHexString(key) + password)));
}
}
using (var hmac = new HMACSHA256())
{
return ToHexString(new Pbkdf2(hmac, key, password, 1).GetBytes(32));
}
}
public static string ToHexString(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower();
}
}
}
| using System;
using System.Security.Cryptography;
using System.Text;
namespace LastPass
{
static class FetcherHelper
{
public static byte[] MakeKey(string username, string password, int iterationCount)
{
// TODO: Check for invalid interationCount
if (iterationCount == 1)
{
using (var sha = SHA256.Create())
{
return sha.ComputeHash(Encoding.UTF8.GetBytes(username + password));
}
}
using (var hmac = new HMACSHA256())
{
return new Pbkdf2(hmac, password, username, iterationCount).GetBytes(32);
}
}
public static string MakeHash(string username, string password, int iterationCount)
{
// TODO: Check for invalid interationCount
var key = MakeKey(username, password, iterationCount);
if (iterationCount == 1)
{
using (var sha = SHA256.Create())
{
return ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(ToHexString(key) + password)));
}
}
using (var hmac = new HMACSHA256())
{
return ToHexString(new Pbkdf2(hmac, key, password, 1).GetBytes(32));
}
}
public static string ToHexString(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", string.Empty).ToLower();
}
}
}
| mit | C# |
e9c334561de186134a704dd06919d1ac0ff7b02b | add new CurrentSession DokanOptions | dokan-dev/dokan-dotnet,magol/dokan-dotnet,dokan-dev/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,magol/dokan-dotnet,viciousviper/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,dokan-dev/dokan-dotnet,viciousviper/dokan-dotnet,magol/dokan-dotnet,viciousviper/dokan-dotnet | DokanNet/DokanOptions.cs | DokanNet/DokanOptions.cs | using System;
namespace DokanNet
{
[Flags]
public enum DokanOptions : long
{
DebugMode = 1, // ouput debug message
StderrOutput = 2, // ouput debug message to stderr
AltStream = 4, // use alternate stream
WriteProtection = 8, // mount drive as write-protected.
NetworkDrive = 16, // use network drive, you need to install Dokan network provider.
RemovableDrive = 32, // use removable drive
MountManager = 64, // use mount manager
CurrentSession = 128, // mount the drive on current session only
FixedDrive = 0,
}
}
| using System;
namespace DokanNet
{
[Flags]
public enum DokanOptions : long
{
DebugMode = 1, // ouput debug message
StderrOutput = 2, // ouput debug message to stderr
AltStream = 4, // use alternate stream
WriteProtection = 8, // mount drive as write-protected.
NetworkDrive = 16, // use network drive, you need to install Dokan network provider.
RemovableDrive = 32, // use removable drive
MountManager = 64, // use mount manager
FixedDrive = 0,
}
} | mit | C# |
9bc6e9673bb9dfd711aac98d61d7c1c346c09e54 | Fix PingPong Test | p-org/PSharp | Samples/PSharpFramework/PingPong/Test.cs | Samples/PSharpFramework/PingPong/Test.cs | using System;
using System.Collections.Generic;
using Microsoft.PSharp;
namespace PingPong
{
public class Test
{
static void Main(string[] args)
{
Test.Execute();
Console.ReadLine();
}
[Microsoft.PSharp.Test]
public static void Execute()
{
PSharpRuntime.CreateMachine(typeof(Server));
}
}
}
| using System;
using Microsoft.PSharp;
namespace SystematicTesting
{
class Config : Event
{
public MachineId Id;
public Config(MachineId id) : base(-1, -1) { this.Id = id; }
}
class E1 : Event
{
public E1() : base(1, -1) { }
}
class E2 : Event
{
public int Value;
public E2(int value) : base(1, -1) { this.Value = value; }
}
class E3 : Event
{
public E3() : base(-1, -1) { }
}
class E4 : Event { }
class Unit : Event
{
public Unit() : base(1, -1) { }
}
class RealMachine : Machine
{
MachineId GhostMachine;
[Start]
[OnEntry(nameof(EntryInit))]
[OnEventPushState(typeof(Unit), typeof(S1))]
[OnEventGotoState(typeof(E4), typeof(S2))]
[OnEventDoAction(typeof(E2), nameof(Action1))]
class Init : MachineState { }
void EntryInit()
{
GhostMachine = this.CreateMachine(typeof(GhostMachine));
this.Send(GhostMachine, new Config(this.Id));
this.Raise(new Unit());
}
[OnEntry(nameof(EntryS1))]
class S1 : MachineState { }
void EntryS1()
{
this.Send(GhostMachine, new E1());
this.Send(GhostMachine, new E1()); // error
}
[OnEntry(nameof(EntryS2))]
[OnEventGotoState(typeof(Unit), typeof(S3))]
class S2 : MachineState { }
void EntryS2()
{
this.Raise(new Unit());
}
[OnEventGotoState(typeof(E4), typeof(S3))]
class S3 : MachineState { }
void Action1()
{
this.Assert((this.ReceivedEvent as E2).Value == 100);
this.Send(GhostMachine, new E3());
this.Send(GhostMachine, new E3());
}
}
class GhostMachine : Machine
{
MachineId RealMachine;
[Start]
[OnEventDoAction(typeof(Config), nameof(Configure))]
[OnEventGotoState(typeof(Unit), typeof(GhostInit))]
class Init : MachineState { }
void Configure()
{
RealMachine = (this.ReceivedEvent as Config).Id;
this.Raise(new Unit());
}
[OnEventGotoState(typeof(E1), typeof(S1))]
class GhostInit : MachineState { }
[OnEntry(nameof(EntryS1))]
[OnEventGotoState(typeof(E3), typeof(S2))]
[IgnoreEvents(typeof(E1))]
class S1 : MachineState { }
void EntryS1()
{
this.Send(RealMachine, new E2(100));
}
[OnEntry(nameof(EntryS2))]
[OnEventGotoState(typeof(E3), typeof(GhostInit))]
class S2 : MachineState { }
void EntryS2()
{
this.Send(RealMachine, new E4());
this.Send(RealMachine, new E4());
this.Send(RealMachine, new E4());
}
}
public static class TestProgram
{
public static void Main(string[] args)
{
TestProgram.Execute();
Console.ReadLine();
}
[Test]
public static void Execute()
{
PSharpRuntime.CreateMachine(typeof(RealMachine));
}
}
} | mit | C# |
d5385b113c7a698efbd1404003132947aafafdf6 | Scale TextOutline with Camera's OrthographicSize | NitorInc/NitoriWare,Barleytree/NitoriWare,uulltt/NitoriWare,plrusek/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare | Assets/Scripts/UI/TextOutline.cs | Assets/Scripts/UI/TextOutline.cs | //Found this online
using UnityEngine;
using System.Collections;
public class TextOutline : MonoBehaviour
{
public float pixelSize = 1;
public int cloneCount = 8;
public Color outlineColor = Color.black;
public bool resolutionDependant = false;
public int doubleResolution = 1024;
private TextMesh textMesh;
private MeshRenderer meshRenderer;
void Start()
{
textMesh = GetComponent<TextMesh>();
meshRenderer = GetComponent<MeshRenderer>();
for (int i = 0; i < cloneCount; i++)
{
GameObject outline = new GameObject("outline", typeof(TextMesh));
outline.transform.parent = transform;
outline.transform.localScale = new Vector3(1, 1, 1);
MeshRenderer otherMeshRenderer = outline.GetComponent<MeshRenderer>();
otherMeshRenderer.material = new Material(meshRenderer.material);
otherMeshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
otherMeshRenderer.receiveShadows = false;
otherMeshRenderer.sortingLayerID = meshRenderer.sortingLayerID;
otherMeshRenderer.sortingLayerName = meshRenderer.sortingLayerName;
otherMeshRenderer.sortingOrder = meshRenderer.sortingOrder;
}
}
void LateUpdate()
{
Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
outlineColor.a = textMesh.color.a * textMesh.color.a;
// copy attributes
for (int i = 0; i < transform.childCount; i++)
{
TextMesh other = transform.GetChild(i).GetComponent<TextMesh>();
other.color = outlineColor;
other.text = textMesh.text;
other.alignment = textMesh.alignment;
other.anchor = textMesh.anchor;
other.characterSize = textMesh.characterSize;
other.font = textMesh.font;
other.fontSize = textMesh.fontSize;
other.fontStyle = textMesh.fontStyle;
other.richText = textMesh.richText;
other.tabSize = textMesh.tabSize;
other.lineSpacing = textMesh.lineSpacing;
other.offsetZ = textMesh.offsetZ;
other.gameObject.layer = gameObject.layer;
bool doublePixel = resolutionDependant && (Screen.width > doubleResolution || Screen.height > doubleResolution);
Vector3 pixelOffset = GetOffset(i) * (doublePixel ? 2.0f * getFunctionalPixelSize() : getFunctionalPixelSize());
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint + pixelOffset);
other.transform.position = worldPoint + new Vector3(0f, 0f, .001f);
MeshRenderer otherMeshRenderer = transform.GetChild(i).GetComponent<MeshRenderer>();
otherMeshRenderer.sortingLayerID = meshRenderer.sortingLayerID;
otherMeshRenderer.sortingLayerName = meshRenderer.sortingLayerName;
}
}
float getFunctionalPixelSize()
{
return pixelSize * 5f / Camera.main.orthographicSize;
}
Vector3 GetOffset(int i)
{
return (Vector3)MathHelper.getVectorFromAngle2D(360f * ((float)i / (float)cloneCount), 1f);
}
} | //Found this online
using UnityEngine;
using System.Collections;
public class TextOutline : MonoBehaviour
{
public float pixelSize = 1;
public int cloneCount = 8;
public Color outlineColor = Color.black;
public bool resolutionDependant = false;
public int doubleResolution = 1024;
private TextMesh textMesh;
private MeshRenderer meshRenderer;
void Start()
{
textMesh = GetComponent<TextMesh>();
meshRenderer = GetComponent<MeshRenderer>();
for (int i = 0; i < cloneCount; i++)
{
GameObject outline = new GameObject("outline", typeof(TextMesh));
outline.transform.parent = transform;
outline.transform.localScale = new Vector3(1, 1, 1);
MeshRenderer otherMeshRenderer = outline.GetComponent<MeshRenderer>();
otherMeshRenderer.material = new Material(meshRenderer.material);
otherMeshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
otherMeshRenderer.receiveShadows = false;
otherMeshRenderer.sortingLayerID = meshRenderer.sortingLayerID;
otherMeshRenderer.sortingLayerName = meshRenderer.sortingLayerName;
otherMeshRenderer.sortingOrder = meshRenderer.sortingOrder;
}
}
void LateUpdate()
{
Vector3 screenPoint = Camera.main.WorldToScreenPoint(transform.position);
outlineColor.a = textMesh.color.a * textMesh.color.a;
// copy attributes
for (int i = 0; i < transform.childCount; i++)
{
TextMesh other = transform.GetChild(i).GetComponent<TextMesh>();
other.color = outlineColor;
other.text = textMesh.text;
other.alignment = textMesh.alignment;
other.anchor = textMesh.anchor;
other.characterSize = textMesh.characterSize;
other.font = textMesh.font;
other.fontSize = textMesh.fontSize;
other.fontStyle = textMesh.fontStyle;
other.richText = textMesh.richText;
other.tabSize = textMesh.tabSize;
other.lineSpacing = textMesh.lineSpacing;
other.offsetZ = textMesh.offsetZ;
other.gameObject.layer = gameObject.layer;
bool doublePixel = resolutionDependant && (Screen.width > doubleResolution || Screen.height > doubleResolution);
Vector3 pixelOffset = GetOffset(i) * (doublePixel ? 2.0f * pixelSize : pixelSize);
Vector3 worldPoint = Camera.main.ScreenToWorldPoint(screenPoint + pixelOffset);
other.transform.position = worldPoint + new Vector3(0f, 0f, .001f);
MeshRenderer otherMeshRenderer = transform.GetChild(i).GetComponent<MeshRenderer>();
otherMeshRenderer.sortingLayerID = meshRenderer.sortingLayerID;
otherMeshRenderer.sortingLayerName = meshRenderer.sortingLayerName;
}
}
Vector3 GetOffset(int i)
{
return (Vector3)MathHelper.getVectorFromAngle2D(360f * ((float)i / (float)cloneCount), 1f);
}
} | mit | C# |
d841565f8f71fbe1ba0a5dc0eafc04c72e18841e | Bump version | roman-yagodin/R7.News,roman-yagodin/R7.News,roman-yagodin/R7.News | R7.News/Properties/SolutionInfo.cs | R7.News/Properties/SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany ("R7.Labs")]
[assembly: AssemblyProduct ("R7.News")]
[assembly: AssemblyCopyright ("Roman M. Yagodin")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyVersion ("1.8.0")]
[assembly: AssemblyInformationalVersion ("1.8.0-beta.1")]
| using System.Reflection;
[assembly: AssemblyCompany ("R7.Labs")]
[assembly: AssemblyProduct ("R7.News")]
[assembly: AssemblyCopyright ("Roman M. Yagodin")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyVersion ("1.8.0")]
[assembly: AssemblyInformationalVersion ("1.8.0")]
| agpl-3.0 | C# |
078d25397279404c98416148ddc9d909fa03c807 | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.RunMRU/ValuesOut.cs | RegistryPlugin.RunMRU/ValuesOut.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.RunMRU
{
public class ValuesOut:IValueOut
{
public ValuesOut(string valueName, string executable, int mruPosition, DateTimeOffset? openedOn)
{
Executable = executable;
ValueName = valueName;
MruPosition = mruPosition;
OpenedOn = openedOn?.UtcDateTime;
}
public string ValueName { get; }
public int MruPosition { get; }
public string Executable { get; }
public DateTime? OpenedOn { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Executable: {Executable}";
public string BatchValueData2 => $"Opened on: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 => $"MRU: {MruPosition}";
}
} | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.RunMRU
{
public class ValuesOut:IValueOut
{
public ValuesOut(string valueName, string executable, int mruPosition, DateTimeOffset? openedOn)
{
Executable = executable;
ValueName = valueName;
MruPosition = mruPosition;
OpenedOn = openedOn?.UtcDateTime;
}
public string ValueName { get; }
public int MruPosition { get; }
public string Executable { get; }
public DateTime? OpenedOn { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"Executable: {Executable}";
public string BatchValueData2 => $"Opened on: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 => $"MRU: {MruPosition}";
}
} | mit | C# |
bfe0db15580395d485ee8bfc005281a82bda7081 | add extension method | isukces/isukces.code | isukces.code/interfaces/ITypeNameResolver.cs | isukces.code/interfaces/ITypeNameResolver.cs | using System;
namespace isukces.code.interfaces
{
public interface ITypeNameResolver
{
string GetTypeName(Type type);
}
public static class TypeToNameResolverExtensions
{
public static string GetMemeberName(this ITypeNameResolver resolver, Type type, string instanceName)
{
return resolver.GetTypeName(type) + "." + instanceName;
}
public static string GetMemeberName<T>(this ITypeNameResolver resolver, string instanceName)
{
return resolver.GetTypeName<T>() + "." + instanceName;
}
public static string GetTypeName<T>(this ITypeNameResolver resolver)
{
return resolver.GetTypeName(typeof(T));
}
[Obsolete("Use GetTypeName")]
public static string TypeName(this ITypeNameResolver resolver, Type type)
{
return resolver.GetTypeName(type);
}
public static string GetEnumValueCode<T>(this ITypeNameResolver resolver, T value)
where T : Enum
{
var c = resolver.GetTypeName<T>();
var value2 = c + "." + value;
return value2;
}
}
} | using System;
namespace isukces.code.interfaces
{
public interface ITypeNameResolver
{
string GetTypeName(Type type);
}
public static class TypeToNameResolverExtensions
{
public static string GetMemeberName(this ITypeNameResolver resolver, Type type, string instanceName)
{
return resolver.GetTypeName(type) + "." + instanceName;
}
public static string GetMemeberName<T>(this ITypeNameResolver resolver, string instanceName)
{
return resolver.GetTypeName<T>() + "." + instanceName;
}
public static string GetTypeName<T>(this ITypeNameResolver resolver)
{
return resolver.GetTypeName(typeof(T));
}
[Obsolete("Use GetTypeName")]
public static string TypeName(this ITypeNameResolver resolver, Type type)
{
return resolver.GetTypeName(type);
}
}
} | mit | C# |
e29937efcfc935807379de8a6363869597f60f07 | Fix Track test to use valid tracking number | goshippo/shippo-csharp-client | ShippoTesting/TrackTest.cs | ShippoTesting/TrackTest.cs | using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Shippo;
namespace ShippoTesting
{
[TestFixture ()]
public class TrackTest : ShippoTest
{
private const String TRACKING_NO = "9205590164917337534322";
private const String CARRIER = "usps";
[Test ()]
public void TestValidGetStatus ()
{
Track track = getAPIResource ().RetrieveTracking (CARRIER, TRACKING_NO);
Assert.AreEqual (TRACKING_NO, track.TrackingNumber.ToString());
Assert.IsNotNull (track.TrackingStatus);
Assert.IsNotNull (track.TrackingHistory);
}
[Test ()]
[ExpectedException (typeof (ShippoException))]
public void TestInvalidGetStatus ()
{
getAPIResource ().RetrieveTracking (CARRIER, "INVALID_ID");
}
[Test ()]
public void TestValidRegisterWebhook ()
{
Shipment shipment = ShipmentTest.getDefaultObject ();
Track track = getAPIResource ().RetrieveTracking (CARRIER, shipment.ObjectId);
Assert.IsNotNull (track.TrackingNumber);
Assert.IsNotNull (track.TrackingHistory);
Hashtable parameters = new Hashtable ();
parameters.Add ("carrier", CARRIER);
parameters.Add ("tracking_number", track.TrackingNumber);
Track register = getAPIResource ().RegisterTrackingWebhook (parameters);
Assert.IsNotNull (register.TrackingNumber);
Assert.IsNotNull (register.TrackingHistory);
}
[Test ()]
[ExpectedException (typeof (ShippoException))]
public void TestInvalidRegisterWebhook ()
{
Hashtable parameters = new Hashtable ();
parameters.Add ("carrier", CARRIER);
parameters.Add ("tracking_number", "INVALID_ID");
getAPIResource ().RegisterTrackingWebhook (parameters);
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Shippo;
namespace ShippoTesting
{
[TestFixture ()]
public class TrackTest : ShippoTest
{
[Test ()]
public void TestValidGetStatus ()
{
Shipment shipment = ShipmentTest.getDefaultObject ();
Track track = getAPIResource ().RetrieveTracking ("usps", shipment.ObjectId);
Assert.IsNotNull (track.TrackingNumber);
Assert.IsNotNull (track.TrackingHistory);
}
[Test ()]
[ExpectedException (typeof (ShippoException))]
public void TestInvalidGetStatus ()
{
getAPIResource ().RetrieveTracking ("usps", "INVALID_ID");
}
[Test ()]
public void TestValidRegisterWebhook ()
{
Shipment shipment = ShipmentTest.getDefaultObject ();
Track track = getAPIResource ().RetrieveTracking ("usps", shipment.ObjectId);
Assert.IsNotNull (track.TrackingNumber);
Assert.IsNotNull (track.TrackingHistory);
Hashtable parameters = new Hashtable ();
parameters.Add ("carrier", "usps");
parameters.Add ("tracking_number", track.TrackingNumber);
Track register = getAPIResource ().RegisterTrackingWebhook (parameters);
Assert.IsNotNull (register.TrackingNumber);
Assert.IsNotNull (register.TrackingHistory);
}
[Test ()]
[ExpectedException (typeof (ShippoException))]
public void TestInvalidRegisterWebhook ()
{
Hashtable parameters = new Hashtable ();
parameters.Add ("carrier", "usps");
parameters.Add ("tracking_number", "INVALID_ID");
getAPIResource ().RegisterTrackingWebhook (parameters);
}
}
}
| apache-2.0 | C# |
035804e684ec8802e2b96a706bc610886c5a6f8c | Change path for def template generator | duduluu/RimTrans | RimTrans.Builder.Test/GenHelper.cs | RimTrans.Builder.Test/GenHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RimTrans.Builder;
using RimTrans.Builder.Crawler;
namespace RimTransLibTest {
public static class GenHelper {
public static void Gen_DefTypeNameOf() {
Console.Write(DefTypeCrawler.GenCode(true, false));
}
public static void Gen_DefsTemplate() {
DefinitionData coreDefinitionData = DefinitionData.Load(@"D:\Games\SteamLibrary\steamapps\common\RimWorld\Mods\Core\Defs");
Capture capture = Capture.Parse(coreDefinitionData);
capture.ProcessFieldNames(coreDefinitionData);
coreDefinitionData.Save(@"C:\git\rw\RimWorld-Defs-Templates\CoreDefsProcessed");
string sourceCodePath = @"C:\git\rw\RimWorld-Decompile\Assembly-CSharp";
Capture templates = Capture.Parse(coreDefinitionData, sourceCodePath, true);
templates.Save(@"C:\git\rw\RimWorld-Defs-Templates\Templates");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RimTrans.Builder;
using RimTrans.Builder.Crawler;
namespace RimTransLibTest {
public static class GenHelper {
public static void Gen_DefTypeNameOf() {
Console.Write(DefTypeCrawler.GenCode(true, false));
}
public static void Gen_DefsTemplate() {
DefinitionData coreDefinitionData = DefinitionData.Load(@"D:\Games\SteamLibrary\steamapps\common\RimWorld\Mods\Core\Defs");
Capture capture = Capture.Parse(coreDefinitionData);
capture.ProcessFieldNames(coreDefinitionData);
coreDefinitionData.Save(@"D:\git\rw\RimWorld-Defs-Templates\CoreDefsProcessed");
string sourceCodePath = @"D:\git\rw\RimWorld-Decompile\Assembly-CSharp";
Capture templates = Capture.Parse(coreDefinitionData, sourceCodePath, true);
templates.Save(@"D:\git\rw\RimWorld-Defs-Templates\Templates");
}
}
}
| mit | C# |
c4c6210c2b60b960f5a9e73ddbbdf85d7598ca05 | delete blank | matsurigoto/mvc-base-project,matsurigoto/mvc-base-project | Core/AutoFacModule/TaskModule.cs | Core/AutoFacModule/TaskModule.cs | using System.Reflection;
using Autofac;
using Core.Common.Task;
namespace Core.AutofacModule
{
/// <summary>
/// Autofac用來註冊Task相關的服務
/// </summary>
public class TaskModule : Autofac.Module
{
/// <summary>
/// Override to add registrations to the container.
/// </summary>
/// <param name="builder">The builder through which components can be
/// registered.</param>
/// <remarks>
/// Note that the ContainerBuilder parameter is unique to this module.
/// </remarks>
protected override void Load(Autofac.ContainerBuilder builder)
{
var assemblies = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assemblies).As<IRunAfterEachRequest>().InstancePerRequest();
builder.RegisterAssemblyTypes(assemblies).As<IRunAtStartup>();
builder.RegisterAssemblyTypes(assemblies).As<IRunOnEachRequest>().InstancePerRequest();
builder.RegisterAssemblyTypes(assemblies).As<IRunOnError>();
}
}
}
| using System.Reflection;
using Autofac;
using Core.Common.Task;
namespace Core.AutofacModule
{
/// <summary>
/// Autofac用來註冊Task相關的服務
/// </summary>
public class TaskModule : Autofac.Module
{
/// <summary>
/// Override to add registrations to the container.
/// </summary>
/// <param name="builder">The builder through which components can be
/// registered.</param>
/// <remarks>
/// Note that the ContainerBuilder parameter is unique to this module.
/// </remarks>
protected override void Load(Autofac.ContainerBuilder builder)
{
var assemblies = Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assemblies).As<IRunAfterEachRequest>().InstancePerRequest();
builder.RegisterAssemblyTypes(assemblies).As<IRunAtStartup>();
builder.RegisterAssemblyTypes(assemblies).As<IRunOnEachRequest>().InstancePerRequest();
builder.RegisterAssemblyTypes(assemblies).As<IRunOnError>();
}
}
}
| mit | C# |
ef0cae3d7a57286366f7ab408fe8ac40c79b493d | Throw for null | SteamDatabase/ValveResourceFormat | Decompiler/BasicVpkFileLoader.cs | Decompiler/BasicVpkFileLoader.cs | using System;
using System.IO;
using SteamDatabase.ValvePak;
namespace ValveResourceFormat.IO
{
public class BasicVpkFileLoader : IFileLoader
{
private readonly Package CurrentPackage;
public BasicVpkFileLoader(Package package)
{
CurrentPackage = package ?? throw new ArgumentNullException(nameof(package));
}
public Resource LoadFile(string file)
{
var entry = CurrentPackage.FindEntry(file);
if (entry == null)
{
return null;
}
CurrentPackage.ReadEntry(entry, out var output, false);
var resource = new Resource();
resource.Read(new MemoryStream(output));
return resource;
}
}
}
| using System.IO;
using SteamDatabase.ValvePak;
namespace ValveResourceFormat.IO
{
public class BasicVpkFileLoader : IFileLoader
{
private readonly Package CurrentPackage;
public BasicVpkFileLoader(Package package)
{
CurrentPackage = package;
}
public Resource LoadFile(string file)
{
var entry = CurrentPackage?.FindEntry(file);
if (entry == null)
{
return null;
}
CurrentPackage.ReadEntry(entry, out var output, false);
var resource = new Resource();
resource.Read(new MemoryStream(output));
return resource;
}
}
}
| mit | C# |
7d7c239ee898bc4666f6dd1b251d9ddcaaf39579 | Update assembly version to 3.0.3 | mattnis/ZendeskApi_v2,CKCobra/ZendeskApi_v2,mwarger/ZendeskApi_v2,dcrowe/ZendeskApi_v2 | ZendeskApi_v2/Properties/AssemblyInfo.cs | ZendeskApi_v2/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("ZendeskApi_v2")]
[assembly: AssemblyDescription("A full c# wrapper for Zendesk's api v2")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eric Neifert")]
[assembly: AssemblyProduct("ZendeskApi_v2")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("353b1163-f002-4a2a-9af8-56da7f827082")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.3.0")]
[assembly: AssemblyFileVersion("3.0.3.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("ZendeskApi_v2")]
[assembly: AssemblyDescription("A full c# wrapper for Zendesk's api v2")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Eric Neifert")]
[assembly: AssemblyProduct("ZendeskApi_v2")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("353b1163-f002-4a2a-9af8-56da7f827082")]
// 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.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]
| apache-2.0 | C# |
d776e93208ff31df211f5c1258d5f4ef5dd3f80c | Add overload to ProductInformation to determine which assembly to use | JJVertical/dotnet-apiport,mjrousos/dotnet-apiport,JJVertical/dotnet-apiport,conniey/dotnet-apiport,Microsoft/dotnet-apiport,Microsoft/dotnet-apiport,twsouthwick/dotnet-apiport,mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,conniey/dotnet-apiport,conniey/dotnet-apiport,twsouthwick/dotnet-apiport | src/Microsoft.Fx.Portability/ProductInformation.cs | src/Microsoft.Fx.Portability/ProductInformation.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.Resources;
using System;
using System.Reflection;
namespace Microsoft.Fx.Portability
{
public class ProductInformation
{
public ProductInformation(string name)
: this(name, typeof(ProductInformation))
{ }
public ProductInformation(string name, Type callerType)
{
var version = GetVersionString(callerType).Replace("-", ".");
if (!IsValid(name))
{
throw new ArgumentOutOfRangeException(nameof(name), LocalizedStrings.ProductInformationInvalidArgument);
}
if (!IsValid(version))
{
throw new ArgumentOutOfRangeException(nameof(version), LocalizedStrings.ProductInformationInvalidArgument);
}
Name = name;
Version = version;
}
public string Name { get; }
public string Version { get; }
private static string GetVersionString(Type callerType)
{
var assembly = callerType.GetTypeInfo().Assembly;
var info = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
return info?.InformationalVersion ?? "unknown";
}
/// <summary>
/// Verify strings/versions only contain letters, digits, '.', or '_'. Otherwise, the user agent string may be created incorrectly
/// </summary>
private static bool IsValid(string str)
{
foreach (var s in str.ToCharArray())
{
if (!char.IsLetterOrDigit(s) && s != '.' && s != '_')
{
return false;
}
}
return true;
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Fx.Portability.Resources;
using System;
using System.Reflection;
namespace Microsoft.Fx.Portability
{
public class ProductInformation
{
public ProductInformation(string name)
{
var version = GetVersionString().Replace("-", ".");
if (!IsValid(name))
{
throw new ArgumentOutOfRangeException(nameof(name), LocalizedStrings.ProductInformationInvalidArgument);
}
if (!IsValid(version))
{
throw new ArgumentOutOfRangeException(nameof(version), LocalizedStrings.ProductInformationInvalidArgument);
}
Name = name;
Version = version;
}
public string Name { get; }
public string Version { get; }
private static string GetVersionString()
{
var assembly = typeof(ProductInformation).GetTypeInfo().Assembly;
var info = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
return info?.InformationalVersion ?? "unknown";
}
/// <summary>
/// Verify strings/versions only contain letters, digits, '.', or '_'. Otherwise, the user agent string may be created incorrectly
/// </summary>
private static bool IsValid(string str)
{
foreach (var s in str.ToCharArray())
{
if (!char.IsLetterOrDigit(s) && s != '.' && s != '_')
{
return false;
}
}
return true;
}
}
}
| mit | C# |
4d1d82d9941b4ead34ae2e5b64725b7fd308c3ad | Increase the time for each test; a full run will be slower, but individual method runs become more stable. | BenJenkinson/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,malcolmr/nodatime,malcolmr/nodatime,nodatime/nodatime,nodatime/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,jskeet/nodatime,zaccharles/nodatime,zaccharles/nodatime | src/NodaTime.Benchmarks/Timing/BenchmarkOptions.cs | src/NodaTime.Benchmarks/Timing/BenchmarkOptions.cs | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2010 Jon Skeet
//
// 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.Linq;
namespace NodaTime.Benchmarks.Timing
{
/// <summary>
/// Encapsulates all the options for benchmarking, such as
/// the approximate length of each test, the timer to use
/// and so on.
/// </summary>
internal class BenchmarkOptions
{
private BenchmarkOptions()
{
}
internal Duration WarmUpTime { get; private set; }
internal Duration TestTime { get; private set; }
internal IBenchTimer Timer { get; private set; }
internal string TypeFilter { get; private set; }
internal string MethodFilter { get; private set; }
internal bool DisplayRawData { get; private set; }
internal static BenchmarkOptions FromCommandLine(string[] args)
{
// TODO: Use command line:)
return new BenchmarkOptions
{
TypeFilter = args.FirstOrDefault(),
MethodFilter = args.Skip(1).FirstOrDefault(),
WarmUpTime = Duration.FromSeconds(1),
TestTime = Duration.FromSeconds(10),
Timer = new WallTimer(),
DisplayRawData = args.Contains("-rawData")
};
}
}
} | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2010 Jon Skeet
//
// 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.Linq;
namespace NodaTime.Benchmarks.Timing
{
/// <summary>
/// Encapsulates all the options for benchmarking, such as
/// the approximate length of each test, the timer to use
/// and so on.
/// </summary>
internal class BenchmarkOptions
{
private BenchmarkOptions()
{
}
internal Duration WarmUpTime { get; private set; }
internal Duration TestTime { get; private set; }
internal IBenchTimer Timer { get; private set; }
internal string TypeFilter { get; private set; }
internal string MethodFilter { get; private set; }
internal bool DisplayRawData { get; private set; }
internal static BenchmarkOptions FromCommandLine(string[] args)
{
// TODO: Use command line:)
return new BenchmarkOptions
{
TypeFilter = args.FirstOrDefault(),
MethodFilter = args.Skip(1).FirstOrDefault(),
WarmUpTime = Duration.FromSeconds(1),
TestTime = Duration.FromSeconds(3),
Timer = new WallTimer(),
DisplayRawData = args.Contains("-rawData")
};
}
}
} | apache-2.0 | C# |
f00d243df3d066e065a3d74f1be0a04bbb5fd3b9 | Disable mipmap generation for LargeTextureStore | EVAST9919/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,Tom94/osu-framework | osu.Framework/Graphics/Textures/LargeTextureStore.cs | osu.Framework/Graphics/Textures/LargeTextureStore.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.IO.Stores;
using OpenTK.Graphics.ES30;
namespace osu.Framework.Graphics.Textures
{
/// <summary>
/// A texture store that bypasses atlasing and removes textures from memory after dereferenced by all consumers.
/// </summary>
public class LargeTextureStore : TextureStore
{
public LargeTextureStore(IResourceStore<TextureUpload> store = null)
: base(store, false, All.Linear, true)
{
}
/// <summary>
/// Retrieves a texture.
/// This texture should only be assigned once, as reference counting is being used internally.
/// If you wish to use the same texture multiple times, call this method an equal number of times.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <returns>The texture.</returns>
public override Texture Get(string name)
{
var baseTex = base.Get(name);
if (baseTex?.TextureGL == null) return null;
// encapsulate texture for ref counting
return new TextureWithRefCount(baseTex.TextureGL) { ScaleAdjust = ScaleAdjust };
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.IO.Stores;
namespace osu.Framework.Graphics.Textures
{
/// <summary>
/// A texture store that bypasses atlasing and removes textures from memory after dereferenced by all consumers.
/// </summary>
public class LargeTextureStore : TextureStore
{
public LargeTextureStore(IResourceStore<TextureUpload> store = null)
: base(store, false)
{
}
/// <summary>
/// Retrieves a texture.
/// This texture should only be assigned once, as reference counting is being used internally.
/// If you wish to use the same texture multiple times, call this method an equal number of times.
/// </summary>
/// <param name="name">The name of the texture.</param>
/// <returns>The texture.</returns>
public override Texture Get(string name)
{
var baseTex = base.Get(name);
if (baseTex?.TextureGL == null) return null;
// encapsulate texture for ref counting
return new TextureWithRefCount(baseTex.TextureGL) { ScaleAdjust = ScaleAdjust };
}
}
}
| mit | C# |
611f4df484972eb8236c2b3fd7ed12faf67d9d14 | Add licence header | johnneijzen/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,ZLima12/osu,UselessToucan/osu,peppy/osu,Frontear/osuKyzer,DrabWeb/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,Nabile-Rahmani/osu,Drezi126/osu,naoey/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,2yangk23/osu,smoogipooo/osu,ppy/osu,naoey/osu,NeoAdonis/osu,naoey/osu,smoogipoo/osu | osu.Game.Rulesets.Catch/Tests/TestCaseCatchPlayer.cs | osu.Game.Rulesets.Catch/Tests/TestCaseCatchPlayer.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
public class TestCaseCatchPlayer : Game.Tests.Visual.TestCasePlayer
{
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
| using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
public class TestCaseCatchPlayer : Game.Tests.Visual.TestCasePlayer
{
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
| mit | C# |
795ebeb1037c7777c75cf1a0e8414304ebc00257 | bump version | distantcam/Anotar,Fody/Anotar,mstyura/Anotar,modulexcite/Anotar | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("2.14.0")]
[assembly: AssemblyFileVersion("2.14.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("2.13.1")]
[assembly: AssemblyFileVersion("2.13.1")]
| mit | C# |
4ede16318ad15edd2a5f06b379e46a54066eb0c9 | Set the project's version number to what I currently expect. | antiduh/nsspi | NSspi/Properties/AssemblyInfo.cs | NSspi/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("NSspi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kevin Thompson")]
[assembly: AssemblyProduct("NSspi")]
[assembly: AssemblyCopyright("Copyright © Kevin Thompson 2014")]
[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("9abf710c-c646-42aa-8183-76bfa141a07b")]
// 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.1.0")]
[assembly: AssemblyFileVersion("0.1.1.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("NSspi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kevin Thompson")]
[assembly: AssemblyProduct("NSspi")]
[assembly: AssemblyCopyright("Copyright © Kevin Thompson 2014")]
[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("9abf710c-c646-42aa-8183-76bfa141a07b")]
// 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")]
| bsd-2-clause | C# |
80f3e8edbc416c298c401aa02f36967a2de47b18 | Fix stupid stuff. | TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC | OpenSim/Framework/CustomTypes.cs | OpenSim/Framework/CustomTypes.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 System;
namespace OpenSim.Framework
{
public enum CustomAssetType : sbyte
{
CustomTypeBase = 0x60,
AnimationSet = 0x60,
}
public enum CustomInventoryType : sbyte
{
CustomTypeBase = 0x60,
AnimationSet = 0x60,
}
}
| /*
* 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 System;
public const sbyte CustomTypeBase = 0x60;
public enum CustomAssetType : sbyte
{
AnimationSet = 0x60,
}
public enum CustomInventoryType : sbyte
{
AnimationSet = 0x60,
}
| bsd-3-clause | C# |
a9b6b03723822deb5f2ad6ead4617ca88116ea0a | Remove extra iterations | smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework | osu.Framework.Benchmarks/BenchmarkEnum.cs | osu.Framework.Benchmarks/BenchmarkEnum.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using BenchmarkDotNet.Attributes;
using osu.Framework.Extensions.EnumExtensions;
namespace osu.Framework.Benchmarks
{
[MemoryDiagnoser]
public class BenchmarkEnum
{
[Benchmark]
public bool HasFlag()
{
#pragma warning disable RS0030 // (banned API)
return (FlagsEnum.Flag2 | FlagsEnum.Flag3).HasFlag(FlagsEnum.Flag2);
#pragma warning restore RS0030
}
[Benchmark]
public bool BitwiseAnd()
{
return ((FlagsEnum.Flag2 | FlagsEnum.Flag3) & FlagsEnum.Flag2) > 0;
}
[Benchmark]
public bool HasFlagFast()
{
return (FlagsEnum.Flag2 | FlagsEnum.Flag3).HasFlagFast(FlagsEnum.Flag2);
}
[Flags]
private enum FlagsEnum
{
Flag1 = 1,
Flag2 = 2,
Flag3 = 4,
Flag4 = 8
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Runtime.CompilerServices;
using BenchmarkDotNet.Attributes;
using osu.Framework.Extensions.EnumExtensions;
namespace osu.Framework.Benchmarks
{
[MemoryDiagnoser]
public class BenchmarkEnum
{
[Benchmark]
public bool HasFlag()
{
bool result = false;
#pragma warning disable RS0030 // (banned API)
for (int i = 0; i < 1000000; i++)
result |= getFlags(i).HasFlag((FlagsEnum)i);
#pragma warning restore RS0030
return result;
}
[Benchmark]
public bool BitwiseAnd()
{
bool result = false;
for (int i = 0; i < 1000000; i++)
result |= (getFlags(i) & (FlagsEnum)i) > 0;
return result;
}
[Benchmark]
public bool HasFlagFast()
{
bool result = false;
for (int i = 0; i < 1000000; i++)
result |= getFlags(i).HasFlagFast((FlagsEnum)i);
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private FlagsEnum getFlags(int i) => (FlagsEnum)i;
[Flags]
private enum FlagsEnum
{
Flag1 = 1,
Flag2 = 2,
Flag3 = 4,
Flag4 = 8
}
}
}
| mit | C# |
766becf56ec945fc44e57447659b06993960b10e | Make virtual tracks reeeeeeeaaally long | EVAST9919/osu-framework,DrabWeb/osu-framework,naoey/osu-framework,default0/osu-framework,Nabile-Rahmani/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,peppy/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,default0/osu-framework,smoogipooo/osu-framework | osu.Framework/Audio/Track/TrackVirtual.cs | osu.Framework/Audio/Track/TrackVirtual.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 osu.Framework.Timing;
namespace osu.Framework.Audio.Track
{
public class TrackVirtual : Track
{
private readonly StopwatchClock clock = new StopwatchClock();
private double seekOffset;
public TrackVirtual()
{
Length = double.MaxValue;
}
public override bool Seek(double seek)
{
double current = CurrentTime;
seekOffset = seek;
lock (clock) clock.Restart();
if (Length > 0 && seekOffset > Length)
seekOffset = Length;
return current != seekOffset;
}
public override void Start()
{
lock (clock) clock.Start();
}
public override void Reset()
{
lock (clock) clock.Reset();
seekOffset = 0;
base.Reset();
}
public override void Stop()
{
lock (clock) clock.Stop();
}
public override bool IsRunning
{
get
{
lock (clock) return clock.IsRunning;
}
}
public override bool HasCompleted
{
get
{
lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length;
}
}
public override double CurrentTime
{
get
{
lock (clock) return seekOffset + clock.CurrentTime;
}
}
public override void Update()
{
lock (clock)
{
if (CurrentTime >= Length)
Stop();
}
}
}
}
| // 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 osu.Framework.Timing;
namespace osu.Framework.Audio.Track
{
public class TrackVirtual : Track
{
private readonly StopwatchClock clock = new StopwatchClock();
private double seekOffset;
public override bool Seek(double seek)
{
double current = CurrentTime;
seekOffset = seek;
lock (clock) clock.Restart();
if (Length > 0 && seekOffset > Length)
seekOffset = Length;
return current != seekOffset;
}
public override void Start()
{
lock (clock) clock.Start();
}
public override void Reset()
{
lock (clock) clock.Reset();
seekOffset = 0;
base.Reset();
}
public override void Stop()
{
lock (clock) clock.Stop();
}
public override bool IsRunning
{
get
{
lock (clock) return clock.IsRunning;
}
}
public override bool HasCompleted
{
get
{
lock (clock) return base.HasCompleted || IsLoaded && !IsRunning && CurrentTime >= Length;
}
}
public override double CurrentTime
{
get
{
lock (clock) return seekOffset + clock.CurrentTime;
}
}
public override void Update()
{
lock (clock)
{
if (CurrentTime >= Length)
Stop();
}
}
}
}
| mit | C# |
61b8fb03665b925193801877a73fdfe09c179bc7 | Allow ScreenTestCase to support content | DrabWeb/osu,ZLima12/osu,johnneijzen/osu,smoogipooo/osu,DrabWeb/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,ZLima12/osu,2yangk23/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,DrabWeb/osu,peppy/osu | osu.Game/Tests/Visual/ScreenTestCase.cs | osu.Game/Tests/Visual/ScreenTestCase.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// A test case which can be used to test a screen (that relies on OnEntering being called to execute startup instructions).
/// </summary>
public abstract class ScreenTestCase : OsuTestCase
{
private OsuScreenStack stack;
[BackgroundDependencyLoader]
private void load()
{
Add(stack = new OsuScreenStack { RelativeSizeAxes = Axes.Both });
}
protected void LoadScreen(OsuScreen screen)
{
if (stack.CurrentScreen != null)
stack.Exit();
stack.Push(screen);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Game.Screens;
namespace osu.Game.Tests.Visual
{
/// <summary>
/// A test case which can be used to test a screen (that relies on OnEntering being called to execute startup instructions).
/// </summary>
public abstract class ScreenTestCase : OsuTestCase
{
private readonly OsuScreenStack stack;
protected ScreenTestCase()
{
Child = stack = new OsuScreenStack { RelativeSizeAxes = Axes.Both };
}
protected void LoadScreen(OsuScreen screen)
{
if (stack.CurrentScreen != null)
stack.Exit();
stack.Push(screen);
}
}
}
| mit | C# |
8e1e1d440111ca9937b439ec59deb0e5838e2717 | Send time in UTC #29 | dermeister0/TimesheetParser,dermeister0/TimesheetParser | Source/JiraApi/TempoJobPoster.cs | Source/JiraApi/TempoJobPoster.cs | using Heavysoft.TimesheetParser.PluginInterfaces;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace JiraApi
{
class TempoJobPoster : IJobPoster
{
private readonly string jiraAccountId;
private readonly string token;
private readonly string jobType;
public TempoJobPoster(string jiraAccountId, string token, string jobType)
{
this.jiraAccountId = jiraAccountId;
this.token = token;
this.jobType = jobType;
}
public async Task<bool> SendAsync(JobDefinition job, HttpClient client)
{
var url = "https://api.tempo.io/core/3/worklogs";
var body = new TempoWorkLog() { issueKey = job.TaskId, timeSpentSeconds = job.Duration * 60, description = job.Description,
startDate = job.Date.ToString("yyyy-MM-dd"), startTime = job.Date.ToUniversalTime().ToString("HH:mm:ss"), authorAccountId = jiraAccountId };
body.attributes.Add(new TempoWorkAttribute { key = "_JobType_", value = jobType });
var authValue = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Authorization = authValue;
var response = await client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var content = JsonConvert.DeserializeObject<TempoWorkLogResponse>(await response.Content.ReadAsStringAsync());
var id = content.JiraWorklogId; // @@
return true;
}
return false;
}
}
}
| using Heavysoft.TimesheetParser.PluginInterfaces;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace JiraApi
{
class TempoJobPoster : IJobPoster
{
private readonly string jiraAccountId;
private readonly string token;
private readonly string jobType;
public TempoJobPoster(string jiraAccountId, string token, string jobType)
{
this.jiraAccountId = jiraAccountId;
this.token = token;
this.jobType = jobType;
}
public async Task<bool> SendAsync(JobDefinition job, HttpClient client)
{
var url = "https://api.tempo.io/core/3/worklogs";
var body = new TempoWorkLog() { issueKey = job.TaskId, timeSpentSeconds = job.Duration * 60, description = job.Description,
startDate = job.Date.ToString("yyyy-MM-dd"), startTime = "00:00:00", authorAccountId = jiraAccountId };
body.attributes.Add(new TempoWorkAttribute { key = "_JobType_", value = jobType });
var authValue = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Authorization = authValue;
var response = await client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
var content = JsonConvert.DeserializeObject<TempoWorkLogResponse>(await response.Content.ReadAsStringAsync());
var id = content.JiraWorklogId; // @@
return true;
}
return false;
}
}
}
| mit | C# |
eb11eaca03b26add79c3c22b77a884d577588dfa | Build fixes | nickdodd79/AutoBogus | src/AutoBogus.Conventions/AutoConventions.cs | src/AutoBogus.Conventions/AutoConventions.cs | using System;
using System.Collections.Generic;
namespace AutoBogus.Conventions
{
public static class AutoConventions
{
private static IList<IAutoConvention> Conventions = new List<IAutoConvention>
{
// new FirstNameConvention()
};
public static void Build(Action<AutoConventionsContext> builder = null)
{
// Build the conventions context
var context = new AutoConventionsContext();
if (builder != null)
{
builder.Invoke(context);
}
// Register the generator used to apply the conventions
AutoFaker.AddGeneratorOverride<string>(overrideContext =>
{
return null;
});
}
}
}
| using System;
using System.Collections.Generic;
namespace AutoBogus.Conventions
{
public static class AutoConventions
{
private static IList<IAutoConvention> Conventions = new List<IAutoConvention>
{
new FirstNameConvention()
};
public static void Build(Action<AutoConventionsContext> builder = null)
{
// Build the conventions context
var context = new AutoConventionsContext();
if (builder != null)
{
builder.Invoke(context);
}
// Register the generator used to apply the conventions
AutoFaker.AddGeneratorOverride<string>(overrideContext =>
{
});
}
}
}
| mit | C# |
a56c338ad3bd2aa705b5e9b4e091b41c436130e6 | adjust coding style | lohas1107/knn-on-air | Evaluation/Program.cs | Evaluation/Program.cs | using System;
using System.IO;
using System.Linq;
namespace Evaluation
{
class Program
{
static void Main(string[] args)
{
if (args.Count() == 0) return;
File.AppendAllText("test.txt", "456" + Environment.NewLine);
Console.WriteLine("Finish!");
Console.ReadLine();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Evaluation
{
class Program
{
static void Main(string[] args)
{
if (args.Count() == 0) return;
File.AppendAllText("test.txt", "456" + Environment.NewLine);
Console.WriteLine("Finish!");
Console.ReadLine();
}
}
}
| mit | C# |
902372c2ca32cd703eb3920ab05443591198faba | Add ctor | mstrother/BmpListener | src/BmpListener/Bgp/BgpHeader.cs | src/BmpListener/Bgp/BgpHeader.cs | using System;
using System.Linq;
namespace BmpListener.Bgp
{
public class BgpHeader
{
public BgpHeader()
{
}
public BgpHeader(ArraySegment<byte> data)
{
Decode(data);
}
public byte[] Marker { get; } = new byte[16];
public int Length { get; private set; }
public BgpMessageType Type { get; private set; }
public void Decode(ArraySegment<byte> data)
{
Length = BigEndian.ToUInt16(data, 16);
Type = (BgpMessageType)data.ElementAt(18);
}
}
} | using System;
namespace BmpListener.Bgp
{
public class BgpHeader
{
public byte[] Marker { get; } = new byte[16];
public int Length { get; private set; }
public BgpMessageType Type { get; private set; }
public void Decode(byte[] data, int offset)
{
Array.Copy(data, offset, Marker, 0, 16);
Array.Reverse(data, offset + 16, 2);
Length = BitConverter.ToInt16(data, offset + 16);
Type = (BgpMessageType)data[offset + 18];
}
}
} | mit | C# |
68478bc7e9037e6244fc0721345b23ff72377b80 | Fix memory display, add os | Auxes/Dogey | src/Dogey/Modules/AboutModule.cs | src/Dogey/Modules/AboutModule.cs | using Discord;
using Discord.Commands;
using Octokit;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Dogey.Modules
{
[RequireEnabled]
public class AboutModule : DogeyModuleBase
{
public string Library => $"Discord.Net ({DiscordConfig.Version})";
public string MemoryUsage => $"{Math.Round(_process.PagedMemorySize64 * .000001, 2)}mb";
private readonly GitHubClient _github;
private readonly Process _process;
public AboutModule(GitHubClient github)
{
_github = github;
_process = Process.GetCurrentProcess();
}
public string GetUptime()
{
var uptime = (DateTime.Now - _process.StartTime);
return $"{uptime.Days}d {uptime.Hours}h {uptime.Minutes}m {uptime.Seconds}s";
}
[Command("about")]
public async Task AboutAsync()
{
var app = await Context.Client.GetApplicationInfoAsync();
var commits = await _github.Repository.Commit.GetAll("Aux", "Dogey", new ApiOptions()
{
PageSize = 3,
PageCount = 1
});
var builder = new StringBuilder()
.AppendLine("**Recent Commits:**");
foreach (var commit in commits)
builder.AppendLine($"[`{commit.Sha.Substring(0, 7)}`]({commit.HtmlUrl}) {commit.Commit.Message}");
var embed = new EmbedBuilder()
.WithAuthor(app.Owner)
.WithDescription(builder.ToString())
.AddInlineField("Memory", MemoryUsage)
.AddInlineField("Latency", Context.Client.Latency + "ms")
.AddInlineField("Uptime", GetUptime())
.AddInlineField("OS", RuntimeInformation.OSDescription)
.WithFooter(x => x.Text = Library);
await ReplyEmbedAsync(embed);
}
}
}
| using Discord;
using Discord.Commands;
using Octokit;
using System;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace Dogey.Modules
{
[RequireEnabled]
public class AboutModule : DogeyModuleBase
{
public string Library => $"Discord.Net ({DiscordConfig.Version})";
public string MemoryUsage => $"{Math.Round(GC.GetTotalMemory(true) / (1024.0 * 1024.0), 2)}mb";
private readonly GitHubClient _github;
private readonly Process _process;
public AboutModule(GitHubClient github)
{
_github = github;
_process = Process.GetCurrentProcess();
}
public string GetUptime()
{
var uptime = (DateTime.Now - _process.StartTime);
return $"{uptime.Days}d {uptime.Hours}h {uptime.Minutes}m {uptime.Seconds}s";
}
[Command("about")]
public async Task AboutAsync()
{
var app = await Context.Client.GetApplicationInfoAsync();
var commits = await _github.Repository.Commit.GetAll("Aux", "Dogey", new ApiOptions()
{
PageSize = 3,
PageCount = 1
});
var builder = new StringBuilder()
.AppendLine("**Recent Commits:**");
foreach (var commit in commits)
builder.AppendLine($"[`{commit.Sha.Substring(0, 7)}`]({commit.HtmlUrl}) {commit.Commit.Message}");
var embed = new EmbedBuilder()
.WithAuthor(app.Owner)
.WithDescription(builder.ToString())
.AddInlineField("Memory", MemoryUsage)
.AddInlineField("Latency", Context.Client.Latency + "ms")
.AddInlineField("Uptime", GetUptime())
.WithFooter(x => x.Text = Library);
await ReplyEmbedAsync(embed);
}
}
}
| apache-2.0 | C# |
c2bf38d47e8c513034287c4c62d2626bcd6e8581 | Fix ladder placement. | yungtechboy1/MiNET | src/MiNET/MiNET/Blocks/Ladder.cs | src/MiNET/MiNET/Blocks/Ladder.cs | using System.Numerics;
using MiNET.Utils;
using MiNET.Worlds;
namespace MiNET.Blocks
{
public class Ladder : Block
{
public Ladder() : base(65)
{
IsTransparent = true;
BlastResistance = 2;
Hardness = 0.4f;
}
protected override bool CanPlace(Level world, BlockCoordinates blockCoordinates, BlockFace face)
{
return /*!world.GetBlock(blockCoordinates).IsTransparent &&*/ face != BlockFace.Down && face != BlockFace.Up;
}
public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
{
Metadata = (byte) face;
world.SetBlock(this);
return true;
}
}
} | using System.Numerics;
using MiNET.Utils;
using MiNET.Worlds;
namespace MiNET.Blocks
{
public class Ladder : Block
{
public Ladder() : base(65)
{
IsTransparent = true;
BlastResistance = 2;
Hardness = 0.4f;
}
protected override bool CanPlace(Level world, BlockCoordinates blockCoordinates, BlockFace face)
{
return !world.GetBlock(blockCoordinates).IsTransparent && face != BlockFace.Down && face != BlockFace.Up;
}
public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
{
Metadata = (byte) face;
return base.PlaceBlock(world, player, blockCoordinates, face, faceCoords);
}
}
} | mpl-2.0 | C# |
f633d276f5a371cd04c81c1f45f5c592558959ed | Change Assembly language. | azyobuzin/StatefulModel,ugaya40/StatefulModel | src/StatefulModel/Properties/AssemblyInfo.cs | src/StatefulModel/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("StatefulModel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StatefulModel")]
[assembly: AssemblyCopyright("Copyright (C) Masanori Onoue, 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Reflection;
using System.Resources;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("StatefulModel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StatefulModel")]
[assembly: AssemblyCopyright("Copyright (C) Masanori Onoue, 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("ja")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| mit | C# |
d5160e0c345d8441deae11a417a8d8aa5f14d37c | Update Index.cshtml | KrishnaIBM/TestCt-1478684487505,KrishnaIBM/TestCt-1478684487505 | src/dotnetCloudantWebstarter/Views/Home/Index.cshtml | src/dotnetCloudantWebstarter/Views/Home/Index.cshtml | @{
ViewData["Title"] = "Home Page";
}
<h3></h3>
<form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
<input type="file" name="files" multiple />
<input type="submit" value="Upload" />
</form>
| @{
ViewData["Title"] = "Home Page";
}
<h3>@ViewData["Message"]</h3>
<form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
<input type="file" name="files" multiple />
<input type="submit" value="Upload" />
</form>
| apache-2.0 | C# |
6a661d1766e473e0a013cafe5b227a7723f59a59 | Prepare inspect code | NeoAdonis/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,EVAST9919/osu,ZLima12/osu,smoogipoo/osu,smoogipooo/osu,DrabWeb/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,naoey/osu,2yangk23/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,ZLima12/osu,naoey/osu,NeoAdonis/osu,DrabWeb/osu,NeoAdonis/osu,DrabWeb/osu | build.cake | build.cake | #tool "nuget:?package=JetBrains.ReSharper.CommandLineTools"
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Build");
var framework = Argument("framework", "net471");
var configuration = Argument("configuration", "Release");
var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj");
var testProjects = GetFiles("**/*.Tests.csproj");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Compile")
.Does(() => {
DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings {
Framework = framework,
Configuration = configuration
});
});
Task("Test")
.ContinueOnError()
.DoesForEach(testProjects, testProject => {
DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings {
Framework = framework,
Configuration = configuration,
Logger = $"trx;LogFileName={testProject.GetFilename()}.trx",
ResultsDirectory = "./TestResults/"
});
});
Task("InspectCode")
.Does(() => {
});
Task("Build")
.IsDependentOn("Compile")
.IsDependentOn("Test");
RunTarget(target); | ///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Build");
var framework = Argument("framework", "net471");
var configuration = Argument("configuration", "Release");
var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj");
var testProjects = GetFiles("**/*.Tests.csproj");
///////////////////////////////////////////////////////////////////////////////
// TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Compile")
.Does(() => {
DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings {
Framework = framework,
Configuration = configuration
});
});
Task("Test")
.ContinueOnError()
.DoesForEach(testProjects, testProject => {
DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings {3
Framework = framework,
Configuration = configuration,
Logger = $"trx;LogFileName={testProject.GetFilename()}.trx",
ResultsDirectory = "./TestResults/"
});
});
Task("Build")
.IsDependentOn("Compile")
.IsDependentOn("Test");
RunTarget(target); | mit | C# |
70b27862f369c5441cf5072e29c30b78194d1c80 | Use dotnet core instead of msbuild | olsh/todoist-net | build.cake | build.cake | #tool "nuget:?package=OpenCover"
#tool "nuget:?package=Codecov"
#addin "nuget:?package=Cake.Codecov"
var target = Argument("target", "Default");
var buildConfiguration = "Release";
var projectName = "Todoist.Net";
var testProjectName = "Todoist.Net.Tests";
var projectFolder = string.Format("./src/{0}/", projectName);
var projectFile = string.Format("./src/{0}/{0}.csproj", projectName);
var testProjectFile = string.Format("./src/{0}/{0}.csproj", testProjectName);
var extensionsVersion = XmlPeek(projectFile, "Project/PropertyGroup[1]/VersionPrefix/text()");
Task("UpdateBuildVersion")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
var buildNumber = BuildSystem.AppVeyor.Environment.Build.Number;
BuildSystem.AppVeyor.UpdateBuildVersion(string.Format("{0}.{1}", extensionsVersion, buildNumber));
});
Task("Build")
.Does(() =>
{
var settings = new DotNetCoreBuildSettings
{
Configuration = buildConfiguration
};
DotNetCoreBuild(string.Format("{0}.sln", projectName), settings);
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = buildConfiguration
};
DotNetCoreTest(testProjectFile, settings);
});
Task("CodeCoverage")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = buildConfiguration
};
var coverageSettings = new OpenCoverSettings
{
// Workaround for the issue https://github.com/OpenCover/opencover/issues/601
OldStyle = true
};
var coverageFileName = "./coverage.xml";
OpenCover(tool => { tool.DotNetCoreTest(testProjectFile, settings); },
new FilePath(coverageFileName),
coverageSettings
.WithFilter("+[Todoist.Net]*")
.WithFilter("-[Todoist.Net.Tests]*"));
Codecov(coverageFileName, EnvironmentVariable("codecov:token"));
});
Task("NugetPack")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = buildConfiguration,
OutputDirectory = "."
};
DotNetCorePack(projectFolder, settings);
});
Task("CreateArtifact")
.IsDependentOn("NugetPack")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.nupkg", projectName, extensionsVersion));
});
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("NugetPack");
Task("CI")
.IsDependentOn("UpdateBuildVersion")
.IsDependentOn("CodeCoverage")
.IsDependentOn("CreateArtifact");
RunTarget(target);
| #tool "nuget:?package=OpenCover"
#tool "nuget:?package=Codecov"
#addin "nuget:?package=Cake.Codecov"
var target = Argument("target", "Default");
var buildConfiguration = "Release";
var projectName = "Todoist.Net";
var testProjectName = "Todoist.Net.Tests";
var projectFolder = string.Format("./src/{0}/", projectName);
var projectFile = string.Format("./src/{0}/{0}.csproj", projectName);
var testProjectFile = string.Format("./src/{0}/{0}.csproj", testProjectName);
var extensionsVersion = XmlPeek(projectFile, "Project/PropertyGroup[1]/VersionPrefix/text()");
Task("UpdateBuildVersion")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
var buildNumber = BuildSystem.AppVeyor.Environment.Build.Number;
BuildSystem.AppVeyor.UpdateBuildVersion(string.Format("{0}.{1}", extensionsVersion, buildNumber));
});
Task("Build")
.Does(() =>
{
MSBuild(string.Format("{0}.sln", projectName),
settings => settings
.SetConfiguration(buildConfiguration)
.SetVerbosity(Verbosity.Minimal));
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = buildConfiguration
};
DotNetCoreTest(testProjectFile, settings);
});
Task("CodeCoverage")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCoreTestSettings
{
Configuration = buildConfiguration
};
var coverageSettings = new OpenCoverSettings
{
// Workaround for the issue https://github.com/OpenCover/opencover/issues/601
OldStyle = true
};
var coverageFileName = "./coverage.xml";
OpenCover(tool => { tool.DotNetCoreTest(testProjectFile, settings); },
new FilePath(coverageFileName),
coverageSettings
.WithFilter("+[Todoist.Net]*")
.WithFilter("-[Todoist.Net.Tests]*"));
Codecov(coverageFileName, EnvironmentVariable("codecov:token"));
});
Task("NugetPack")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = buildConfiguration,
OutputDirectory = "."
};
DotNetCorePack(projectFolder, settings);
});
Task("CreateArtifact")
.IsDependentOn("NugetPack")
.WithCriteria(BuildSystem.AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
BuildSystem.AppVeyor.UploadArtifact(string.Format("{0}.{1}.nupkg", projectName, extensionsVersion));
});
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("NugetPack");
Task("CI")
.IsDependentOn("UpdateBuildVersion")
.IsDependentOn("CodeCoverage")
.IsDependentOn("CreateArtifact");
RunTarget(target);
| mit | C# |
d59090c38cabd735de4dd661eb940fc8991de93c | Update to latest PleOps.Cake | SceneGate/Yarhl | build.cake | build.cake | #load "nuget:?package=PleOps.Cake&version=0.5.1"
Task("Define-Project")
.Description("Fill specific project information")
.Does<BuildInfo>(info =>
{
info.AddLibraryProjects("Yarhl");
info.AddLibraryProjects("Yarhl.Media");
info.AddTestProjects("Yarhl.UnitTests");
info.AddTestProjects("Yarhl.IntegrationTests");
info.PreviewNuGetFeed = "https://pkgs.dev.azure.com/SceneGate/SceneGate/_packaging/SceneGate-Preview/nuget/v3/index.json";
});
Task("Prepare-IntegrationTests")
.Description("Prepare the integration tests by copying an example of DLL")
.IsDependeeOf("Test")
.Does<BuildInfo>(info =>
{
// Copy a good and bad plugin to test the assembly load logic
string pluginPath = $"src/Yarhl.Media/bin/{info.Configuration}/netstandard2.0/Yarhl.Media.dll";
string badPluginPath = info.SolutionFile; // this isn't a DLL for sure :D
string outputBasePath = $"src/Yarhl.IntegrationTests/bin/{info.Configuration}";
string testProjectPath = "src/Yarhl.IntegrationTests/Yarhl.IntegrationTests.csproj";
foreach (string framework in GetTargetFrameworks(testProjectPath)) {
string pluginDir = $"{outputBasePath}/{framework}/Plugins";
CreateDirectory(pluginDir);
CopyFile(pluginPath, $"{pluginDir}/Yarhl.Media.dll");
CopyFile(badPluginPath, $"{pluginDir}/MyBadPlugin.dll");
}
});
public IEnumerable<string> GetTargetFrameworks(string projectPath)
{
var projectXml = System.Xml.Linq.XDocument.Load(projectPath).Root;
List<string> frameworks = projectXml.Elements("PropertyGroup")
.Where(x => x.Element("TargetFrameworks") != null)
.SelectMany(x => x.Element("TargetFrameworks").Value.Split(';'))
.ToList();
string singleFramework = projectXml.Elements("PropertyGroup")
.Select(x => x.Element("TargetFramework")?.Value)
.FirstOrDefault();
if (singleFramework != null && !frameworks.Contains(singleFramework)) {
frameworks.Add(singleFramework);
}
return frameworks;
}
Task("Default")
.IsDependentOn("Stage-Artifacts");
string target = Argument("target", "Default");
RunTarget(target);
| #load "nuget:?package=PleOps.Cake&version=0.5.0"
Task("Define-Project")
.Description("Fill specific project information")
.Does<BuildInfo>(info =>
{
info.AddLibraryProjects("Yarhl");
info.AddLibraryProjects("Yarhl.Media");
info.AddTestProjects("Yarhl.UnitTests");
info.AddTestProjects("Yarhl.IntegrationTests");
info.PreviewNuGetFeed = "https://pkgs.dev.azure.com/SceneGate/SceneGate/_packaging/SceneGate-Preview/nuget/v3/index.json";
});
Task("Prepare-IntegrationTests")
.Description("Prepare the integration tests by copying an example of DLL")
.IsDependeeOf("Test")
.Does<BuildInfo>(info =>
{
// Copy a good and bad plugin to test the assembly load logic
string pluginPath = $"src/Yarhl.Media/bin/{info.Configuration}/netstandard2.0/Yarhl.Media.dll";
string badPluginPath = info.SolutionFile; // this isn't a DLL for sure :D
string outputBasePath = $"src/Yarhl.IntegrationTests/bin/{info.Configuration}";
string testProjectPath = "src/Yarhl.IntegrationTests/Yarhl.IntegrationTests.csproj";
foreach (string framework in GetTargetFrameworks(testProjectPath)) {
string pluginDir = $"{outputBasePath}/{framework}/Plugins";
CreateDirectory(pluginDir);
CopyFile(pluginPath, $"{pluginDir}/Yarhl.Media.dll");
CopyFile(badPluginPath, $"{pluginDir}/MyBadPlugin.dll");
}
});
public IEnumerable<string> GetTargetFrameworks(string projectPath)
{
var projectXml = System.Xml.Linq.XDocument.Load(projectPath).Root;
List<string> frameworks = projectXml.Elements("PropertyGroup")
.Where(x => x.Element("TargetFrameworks") != null)
.SelectMany(x => x.Element("TargetFrameworks").Value.Split(';'))
.ToList();
string singleFramework = projectXml.Elements("PropertyGroup")
.Select(x => x.Element("TargetFramework")?.Value)
.FirstOrDefault();
if (singleFramework != null && !frameworks.Contains(singleFramework)) {
frameworks.Add(singleFramework);
}
return frameworks;
}
Task("Default")
.IsDependentOn("Stage-Artifacts");
string target = Argument("target", "Default");
RunTarget(target);
| mit | C# |
a53d8af1e10adab85a67518a77caa9d977ca4cee | Add unit test script | Krusen/Additio.Sitecore.DependencyConfigReader | build.cake | build.cake | #tool "xunit.runner.console"
var target = Argument("target", "Default");
var solution = "./src/Additio.Sitecore.DependencyConfigReader.sln";
var version = "1.0.2";
var buildOutput = "./.build";
Task("Default")
.IsDependentOn("Clean")
.IsDependentOn("Build")
.IsDependentOn("Pack")
;
Task("Clean")
.Does(() =>
{
CleanDirectory(buildOutput);
});
Task("Build")
.Does(() =>
{
NuGetRestore(solution);
MSBuild(solution, settings =>
settings.SetVerbosity(Verbosity.Minimal)
.SetConfiguration("Release")
.WithTarget("Rebuild")
.UseToolVersion(MSBuildToolVersion.VS2015)
.SetMaxCpuCount(0)
.ArgumentCustomization = args => args.Append("/nologo")
);
});
Task("UnitTest")
.IsDependentOn("Build")
.Does(() =>
{
var projectFiles = GetFiles("./src/**/*.csproj").Where(x => x.FullPath.EndsWith(".Tests.csproj"));
foreach (var project in projectFiles)
{
Information("Building test project '" + project.Segments.Last() + "'");
MSBuild(project, settings =>
settings.SetVerbosity(Verbosity.Normal)
.SetConfiguration("Release")
.WithTarget("Build")
.UseToolVersion(MSBuildToolVersion.VS2015)
.ArgumentCustomization = args => args.Append("/nologo")
);
}
XUnit2("./src/**/bin/Release/*.Tests.dll");
});
Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = version,
Symbols = false,
OutputDirectory = buildOutput
};
NuGetPack("./nuget/Additio.Sitecore.DependencyConfigReader.nuspec", settings);
});
RunTarget(target); | var target = Argument("target", "Default");
var solution = "./src/Additio.Sitecore.DependencyConfigReader.sln";
var version = "1.0.2";
var buildOutput = "./.build";
Task("Default")
.IsDependentOn("Clean")
.IsDependentOn("Build")
.IsDependentOn("Pack")
;
Task("Clean")
.Does(() =>
{
CleanDirectory(buildOutput);
});
Task("Build")
.Does(() =>
{
NuGetRestore(solution);
MSBuild(solution, settings =>
settings.SetVerbosity(Verbosity.Minimal)
.SetConfiguration("Release")
.WithTarget("Rebuild")
.UseToolVersion(MSBuildToolVersion.VS2015)
.SetMaxCpuCount(0)
.ArgumentCustomization = args => args.Append("/nologo")
);
});
Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
var settings = new NuGetPackSettings
{
Version = version,
Symbols = false,
OutputDirectory = buildOutput
};
NuGetPack("./nuget/Additio.Sitecore.DependencyConfigReader.nuspec", settings);
});
RunTarget(target); | unlicense | C# |
5e9887684de8272285df8f4ea2d40d5d12365268 | Fix category of revision log RSS feeds. | netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,netjunki/trac-Pygit2,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac,jun66j5/trac-ja,walty8/trac,walty8/trac,netjunki/trac-Pygit2 | templates/log_rss.cs | templates/log_rss.cs | <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Log</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
| <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Report</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
| bsd-3-clause | C# |
496e4d97a021479b5f6179b17dbdfd6a6a2ce9c1 | Change to find current muxer (#11405) | johnbeisner/cli,livarcocc/cli-1,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1,johnbeisner/cli | src/Microsoft.DotNet.Cli.Utils/Muxer.cs | src/Microsoft.DotNet.Cli.Utils/Muxer.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics;
using System.IO;
namespace Microsoft.DotNet.Cli.Utils
{
public class Muxer
{
public static readonly string MuxerName = "dotnet";
private readonly string _muxerPath;
internal string SharedFxVersion
{
get
{
var depsFile = new FileInfo(GetDataFromAppDomain("FX_DEPS_FILE"));
return depsFile.Directory.Name;
}
}
public string MuxerPath
{
get
{
if (_muxerPath == null)
{
throw new InvalidOperationException(LocalizableStrings.UnableToLocateDotnetMultiplexer);
}
return _muxerPath;
}
}
public Muxer()
{
_muxerPath = Process.GetCurrentProcess().MainModule.FileName;
}
public static string GetDataFromAppDomain(string propertyName)
{
return AppContext.GetData(propertyName) as string;
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Reflection;
namespace Microsoft.DotNet.Cli.Utils
{
public class Muxer
{
public static readonly string MuxerName = "dotnet";
private static readonly string s_muxerFileName = MuxerName + Constants.ExeSuffix;
private string _muxerPath;
internal string SharedFxVersion
{
get
{
var depsFile = new FileInfo(GetDataFromAppDomain("FX_DEPS_FILE"));
return depsFile.Directory.Name;
}
}
public string MuxerPath
{
get
{
if (_muxerPath == null)
{
throw new InvalidOperationException(LocalizableStrings.UnableToLocateDotnetMultiplexer);
}
return _muxerPath;
}
}
public Muxer()
{
if (!TryResolveMuxerFromParentDirectories())
{
TryResolverMuxerFromPath();
}
}
public static string GetDataFromAppDomain(string propertyName)
{
return AppContext.GetData(propertyName) as string;
}
private bool TryResolveMuxerFromParentDirectories()
{
var fxDepsFile = GetDataFromAppDomain("FX_DEPS_FILE");
if (string.IsNullOrEmpty(fxDepsFile))
{
return false;
}
var muxerDir = new FileInfo(fxDepsFile).Directory?.Parent?.Parent?.Parent;
if (muxerDir == null)
{
return false;
}
var muxerCandidate = Path.Combine(muxerDir.FullName, s_muxerFileName);
if (!File.Exists(muxerCandidate))
{
return false;
}
_muxerPath = muxerCandidate;
return true;
}
private bool TryResolverMuxerFromPath()
{
var muxerPath = Env.GetCommandPath(MuxerName, Constants.ExeSuffix);
if (muxerPath == null || !File.Exists(muxerPath))
{
return false;
}
_muxerPath = muxerPath;
return true;
}
}
}
| mit | C# |
0daa4a93e0edb5d7cf4589f0118598dab9ed54e6 | fix #372 do not touch DefaultIndex if its not neccessary while resolving index name | NickCraver/NEST,SeanKilleen/elasticsearch-net,jonyadamit/elasticsearch-net,Grastveit/NEST,starckgates/elasticsearch-net,KodrAus/elasticsearch-net,ststeiger/elasticsearch-net,TheFireCookie/elasticsearch-net,alanprot/elasticsearch-net,jonyadamit/elasticsearch-net,mac2000/elasticsearch-net,NickCraver/NEST,LeoYao/elasticsearch-net,KodrAus/elasticsearch-net,CSGOpenSource/elasticsearch-net,joehmchan/elasticsearch-net,geofeedia/elasticsearch-net,tkirill/elasticsearch-net,alanprot/elasticsearch-net,starckgates/elasticsearch-net,adam-mccoy/elasticsearch-net,alanprot/elasticsearch-net,mac2000/elasticsearch-net,adam-mccoy/elasticsearch-net,robrich/elasticsearch-net,ststeiger/elasticsearch-net,RossLieberman/NEST,gayancc/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,cstlaurent/elasticsearch-net,robertlyson/elasticsearch-net,gayancc/elasticsearch-net,wawrzyn/elasticsearch-net,amyzheng424/elasticsearch-net,geofeedia/elasticsearch-net,joehmchan/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,gayancc/elasticsearch-net,abibell/elasticsearch-net,robrich/elasticsearch-net,amyzheng424/elasticsearch-net,cstlaurent/elasticsearch-net,Grastveit/NEST,junlapong/elasticsearch-net,UdiBen/elasticsearch-net,faisal00813/elasticsearch-net,alanprot/elasticsearch-net,DavidSSL/elasticsearch-net,mac2000/elasticsearch-net,UdiBen/elasticsearch-net,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,DavidSSL/elasticsearch-net,LeoYao/elasticsearch-net,geofeedia/elasticsearch-net,amyzheng424/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,faisal00813/elasticsearch-net,wawrzyn/elasticsearch-net,faisal00813/elasticsearch-net,robertlyson/elasticsearch-net,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,junlapong/elasticsearch-net,elastic/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net,SeanKilleen/elasticsearch-net,abibell/elasticsearch-net,robertlyson/elasticsearch-net,tkirill/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,joehmchan/elasticsearch-net,DavidSSL/elasticsearch-net,abibell/elasticsearch-net,cstlaurent/elasticsearch-net,NickCraver/NEST,junlapong/elasticsearch-net,Grastveit/NEST,LeoYao/elasticsearch-net,tkirill/elasticsearch-net,RossLieberman/NEST,wawrzyn/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Resolvers/IndexNameResolver.cs | src/Nest/Resolvers/IndexNameResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Reflection;
namespace Nest.Resolvers
{
public class IndexNameResolver
{
private readonly IConnectionSettings _connectionSettings;
public IndexNameResolver(IConnectionSettings connectionSettings)
{
connectionSettings.ThrowIfNull("hasDefaultIndices");
this._connectionSettings = connectionSettings;
}
public string GetIndexForType<T>()
{
return this.GetIndexForType(typeof(T));
}
public string GetIndexForType(Type type)
{
var defaultIndices = this._connectionSettings.DefaultIndices;
if (defaultIndices == null)
return this._connectionSettings.DefaultIndex;
if (defaultIndices.ContainsKey(type) && !string.IsNullOrWhiteSpace(defaultIndices[type]))
return defaultIndices[type];
return this._connectionSettings.DefaultIndex;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Reflection;
namespace Nest.Resolvers
{
public class IndexNameResolver
{
private readonly IConnectionSettings _connectionSettings;
public IndexNameResolver(IConnectionSettings connectionSettings)
{
connectionSettings.ThrowIfNull("hasDefaultIndices");
this._connectionSettings = connectionSettings;
}
public string GetIndexForType<T>()
{
return this.GetIndexForType(typeof(T));
}
public string GetIndexForType(Type type)
{
var defaultIndices = this._connectionSettings.DefaultIndices;
var defaultIndex = this._connectionSettings.DefaultIndex;
if (defaultIndices == null)
return defaultIndex;
if (defaultIndices.ContainsKey(type) && !string.IsNullOrWhiteSpace(defaultIndices[type]))
return defaultIndices[type];
return defaultIndex;
}
}
}
| apache-2.0 | C# |
b4d41dd89d7d1214fd7adfd9140e2e220b0eb263 | Trim newline chars on clipboard data. | antmicro/TermSharp | Misc/ClipboardData.cs | Misc/ClipboardData.cs | //
// Copyright (c) Antmicro
//
// Full license details are defined in the 'LICENSE' file.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace TermSharp.Misc
{
public sealed class ClipboardData
{
public ClipboardData()
{
rows = new List<string>();
}
public void AppendText(string text)
{
rows.Add(text);
}
public string Text
{
get
{
if(rows.Count == 0)
{
return string.Empty;
}
return string.Join(Environment.NewLine, rows.Select(x => x.TrimEnd('\n').TrimEnd('\r')));
}
}
private readonly List<string> rows;
}
}
| //
// Copyright (c) Antmicro
//
// Full license details are defined in the 'LICENSE' file.
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace TermSharp.Misc
{
public sealed class ClipboardData
{
public ClipboardData()
{
rows = new List<string>();
}
public void AppendText(string text)
{
rows.Add(text);
}
public string Text
{
get
{
if(rows.Count == 0)
{
return string.Empty;
}
return string.Join(Environment.NewLine, rows);
}
}
private readonly List<string> rows;
}
}
| apache-2.0 | C# |
89bc03e9c5078c217f848878aa49091c80dcb068 | Fix ISchedulerProvider Autofac registration. | xjpeter/Naru | Naru.WPF/WPFModule.cs | Naru.WPF/WPFModule.cs | using Autofac;
using Naru.WPF.Dialog;
using Naru.WPF.Menu;
using Naru.WPF.MVVM;
using Naru.WPF.Scheduler;
using Naru.WPF.ToolBar;
using Naru.WPF.ViewModel;
namespace Naru.WPF
{
public class WPFModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<SchedulerProvider>().As<ISchedulerProvider>().SingleInstance();
builder.RegisterType<ViewService>().As<IViewService>();
// Dialogs
builder.RegisterGeneric(typeof(DialogBuilder<>)).As(typeof(IDialogBuilder<>)).InstancePerDependency();
builder.RegisterType<StandardDialogBuilder>().As<IStandardDialogBuilder>().InstancePerDependency();
// ToolBar
builder.RegisterType<ToolBarService>().As<IToolBarService>().SingleInstance();
builder.RegisterType<ToolBarButtonItem>().AsSelf().InstancePerDependency();
// Menu
builder.RegisterType<MenuService>().As<IMenuService>().SingleInstance();
builder.RegisterType<MenuButtonItem>().AsSelf().InstancePerDependency();
builder.RegisterType<MenuGroupItem>().AsSelf().InstancePerDependency();
builder.RegisterType<MenuSeperatorItem>().AsSelf().InstancePerDependency();
// Collections
builder.RegisterGeneric(typeof(BindableCollection<>)).AsSelf().InstancePerDependency();
builder.RegisterGeneric(typeof(ReactiveSingleSelectCollection<>)).AsSelf().InstancePerDependency();
builder.RegisterGeneric(typeof(ReactiveMultiSelectCollection<>)).AsSelf().InstancePerDependency();
}
}
} | using Autofac;
using Naru.WPF.Dialog;
using Naru.WPF.Menu;
using Naru.WPF.MVVM;
using Naru.WPF.Scheduler;
using Naru.WPF.ToolBar;
using Naru.WPF.ViewModel;
namespace Naru.WPF
{
public class WPFModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<SchedulerProvider>().As<ISchedulerProvider>();
builder.RegisterType<ViewService>().As<IViewService>();
// Dialogs
builder.RegisterGeneric(typeof(DialogBuilder<>)).As(typeof(IDialogBuilder<>)).InstancePerDependency();
builder.RegisterType<StandardDialogBuilder>().As<IStandardDialogBuilder>().InstancePerDependency();
// ToolBar
builder.RegisterType<ToolBarService>().As<IToolBarService>().SingleInstance();
builder.RegisterType<ToolBarButtonItem>().AsSelf().InstancePerDependency();
// Menu
builder.RegisterType<MenuService>().As<IMenuService>().SingleInstance();
builder.RegisterType<MenuButtonItem>().AsSelf().InstancePerDependency();
builder.RegisterType<MenuGroupItem>().AsSelf().InstancePerDependency();
builder.RegisterType<MenuSeperatorItem>().AsSelf().InstancePerDependency();
// Collections
builder.RegisterGeneric(typeof(BindableCollection<>)).AsSelf().InstancePerDependency();
builder.RegisterGeneric(typeof(ReactiveSingleSelectCollection<>)).AsSelf().InstancePerDependency();
builder.RegisterGeneric(typeof(ReactiveMultiSelectCollection<>)).AsSelf().InstancePerDependency();
}
}
} | mit | C# |
2f6a5aa5b053a8fe17dd33039253722c81b305d9 | rewrite Log4NetLogger, add new constructor. | functionGHW/HelperLibrary | HelperLibrary.Core.Logging.Log4Net/Log4NetLogger.cs | HelperLibrary.Core.Logging.Log4Net/Log4NetLogger.cs | /*
* FileName: Log4NetLogger.cs
* Author: functionghw<functionghw@hotmail.com>
* CreateTime: 3/1/2016 8:11:33 PM
* Description:
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
namespace HelperLibrary.Core.Logging
{
public class Log4NetLogger : ILogger
{
private readonly ILog infoLogger;
private readonly ILog debugLogger;
private readonly ILog warnLogger;
private readonly ILog errorLogger;
private readonly ILog fatalLogger;
public Log4NetLogger(ILog logger) : this(logger, logger, logger, logger, logger)
{
}
public Log4NetLogger(ILog infoLogger, ILog debugLogger, ILog warnLogger, ILog errorLogger, ILog fatalLogger)
{
if (infoLogger == null)
throw new ArgumentNullException(nameof(infoLogger));
if (debugLogger == null)
throw new ArgumentNullException(nameof(debugLogger));
if (warnLogger == null)
throw new ArgumentNullException(nameof(warnLogger));
if (errorLogger == null)
throw new ArgumentNullException(nameof(errorLogger));
if (fatalLogger == null)
throw new ArgumentNullException(nameof(fatalLogger));
this.infoLogger = infoLogger;
this.debugLogger = debugLogger;
this.warnLogger = warnLogger;
this.errorLogger = errorLogger;
this.fatalLogger = fatalLogger;
}
public void Info(string message)
{
infoLogger.Info(message);
}
public void Debug(string message)
{
debugLogger.Debug(message);
}
public void Warn(string message)
{
warnLogger.Warn(message);
}
public void Error(string message)
{
errorLogger.Error(message);
}
public void Fatal(string message)
{
fatalLogger.Fatal(message);
}
}
}
| /*
* FileName: Log4NetLogger.cs
* Author: functionghw<functionghw@hotmail.com>
* CreateTime: 3/1/2016 8:11:33 PM
* Description:
* */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
namespace HelperLibrary.Core.Logging
{
public class Log4NetLogger : ILogger
{
private readonly ILog logger;
public Log4NetLogger(ILog logger)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
this.logger = logger;
}
public void Info(string message)
{
logger.Info(message);
}
public void Debug(string message)
{
logger.Debug(message);
}
public void Warn(string message)
{
logger.Warn(message);
}
public void Error(string message)
{
logger.Error(message);
}
public void Fatal(string message)
{
logger.Fatal(message);
}
}
}
| mit | C# |
f197af4434363fde47f1981739f5aa9188d9d878 | Simplify default ETW providers | Microsoft/xunit-performance,Microsoft/xunit-performance,pharring/xunit-performance,ianhays/xunit-performance,ericeil/xunit-performance,visia/xunit-performance,mmitche/xunit-performance | src/xunit.performance.run/ETWLogging.cs | src/xunit.performance.run/ETWLogging.cs | using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.ProcessDomain;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Xunit.Performance
{
static class ETWLogging
{
static readonly Guid BenchmarkEventSourceGuid = Guid.Parse("A3B447A8-6549-4158-9BAD-76D442A47061");
static readonly ProviderInfo[] RequiredProviders = new ProviderInfo[]
{
new KernelProviderInfo()
{
Keywords = (ulong)KernelTraceEventParser.Keywords.Process
},
new UserProviderInfo()
{
ProviderGuid = BenchmarkEventSourceGuid,
Level = TraceEventLevel.Verbose,
Keywords = ulong.MaxValue,
},
};
public static ProcDomain _loggerDomain = ProcDomain.CreateDomain("Logger", ".\\xunit.performance.logger.exe", runElevated: true);
private class Stopper : IDisposable
{
private string _session;
public Stopper(string session) { _session = session; }
public void Dispose()
{
_loggerDomain.ExecuteAsync(() => Logger.Stop(_session));
}
}
public static async Task<IDisposable> StartAsync(string filename, IEnumerable<ProviderInfo> providers)
{
var allProviders = RequiredProviders.Concat(providers).ToArray();
var sessionName = await _loggerDomain.ExecuteAsync(() => Logger.Start(filename, allProviders, 128));
return new Stopper(sessionName);
}
}
}
| using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.ProcessDomain;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.Xunit.Performance
{
static class ETWLogging
{
static readonly Guid BenchmarkEventSourceGuid = Guid.Parse("A3B447A8-6549-4158-9BAD-76D442A47061");
static readonly ProviderInfo[] RequiredProviders = new ProviderInfo[]
{
new KernelProviderInfo()
{
Keywords = (ulong)KernelTraceEventParser.Keywords.Process | (ulong)KernelTraceEventParser.Keywords.Profile,
StackKeywords = (ulong)KernelTraceEventParser.Keywords.Profile
},
new UserProviderInfo()
{
ProviderGuid = BenchmarkEventSourceGuid,
Level = TraceEventLevel.Verbose,
Keywords = ulong.MaxValue,
},
new UserProviderInfo()
{
ProviderGuid = ClrTraceEventParser.ProviderGuid,
Level = TraceEventLevel.Informational,
Keywords =
(
(ulong)ClrTraceEventParser.Keywords.Jit |
(ulong)ClrTraceEventParser.Keywords.JittedMethodILToNativeMap |
(ulong)ClrTraceEventParser.Keywords.Loader |
(ulong)ClrTraceEventParser.Keywords.Exception |
(ulong)ClrTraceEventParser.Keywords.GC
),
}
};
public static ProcDomain _loggerDomain = ProcDomain.CreateDomain("Logger", ".\\xunit.performance.logger.exe", runElevated: true);
private class Stopper : IDisposable
{
private string _session;
public Stopper(string session) { _session = session; }
public void Dispose()
{
_loggerDomain.ExecuteAsync(() => Logger.Stop(_session));
}
}
public static async Task<IDisposable> StartAsync(string filename, IEnumerable<ProviderInfo> providers)
{
var allProviders = RequiredProviders.Concat(providers).ToArray();
var sessionName = await _loggerDomain.ExecuteAsync(() => Logger.Start(filename, allProviders, 128));
return new Stopper(sessionName);
}
}
}
| mit | C# |
0f059a4031e85b75a92c3830cc951d4c7c4715df | add hashtag to html color | Pavuucek/ArachNGIN,Pavuucek/ArachNGIN | ClassExtensions/StringColors.cs | ClassExtensions/StringColors.cs | using System;
using System.Drawing;
namespace ArachNGIN.ClassExtensions
{
/// <summary>
/// Extension class to convert strings to named colors and vice versa.
/// </summary>
public static class StringColors
{
/// <summary>
/// Gets color from string. Defaults to black
/// </summary>
/// <param name="strColorName">String containing color name.</param>
/// <returns>Color</returns>
public static Color FromString(this string strColorName)
{
if (string.IsNullOrWhiteSpace(strColorName))
strColorName = "Black";
KnownColor knownColor;
if (Enum.TryParse(strColorName, out knownColor))
return Color.FromKnownColor(knownColor);
return ColorTranslator.FromHtml("#" + strColorName);
}
}
} | using System;
using System.Drawing;
namespace ArachNGIN.ClassExtensions
{
/// <summary>
/// Extension class to convert strings to named colors and vice versa.
/// </summary>
public static class StringColors
{
/// <summary>
/// Gets color from string. Defaults to black
/// </summary>
/// <param name="strColorName">String containing color name.</param>
/// <returns>Color</returns>
public static Color FromString(this string strColorName)
{
if (string.IsNullOrWhiteSpace(strColorName))
strColorName = "Black";
KnownColor knownColor;
if (Enum.TryParse(strColorName, out knownColor))
return Color.FromKnownColor(knownColor);
return ColorTranslator.FromHtml(strColorName);
}
}
} | mit | C# |
9d5b265426253aceb8db48db17d649aa5c373546 | Update RuleValidator.cs | KevinWiener/Seatown.Data | Seatown.Data/Validation/Rules/RuleValidator.cs | Seatown.Data/Validation/Rules/RuleValidator.cs | using Seatown.Data.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Seatown.Data.Validation.Rules
{
public class RuleValidator<T> : IValidator<T>
{
private List<RuleSet<T>> m_RuleSets = new List<RuleSet<T>>();
public RuleValidator(params RuleSet<T>[] ruleSets)
{
if (ruleSets != null && ruleSets.Length > 0)
{
this.m_RuleSets.AddRange(ruleSets);
}
}
public IValidationResult[] Validate(params T[] objectsToValidate)
{
var result = new List<IValidationResult>();
if (objectsToValidate?.Length > 0)
{
foreach (T objectToValidate in objectsToValidate)
{
result.Add(this.Validate(objectToValidate));
}
}
return result.ToArray();
}
public IValidationResult Validate(T objectToValidate)
{
bool aggregateResult = true;
foreach (var ruleSet in this.m_RuleSets)
{
aggregateResult &= ruleSet.Evaluate(objectToValidate);
}
return new ValidationResult(aggregateResult, objectToValidate, null);
}
}
}
| using Seatown.Data.Validation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace Seatown.Data.Validation.Rules
{
public class RuleValidator<T> : IValidator<T>
{
private List<RuleSet<T>> m_RuleSets = new List<RuleSet<T>>();
public RuleValidator(params RuleSet<T>[] ruleSets)
{
if (ruleSets != null && ruleSets.Length > 0)
{
this.m_RuleSets.AddRange(ruleSets);
}
}
public IValidationResult Validate(T objectToValidate)
{
bool aggregateResult = true;
foreach (var ruleSet in this.m_RuleSets)
{
aggregateResult &= ruleSet.Evaluate(objectToValidate);
}
return new ValidationResult(aggregateResult, objectToValidate, null);
}
}
}
| mit | C# |
7f18e632110f22d1b1ba4ac2e7dc87246f953f58 | Fix Group serializer | ermau/Tempest.Social | Desktop/Tempest.Social/Group.cs | Desktop/Tempest.Social/Group.cs | //
// Group.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2013 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Tempest.Social
{
public class Group
: INotifyPropertyChanged
{
public Group (int id)
{
Id = id;
}
public Group (int id, string ownerId)
: this (id)
{
if (ownerId == null)
throw new ArgumentNullException ("ownerId");
OwnerId = ownerId;
this.participants.Add (ownerId);
}
public event PropertyChangedEventHandler PropertyChanged;
public int Id
{
get;
private set;
}
public string OwnerId
{
get { return this.ownerId; }
set
{
if (this.ownerId == value)
return;
this.ownerId = value;
OnPropertyChanged();
}
}
public ICollection<string> Participants
{
get { return this.participants; }
}
private readonly ObservableCollection<string> participants = new ObservableCollection<string>();
private string ownerId;
protected virtual void OnPropertyChanged ([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler (this, new PropertyChangedEventArgs (propertyName));
}
}
public class GroupSerializer
: ISerializer<Group>
{
public static readonly GroupSerializer Instance = new GroupSerializer();
public void Serialize (ISerializationContext context, IValueWriter writer, Group element)
{
writer.WriteInt32 (element.Id);
writer.WriteString (element.OwnerId);
writer.WriteEnumerable (context, Serializer<string>.Default, element.Participants);
}
public Group Deserialize (ISerializationContext context, IValueReader reader)
{
var g = new Group (reader.ReadInt32(), reader.ReadString());
foreach (string participant in reader.ReadEnumerable (context, Serializer<string>.Default))
g.Participants.Add (participant);
return g;
}
}
} | //
// Group.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2013 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace Tempest.Social
{
public class Group
: INotifyPropertyChanged
{
public Group (int id)
{
Id = id;
}
public Group (int id, string ownerId)
: this (id)
{
if (ownerId == null)
throw new ArgumentNullException ("ownerId");
OwnerId = ownerId;
this.participants.Add (ownerId);
}
public event PropertyChangedEventHandler PropertyChanged;
public int Id
{
get;
private set;
}
public string OwnerId
{
get { return this.ownerId; }
set
{
if (this.ownerId == value)
return;
this.ownerId = value;
OnPropertyChanged();
}
}
public ICollection<string> Participants
{
get { return this.participants; }
}
private readonly ObservableCollection<string> participants = new ObservableCollection<string>();
private string ownerId;
protected virtual void OnPropertyChanged ([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler (this, new PropertyChangedEventArgs (propertyName));
}
}
public class GroupSerializer
: ISerializer<Group>
{
public static readonly GroupSerializer Instance = new GroupSerializer();
public void Serialize (ISerializationContext context, IValueWriter writer, Group element)
{
writer.WriteInt32 (element.Id);
writer.WriteEnumerable (context, Serializer<string>.Default, element.Participants);
}
public Group Deserialize (ISerializationContext context, IValueReader reader)
{
var g = new Group (reader.ReadInt32(), reader.ReadString());
foreach (string participant in reader.ReadEnumerable (context, Serializer<string>.Default))
g.Participants.Add (participant);
return g;
}
}
} | mit | C# |
247a09d205efe9eabebccceb05521a0c8662502c | remove dead using | fluffynuts/PeanutButter,fluffynuts/PeanutButter,fluffynuts/PeanutButter | source/TestUtils/PeanutButter.TestUtils.AspNetCore.Tests/TestViewDataDictionaryBuilder.cs | source/TestUtils/PeanutButter.TestUtils.AspNetCore.Tests/TestViewDataDictionaryBuilder.cs | using NUnit.Framework;
using NExpect;
using PeanutButter.TestUtils.AspNetCore.Builders;
using static NExpect.Expectations;
namespace PeanutButter.TestUtils.AspNetCore.Tests
{
[TestFixture]
public class TestViewDataDictionaryBuilder
{
[TestFixture]
public class BuildDefault
{
[Test]
public void ShouldBuildAValidViewData()
{
// Arrange
// Act
var result = ViewDataDictionaryBuilder.BuildDefault();
// Assert
Expect(result)
.Not.To.Be.Null();
Expect(result.Model)
.Not.To.Be.Null();
}
}
[Test]
public void ShouldBeAbleToSetModel()
{
// Arrange
var model = new { Id = 1 };
// Act
var result = ViewDataDictionaryBuilder.Create()
.WithModel(model)
.Build();
// Assert
Expect(result.Model)
.To.Be(model);
}
}
} | using NUnit.Framework;
using NExpect;
using PeanutButter.TestUtils.AspNetCore.Builders;
using static NExpect.Expectations;
using static PeanutButter.RandomGenerators.RandomValueGen;
namespace PeanutButter.TestUtils.AspNetCore.Tests
{
[TestFixture]
public class TestViewDataDictionaryBuilder
{
[TestFixture]
public class BuildDefault
{
[Test]
public void ShouldBuildAValidViewData()
{
// Arrange
// Act
var result = ViewDataDictionaryBuilder.BuildDefault();
// Assert
Expect(result)
.Not.To.Be.Null();
Expect(result.Model)
.Not.To.Be.Null();
}
}
[Test]
public void ShouldBeAbleToSetModel()
{
// Arrange
var model = new { Id = 1 };
// Act
var result = ViewDataDictionaryBuilder.Create()
.WithModel(model)
.Build();
// Assert
Expect(result.Model)
.To.Be(model);
}
}
} | bsd-3-clause | C# |
f0d1cb96cd6373313a8ac875098866da3928436d | fix tag names with strange char ending | michael-reichenauer/GitMind | GitMind/Utils/Git/Private/GitTagService.cs | GitMind/Utils/Git/Private/GitTagService.cs | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitTagService : IGitTagService
{
private readonly IGitCmdService gitCmdService;
public GitTagService(IGitCmdService gitCmdService)
{
this.gitCmdService = gitCmdService;
}
public async Task<R<IReadOnlyList<GitTag>>> GetAllTagsAsync(CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync("show-ref -d --tags", ct);
if (result.IsFaulted)
{
if (!(result.ExitCode == 1 && string.IsNullOrEmpty(result.Output)))
{
return R.Error("Failed to list tags", result.AsException());
}
}
IReadOnlyList<GitTag> tags = ParseTags(result);
Log.Info($"Got {tags.Count} tags");
return R.From(tags);
}
public async Task<R<GitTag>> AddTagAsync(string sha, string tagName, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync($"tag {tagName} {sha}", ct);
if (result.IsFaulted)
{
return R.Error($"Failed to add tag {tagName} at {sha}", result.AsException());
}
Log.Info($"Added {tagName} at {sha}");
return new GitTag(sha, tagName);
}
public async Task<R> DeleteTagAsync(string tagName, CancellationToken ct)
{
R<CmdResult2> result = await gitCmdService.RunAsync($"tag --delete {tagName}", ct);
if (result.IsFaulted)
{
return R.Error($"Failed to delete tag {tagName}", result.Exception);
}
Log.Info($"Deleted {tagName}");
return R.Ok;
}
private IReadOnlyList<GitTag> ParseTags(R<CmdResult2> result)
{
List<GitTag> tags = new List<GitTag>();
foreach (string line in result.Value.OutputLines)
{
string sha = line.Substring(0, 40);
string tagName = line.Substring(51);
if (tagName.EndsWith("^{}"))
{
tagName = tagName.Substring(0, tagName.Length - 3);
}
tags.Add(new GitTag(sha, tagName));
}
return tags;
}
}
} | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using GitMind.Utils.OsSystem;
namespace GitMind.Utils.Git.Private
{
internal class GitTagService : IGitTagService
{
private readonly IGitCmdService gitCmdService;
public GitTagService(IGitCmdService gitCmdService)
{
this.gitCmdService = gitCmdService;
}
public async Task<R<IReadOnlyList<GitTag>>> GetAllTagsAsync(CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync("show-ref -d --tags", ct);
if (result.IsFaulted)
{
if (!(result.ExitCode == 1 && string.IsNullOrEmpty(result.Output)))
{
return R.Error("Failed to list tags", result.AsException());
}
}
IReadOnlyList<GitTag> tags = ParseTags(result);
Log.Info($"Got {tags.Count} tags");
return R.From(tags);
}
public async Task<R<GitTag>> AddTagAsync(string sha, string tagName, CancellationToken ct)
{
CmdResult2 result = await gitCmdService.RunCmdAsync($"tag {tagName} {sha}", ct);
if (result.IsFaulted)
{
return R.Error($"Failed to add tag {tagName} at {sha}", result.AsException());
}
Log.Info($"Added {tagName} at {sha}");
return new GitTag(sha, tagName);
}
public async Task<R> DeleteTagAsync(string tagName, CancellationToken ct)
{
R<CmdResult2> result = await gitCmdService.RunAsync($"tag --delete {tagName}", ct);
if (result.IsFaulted)
{
return R.Error($"Failed to delete tag {tagName}", result.Exception);
}
Log.Info($"Deleted {tagName}");
return R.Ok;
}
private IReadOnlyList<GitTag> ParseTags(R<CmdResult2> result)
{
List<GitTag> tags = new List<GitTag>();
foreach (string line in result.Value.OutputLines)
{
string sha = line.Substring(0, 40);
string tagName = line.Substring(51);
tags.Add(new GitTag(sha, tagName));
}
return tags;
}
}
} | mit | C# |
138e28137405235b0af417f3189e86974ce26347 | modify assembly info | wanlitao/HangfireExtension,AGRocks/HangfireExtension,AGRocks/HangfireExtension,AGRocks/HangfireExtension | Hangfire.SQLite/Properties/AssemblyInfo.cs | Hangfire.SQLite/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Hangfire.SQLite")]
[assembly: AssemblyDescription("Hangfire plugin for SQLite Storage")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("GreatBillows")]
[assembly: AssemblyProduct("Hangfire.SQLite")]
[assembly: AssemblyCopyright("Copyright © GreatBillows 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("77c7e1c1-f530-461a-a93e-6ab249a4ebe0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Hangfire.SQLite")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hangfire.SQLite")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("77c7e1c1-f530-461a-a93e-6ab249a4ebe0")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
2bb1662a0af8bf23629411c033e0eed95711ec74 | Remove these enum values that were copy-pasted by mistake. | roblans/ZWave4Net,MiTheFreeman/ZWave4Net | ZWave/CommandClasses/ThermostatFanModeValue.cs | ZWave/CommandClasses/ThermostatFanModeValue.cs | namespace ZWave.CommandClasses
{
public enum ThermostatFanModeValue : byte
{
AutoLow = 0x00,
Low = 0x01,
AutoHigh = 0x02,
High = 0x03,
AutoMedium = 0x04,
Medium = 0x05,
Circulation = 0x06,
HumidityCirculation = 0x07,
LeftAndRight = 0x08,
UpAndDown = 0x09,
Quiet = 0x0A,
ExternalCirculation = 0x0B
};
}
| namespace ZWave.CommandClasses
{
public enum ThermostatFanModeValue : byte
{
AutoLow = 0x00,
Low = 0x01,
AutoHigh = 0x02,
High = 0x03,
AutoMedium = 0x04,
Medium = 0x05,
Circulation = 0x06,
HumidityCirculation = 0x07,
LeftAndRight = 0x08,
UpAndDown = 0x09,
Quiet = 0x0A,
ExternalCirculation = 0x0B,
EnergyCool = 0x0C,
Away = 0x0D,
Reserved = 0x0E,
FullPower = 0x0F,
ManufacturerSpecific = 0x1F
};
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.