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 |
|---|---|---|---|---|---|---|---|---|
f87f710eec948b6e3f778f894f340d619b652e80 | Update App.xaml.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D/App.xaml.cs | src/Draw2D/App.xaml.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using Avalonia.Markup.Xaml;
using Draw2D.Editor;
using Draw2D.Views;
namespace Draw2D
{
public class App : Application
{
[STAThread]
static void Main(string[] args)
{
BuildAvaloniaApp().Start(AppMain, args);
}
static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new ContainerEditor(),
};
app.Run(window);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.With(new Win32PlatformOptions { AllowEglInitialization = true })
.With(new X11PlatformOptions { UseGpu = true, UseEGL = true })
.With(new AvaloniaNativePlatformOptions { UseGpu = true })
.UseSkia()
.LogToDebug();
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using Avalonia.Markup.Xaml;
using Draw2D.Editor;
using Draw2D.Views;
namespace Draw2D
{
public class App : Application
{
[STAThread]
static void Main(string[] args)
{
BuildAvaloniaApp().Start(AppMain, args);
}
static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new ContainerEditor(),
};
app.Run(window);
}
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.With(new Win32PlatformOptions { AllowEglInitialization = true })
.With(new X11PlatformOptions { UseGpu = true, UseEGL = false })
.With(new AvaloniaNativePlatformOptions { UseGpu = true })
.UseSkia()
.LogToDebug();
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| mit | C# |
8714b2cee4364f0f5602e54c19cfbc2109cee407 | Support "\r\n" line endings | oocx/acme.net | src/Oocx.Asn1PKCS/Extensions.cs | src/Oocx.Asn1PKCS/Extensions.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Oocx.Asn1PKCS.Asn1BaseTypes;
namespace Oocx.Asn1PKCS
{
public static class PEMExtensions
{
public const string RSAPrivateKey = "RSA PRIVATE KEY";
public const string PrivateKey = "PRIVATE KEY";
public static string EncodeAsPEM(this byte[] data, string type)
{
var base64 = Convert.ToBase64String(data);
string base64Lines = "";
for (int i = 0; i < base64.Length; i += 64)
{
base64Lines += base64.Substring(i, Math.Min(64, base64.Length - i)) + "\n";
}
var pem = $"-----BEGIN {type}-----\n{base64Lines}-----END {type}-----";
return pem;
}
public static byte[] DecodePEM(this Stream pem, string type)
{
var lines = new List<string>();
string line;
using (var sr = new StreamReader(pem))
{
while ((line = sr.ReadLine()) != null)
{
if (string.IsNullOrEmpty(line)) continue;
lines.Add(line);
}
}
if (!$"-----BEGIN {type}-----".Equals(lines[0]))
{
throw new InvalidDataException($"The PEM file should start with -----BEGIN {type}-----");
}
if (!"-----END PRIVATE KEY-----".Equals(lines[lines.Count - 1]))
{
throw new InvalidDataException($"The PEM file should end with -----END {type}-----");
}
var base64 = string.Join("", lines.Skip(1).Take(lines.Count - 2));
var der = base64.Base64UrlDecode();
return der;
}
}
}
| using System;
using System.IO;
using System.Linq;
using Oocx.Asn1PKCS.Asn1BaseTypes;
namespace Oocx.Asn1PKCS
{
public static class PEMExtensions
{
public const string RSAPrivateKey = "RSA PRIVATE KEY";
public const string PrivateKey = "PRIVATE KEY";
public static string EncodeAsPEM(this byte[] data, string type)
{
var base64 = Convert.ToBase64String(data);
string base64Lines = "";
for (int i = 0; i < base64.Length; i += 64)
{
base64Lines += base64.Substring(i, Math.Min(64, base64.Length - i)) + "\n";
}
var pem = $"-----BEGIN {type}-----\n{base64Lines}-----END {type}-----";
return pem;
}
public static byte[] DecodePEM(this Stream pem, string type)
{
string[] lines;
using (var sr = new StreamReader(pem))
{
lines = sr.ReadToEnd().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
if (!$"-----BEGIN {type}-----".Equals(lines.First()))
{
throw new InvalidDataException($"The PEM file should start with -----BEGIN {type}-----");
}
if (!"-----END PRIVATE KEY-----".Equals(lines.Last()))
{
throw new InvalidDataException($"The PEM file should end with -----END {type}-----");
}
var base64 = string.Join("", lines.Skip(1).Take(lines.Length - 2));
var der = base64.Base64UrlDecode();
return der;
}
}
}
| mit | C# |
06095cd2c8d85fcbdbdb486277dda4efb830ceed | Add DisableEncoding to ITemplatePage #106 | toddams/RazorLight,toddams/RazorLight | src/RazorLight/ITemplatePage.cs | src/RazorLight/ITemplatePage.cs | using Microsoft.AspNetCore.Html;
using RazorLight.Internal;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RazorLight
{
public interface ITemplatePage
{
void SetModel(object model);
/// <summary>
/// Gets or sets the view context of the rendering template.
/// </summary>
PageContext PageContext { get; set; }
/// <summary>
/// Gets or sets the body content.
/// </summary>
IHtmlContent BodyContent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether encoding is disabled for the entire template
/// </summary>
bool DisableEncoding { get; set; }
/// <summary>
/// Gets or sets the unique key of the current template
/// </summary>
string Key { get; set; }
/// <summary>
/// Gets or sets a flag that determines if the layout of this page is being rendered.
/// </summary>
/// <remarks>
/// Sections defined in a page are deferred and executed as part of the layout page.
/// When this flag is set, all write operations performed by the page are part of a
/// section being rendered.
/// </remarks>
bool IsLayoutBeingRendered { get; set; }
/// <summary>
/// Gets or sets the key of a layout page.
/// </summary>
string Layout { get; set; }
/// <summary>
/// Gets or sets the sections that can be rendered by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> PreviousSectionWriters { get; set; }
/// <summary>
/// Gets the sections that are defined by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> SectionWriters { get; }
/// <summary>
/// Renders the page and writes the output to the <see cref="IPageContext.Writer"/> />.
/// </summary>
/// <returns>A task representing the result of executing the page.</returns>
Task ExecuteAsync();
Func<string, object, Task> IncludeFunc { get; set; }
void EnsureRenderedBodyOrSections();
}
}
| using Microsoft.AspNetCore.Html;
using RazorLight.Internal;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RazorLight
{
public interface ITemplatePage
{
void SetModel(object model);
/// <summary>
/// Gets or sets the view context of the rendering template.
/// </summary>
PageContext PageContext { get; set; }
/// <summary>
/// Gets or sets the body content.
/// </summary>
IHtmlContent BodyContent { get; set; }
/// <summary>
/// Gets or sets the unique key of the current template
/// </summary>
string Key { get; set; }
/// <summary>
/// Gets or sets a flag that determines if the layout of this page is being rendered.
/// </summary>
/// <remarks>
/// Sections defined in a page are deferred and executed as part of the layout page.
/// When this flag is set, all write operations performed by the page are part of a
/// section being rendered.
/// </remarks>
bool IsLayoutBeingRendered { get; set; }
/// <summary>
/// Gets or sets the key of a layout page.
/// </summary>
string Layout { get; set; }
/// <summary>
/// Gets or sets the sections that can be rendered by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> PreviousSectionWriters { get; set; }
/// <summary>
/// Gets the sections that are defined by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> SectionWriters { get; }
/// <summary>
/// Renders the page and writes the output to the <see cref="IPageContext.Writer"/> />.
/// </summary>
/// <returns>A task representing the result of executing the page.</returns>
Task ExecuteAsync();
Func<string, object, Task> IncludeFunc { get; set; }
void EnsureRenderedBodyOrSections();
}
}
| apache-2.0 | C# |
fcbac809821c0e230e2485cc48ec5ab544908949 | rename slack chanel & add github discussions (#566) | reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website | input/_Navbar.cshtml | input/_Navbar.cshtml | @{
var pages = new Dictionary<string, string>
{
{ "Blog", Context.GetLink("blog") },
{ "Training", Context.GetLink("training") },
{ "Book", Context.GetLink("book") },
{ "Documentation", Context.GetLink("docs") },
{ "Extensions", Context.GetLink("reactive-extensions") },
{ "API", Context.GetLink("api") },
{ "Contribute", Context.GetLink("contribute") },
{ "Discussions", "https://github.com/reactiveui/ReactiveUI/discussions" },
{ "Slack", Context.GetLink("slack") },
{ "Support", Context.GetLink("support") },
};
foreach(var currentPage in pages)
{
var activeClass = Context.GetLink(Document).StartsWith(currentPage.Value) ? "active" : null;
<li class="@activeClass">
<a href="@currentPage.Value">@Html.Raw(currentPage.Key)</a>
</li>
}
<li>
<a class="github" href="https://github.com/reactiveui/reactiveui">
<img src="@Context.GetLink("/assets/img/GitHub-Mark-32px.png")" alt="GitHub" />
</a>
</li>
}
| @{
var pages = new Dictionary<string, string>
{
{ "Blog", Context.GetLink("blog") },
{ "Training", Context.GetLink("training") },
{ "Book", Context.GetLink("book") },
{ "Documentation", Context.GetLink("docs") },
{ "Extensions", Context.GetLink("reactive-extensions") },
{ "API", Context.GetLink("api") },
{ "Contribute", Context.GetLink("contribute") },
{ "Discuss", Context.GetLink("slack") },
{ "Support", Context.GetLink("support") },
};
foreach(var currentPage in pages)
{
var activeClass = Context.GetLink(Document).StartsWith(currentPage.Value) ? "active" : null;
<li class="@activeClass">
<a href="@currentPage.Value">@Html.Raw(currentPage.Key)</a>
</li>
}
<li>
<a class="github" href="https://github.com/reactiveui/reactiveui">
<img src="@Context.GetLink("/assets/img/GitHub-Mark-32px.png")" alt="GitHub" />
</a>
</li>
}
| mit | C# |
d6cdde552daa84e04a76e6bf1c1d61872002c0bb | Add comment explaining dispose logic | smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,2yangk23/osu,ZLima12/osu,ZLima12/osu,johnneijzen/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,ppy/osu,EVAST9919/osu,2yangk23/osu | osu.Game/Rulesets/RulesetConfigCache.cs | osu.Game/Rulesets/RulesetConfigCache.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Concurrent;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
namespace osu.Game.Rulesets
{
/// <summary>
/// A cache that provides a single <see cref="IRulesetConfigManager"/> per-ruleset.
/// This is done to support referring to and updating ruleset configs from multiple locations in the absence of inter-config bindings.
/// </summary>
public class RulesetConfigCache : Component
{
private readonly ConcurrentDictionary<int, IRulesetConfigManager> configCache = new ConcurrentDictionary<int, IRulesetConfigManager>();
private readonly SettingsStore settingsStore;
public RulesetConfigCache(SettingsStore settingsStore)
{
this.settingsStore = settingsStore;
}
/// <summary>
/// Retrieves the <see cref="IRulesetConfigManager"/> for a <see cref="Ruleset"/>.
/// </summary>
/// <param name="ruleset">The <see cref="Ruleset"/> to retrieve the <see cref="IRulesetConfigManager"/> for.</param>
/// <returns>The <see cref="IRulesetConfigManager"/> defined by <paramref name="ruleset"/>, null if <paramref name="ruleset"/> doesn't define one.</returns>
/// <exception cref="InvalidOperationException">If <paramref name="ruleset"/> doesn't have a valid <see cref="RulesetInfo.ID"/>.</exception>
public IRulesetConfigManager GetConfigFor(Ruleset ruleset)
{
if (ruleset.RulesetInfo.ID == null)
return null;
return configCache.GetOrAdd(ruleset.RulesetInfo.ID.Value, _ => ruleset.CreateConfig(settingsStore));
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
// ensures any potential database operations are finalised before game destruction.
foreach (var c in configCache.Values)
(c as IDisposable)?.Dispose();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Concurrent;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Rulesets.Configuration;
namespace osu.Game.Rulesets
{
/// <summary>
/// A cache that provides a single <see cref="IRulesetConfigManager"/> per-ruleset.
/// This is done to support referring to and updating ruleset configs from multiple locations in the absence of inter-config bindings.
/// </summary>
public class RulesetConfigCache : Component
{
private readonly ConcurrentDictionary<int, IRulesetConfigManager> configCache = new ConcurrentDictionary<int, IRulesetConfigManager>();
private readonly SettingsStore settingsStore;
public RulesetConfigCache(SettingsStore settingsStore)
{
this.settingsStore = settingsStore;
}
/// <summary>
/// Retrieves the <see cref="IRulesetConfigManager"/> for a <see cref="Ruleset"/>.
/// </summary>
/// <param name="ruleset">The <see cref="Ruleset"/> to retrieve the <see cref="IRulesetConfigManager"/> for.</param>
/// <returns>The <see cref="IRulesetConfigManager"/> defined by <paramref name="ruleset"/>, null if <paramref name="ruleset"/> doesn't define one.</returns>
/// <exception cref="InvalidOperationException">If <paramref name="ruleset"/> doesn't have a valid <see cref="RulesetInfo.ID"/>.</exception>
public IRulesetConfigManager GetConfigFor(Ruleset ruleset)
{
if (ruleset.RulesetInfo.ID == null)
return null;
return configCache.GetOrAdd(ruleset.RulesetInfo.ID.Value, _ => ruleset.CreateConfig(settingsStore));
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
foreach (var c in configCache.Values)
(c as IDisposable)?.Dispose();
}
}
}
| mit | C# |
4f62ebc8ca59e38cccea9fb7214fee17aa5424ab | Tweak button styling | mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection | src/Cash-Flow-Projection/Views/Home/Index.cshtml | src/Cash-Flow-Projection/Views/Home/Index.cshtml | @model Cash_Flow_Projection.Models.Dashboard
@{
ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Balance", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="text" name="balance" placeholder="Set Balance" />
<button type="submit">Set</button>
}
<table class="table table-striped">
@foreach (var entry in Model.Entries.OrderBy(_ => _.Date))
{
<tr>
<td>@Html.DisplayFor(_ => entry.Date)</td>
<td>@Html.DisplayFor(_ => entry.Description)</td>
<td>@Html.DisplayFor(_ => entry.Amount)</td>
<td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td>
<td>
<div class="input-group" role="group">
@using (Html.BeginForm("Postpone", "Home", new { entry.id }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-default">Postpone</button>
}
@using (Html.BeginForm("Delete", "Home", new { entry.id }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-danger">Delete</button>
}
</div>
</td>
</tr>
}
</table> | @model Cash_Flow_Projection.Models.Dashboard
@{
ViewData["Title"] = "Home Page";
}
@using (Html.BeginForm("Balance", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<input type="text" name="balance" placeholder="Set Balance" />
<button type="submit">Set</button>
}
<table class="table table-striped">
@foreach (var entry in Model.Entries.OrderBy(_ => _.Date))
{
<tr>
<td>@Html.DisplayFor(_ => entry.Date)</td>
<td>@Html.DisplayFor(_ => entry.Description)</td>
<td>@Html.DisplayFor(_ => entry.Amount)</td>
<td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td>
<td>
@using (Html.BeginForm("Postpone", "Home", new { entry.id }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="submit">Postpone</button>
}
@using (Html.BeginForm("Delete", "Home", new { entry.id }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<button type="submit">Delete</button>
}
</td>
</tr>
}
</table> | mit | C# |
d030dea1b1b9760c918d1da46aac9dffeb7340e1 | Optimize query for server time. (not throwing exception) | sergeyzwezdin/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,persi12/Hangfire.Mongo,sergun/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,sergun/Hangfire.Mongo,persi12/Hangfire.Mongo | src/Hangfire.Mongo/MongoUtils/MongoExtensions.cs | src/Hangfire.Mongo/MongoUtils/MongoExtensions.cs | using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
namespace Hangfire.Mongo.MongoUtils
{
/// <summary>
/// Helper utilities to work with Mongo database
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="database">Mongo database</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this IMongoDatabase database)
{
dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
object localTime;
if (((IDictionary<string, object>)serverStatus).TryGetValue("localTime", out localTime))
{
return ((DateTime)localTime).ToUniversalTime();
}
return DateTime.UtcNow;
}
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="dbContext">Hangfire database context</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
{
return GetServerTimeUtc(dbContext.Database);
}
}
} | using Hangfire.Mongo.Database;
using MongoDB.Driver;
using System;
using Hangfire.Mongo.Helpers;
using MongoDB.Bson;
namespace Hangfire.Mongo.MongoUtils
{
/// <summary>
/// Helper utilities to work with Mongo database
/// </summary>
public static class MongoExtensions
{
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="database">Mongo database</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this IMongoDatabase database)
{
try
{
dynamic serverStatus = AsyncHelper.RunSync(() => database.RunCommandAsync<dynamic>(new BsonDocument("isMaster", 1)));
return ((DateTime)serverStatus.localTime).ToUniversalTime();
}
catch (MongoException)
{
return DateTime.UtcNow;
}
}
/// <summary>
/// Retreives server time in UTC zone
/// </summary>
/// <param name="dbContext">Hangfire database context</param>
/// <returns>Server time</returns>
public static DateTime GetServerTimeUtc(this HangfireDbContext dbContext)
{
return GetServerTimeUtc(dbContext.Database);
}
}
} | mit | C# |
9b319e6e2703cb8df1ab3d35a17ecfcbfdc38aa1 | Fix path to bootstrap (#1831) | joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net | src/JoinRpg.Portal/Views/Shared/_Layout.cshtml | src/JoinRpg.Portal/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - JoinRpg.Portal</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/twitter-bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="~/lib/bootstrap-datepicker/css/bootstrap-datepicker.css" />
<link rel="stylesheet" href="~/_content/JoinRpg.WebComponents/lib/bootstrap-select/css/bootstrap-select.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/css/multicontrol.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="~/lib/twitter-bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap-datepicker/css/bootstrap-datepicker.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap-select/css/bootstrap-select.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/multicontrol.css" asp-append-version="true" />
</environment>
<link rel="stylesheet" href="~/css/components.css" />
<base href="/" />
<link href="https://fonts.googleapis.com/css?family=Roboto:400,400i,700,700i&subset=cyrillic" rel="stylesheet" />
@RenderSection("styles", required: false)
<environment include="Development">
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/lib/twitter-bootstrap/js/bootstrap.js"></script>
<script src="~/lib/bootstrap-select/js/bootstrap-select.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/jquery/jquery.min.js"></script>
<script src="~/lib/twitter-bootstrap/js/bootstrap.min.js"></script>
<script src="~/lib/bootstrap-select/js/bootstrap-select.min.js"></script>
</environment>
<partial name="_ValidationScriptsPartial" />
</head>
<body>
<vc:main-menu>
</vc:main-menu>
@if (ViewBag.ProjectId != null)
{
<vc:project-menu>
</vc:project-menu>
}
<div class="container body-content">
@RenderBody()
<partial name="Layout/_FooterPartial" />
</div>
<script src="~/Scripts/multicontrol.js"></script>
<script src="~/lib/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
<script src="~/Scripts/jquery.popconfirm.js" type="text/javascript"></script>
<script src="~/Scripts/edit-funcs.js" type="text/javascript"></script>
@RenderSection("Scripts", required: false)
<partial name="Layout/_YandexPartial" />
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - JoinRpg.Portal</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/twitter-bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="~/lib/bootstrap-datepicker/css/bootstrap-datepicker.css" />
<link rel="stylesheet" href="~/_content/JoinRpg.WebComponents/lib/bootstrap-select/css/bootstrap-select.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/css/multicontrol.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="~/lib/bootstrap/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap-datepicker/css/bootstrap-datepicker.min.css" />
<link rel="stylesheet" href="~/lib/bootstrap-select/css/bootstrap-select.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/css/multicontrol.css" asp-append-version="true" />
</environment>
<link rel="stylesheet" href="~/css/components.css" />
<base href="/" />
<link href="https://fonts.googleapis.com/css?family=Roboto:400,400i,700,700i&subset=cyrillic" rel="stylesheet" />
@RenderSection("styles", required: false)
<environment include="Development">
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/lib/twitter-bootstrap/js/bootstrap.js"></script>
<script src="~/lib/bootstrap-select/js/bootstrap-select.js"></script>
</environment>
<environment exclude="Development">
<script src="~/lib/jquery/jquery.min.js"></script>
<script src="~/lib/twitter-bootstrap/js/bootstrap.min.js"></script>
<script src="~/lib/bootstrap-select/js/bootstrap-select.min.js"></script>
</environment>
<partial name="_ValidationScriptsPartial" />
</head>
<body>
<vc:main-menu>
</vc:main-menu>
@if (ViewBag.ProjectId != null)
{
<vc:project-menu>
</vc:project-menu>
}
<div class="container body-content">
@RenderBody()
<partial name="Layout/_FooterPartial" />
</div>
<script src="~/Scripts/multicontrol.js"></script>
<script src="~/lib/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
<script src="~/Scripts/jquery.popconfirm.js" type="text/javascript"></script>
<script src="~/Scripts/edit-funcs.js" type="text/javascript"></script>
@RenderSection("Scripts", required: false)
<partial name="Layout/_YandexPartial" />
</body>
</html>
| mit | C# |
97107ea7a8c093579c520b1006375dde09a94fac | Fix EnumNameTransformers.UpperSnake does not handle underscore correctly. | msgpack/msgpack-cli,msgpack/msgpack-cli | src/MsgPack/Serialization/KeyNameTransformers.cs | src/MsgPack/Serialization/KeyNameTransformers.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2016 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Text;
namespace MsgPack.Serialization
{
internal static class KeyNameTransformers
{
public static readonly Func<string, string> AsIs = key => key;
public static string ToLowerCamel( string mayBeUpperCamel )
{
if ( String.IsNullOrEmpty( mayBeUpperCamel ) )
{
return mayBeUpperCamel;
}
if ( !Char.IsUpper( mayBeUpperCamel[ 0 ] ) )
{
return mayBeUpperCamel;
}
var buffer = new StringBuilder( mayBeUpperCamel.Length );
buffer.Append( Char.ToLowerInvariant( mayBeUpperCamel[ 0 ] ) );
if ( mayBeUpperCamel.Length > 1 )
{
buffer.Append( mayBeUpperCamel, 1, mayBeUpperCamel.Length - 1 );
}
return buffer.ToString();
}
public static string ToUpperSnake( string mayBeUpperCamel )
{
if ( String.IsNullOrEmpty( mayBeUpperCamel ) )
{
return mayBeUpperCamel;
}
var buffer = new StringBuilder( mayBeUpperCamel.Length * 2 );
char previous = '\0';
int index = 0;
for ( ; index < mayBeUpperCamel.Length; index++ )
{
var c = mayBeUpperCamel[ index ];
if ( Char.IsUpper( c ) )
{
buffer.Append( c );
previous = c;
}
else
{
buffer.Append( Char.ToUpperInvariant( c ) );
previous = c;
index++;
break;
}
}
for ( ; index < mayBeUpperCamel.Length; index++ )
{
var c = mayBeUpperCamel[ index ];
if ( Char.IsUpper( c ) )
{
if ( previous != '_' )
{
buffer.Append( '_' );
}
buffer.Append( c );
previous = c;
}
else
{
buffer.Append( Char.ToUpperInvariant( c ) );
previous = c;
}
}
return buffer.ToString();
}
}
} | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2016 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.Text;
namespace MsgPack.Serialization
{
internal static class KeyNameTransformers
{
public static readonly Func<string, string> AsIs = key => key;
public static string ToLowerCamel( string mayBeUpperCamel )
{
if ( String.IsNullOrEmpty( mayBeUpperCamel ) )
{
return mayBeUpperCamel;
}
if ( !Char.IsUpper( mayBeUpperCamel[ 0 ] ) )
{
return mayBeUpperCamel;
}
var buffer = new StringBuilder( mayBeUpperCamel.Length );
buffer.Append( Char.ToLowerInvariant( mayBeUpperCamel[ 0 ] ) );
if ( mayBeUpperCamel.Length > 1 )
{
buffer.Append( mayBeUpperCamel, 1, mayBeUpperCamel.Length - 1 );
}
return buffer.ToString();
}
public static string ToUpperSnake( string mayBeUpperCamel )
{
if ( String.IsNullOrEmpty( mayBeUpperCamel ) )
{
return mayBeUpperCamel;
}
var buffer = new StringBuilder( mayBeUpperCamel.Length * 2 );
int index = 0;
for ( ; index < mayBeUpperCamel.Length; index++ )
{
var c = mayBeUpperCamel[ index ];
if ( Char.IsUpper( c ) )
{
buffer.Append( c );
}
else
{
buffer.Append( Char.ToUpperInvariant( c ) );
index++;
break;
}
}
for ( ; index < mayBeUpperCamel.Length; index++ )
{
var c = mayBeUpperCamel[ index ];
if ( Char.IsUpper( c ) )
{
buffer.Append( '_' );
buffer.Append( c );
}
else
{
buffer.Append( Char.ToUpperInvariant( c ) );
}
}
return buffer.ToString();
}
}
} | apache-2.0 | C# |
4c8b439c0025e7bec773b9617cb82dfa97db6f13 | disable auto properties. | jwChung/TfsBuilder | test/WebApplication.UnitTest/TheoremAttribute.cs | test/WebApplication.UnitTest/TheoremAttribute.cs | using System;
using System.Reflection;
using Jwc.Experiment;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Kernel;
using Ploeh.AutoFixture.Xunit;
namespace Jwc.TfsBuilder.WebApplication
{
/// <summary>
/// 이 attribute는 method위에 선언되어 해당 method가 test case라는 것을
/// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도
/// 사용될 수 있다.
/// Parameterized test에 대해 이 attribute는 AutoFixture library를 이용하여
/// auto data기능을 제공한다.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class TheoremAttribute : NaiveTheoremAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TheoremAttribute"/> class.
/// </summary>
public TheoremAttribute() : base(CreateTestFixture)
{
}
private static ITestFixture CreateTestFixture(MethodInfo testMethod)
{
var fixture = CreateFixture();
foreach (var parameter in testMethod.GetParameters())
{
Customize(fixture, parameter);
}
return new TestFixtureAdapter(new SpecimenContext(fixture));
}
private static IFixture CreateFixture()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization());
fixture.OmitAutoProperties = true;
return fixture;
}
private static void Customize(IFixture fixture, ParameterInfo parameter)
{
foreach (CustomizeAttribute customAttribute
in parameter.GetCustomAttributes(typeof(CustomizeAttribute), false))
{
var customization = customAttribute.GetCustomization(parameter);
fixture.Customize(customization);
}
}
}
} | using System;
using System.Reflection;
using Jwc.Experiment;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Kernel;
using Ploeh.AutoFixture.Xunit;
namespace Jwc.TfsBuilder.WebApplication
{
/// <summary>
/// 이 attribute는 method위에 선언되어 해당 method가 test case라는 것을
/// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도
/// 사용될 수 있다.
/// Parameterized test에 대해 이 attribute는 AutoFixture library를 이용하여
/// auto data기능을 제공한다.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class TheoremAttribute : NaiveTheoremAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="TheoremAttribute"/> class.
/// </summary>
public TheoremAttribute() : base(CreateTestFixture)
{
}
private static ITestFixture CreateTestFixture(MethodInfo testMethod)
{
var fixture = CreateFixture();
foreach (var parameter in testMethod.GetParameters())
{
Customize(fixture, parameter);
}
return new TestFixtureAdapter(new SpecimenContext(fixture));
}
private static IFixture CreateFixture()
{
return new Fixture().Customize(new AutoMoqCustomization());
}
private static void Customize(IFixture fixture, ParameterInfo parameter)
{
foreach (CustomizeAttribute customAttribute
in parameter.GetCustomAttributes(typeof(CustomizeAttribute), false))
{
var customization = customAttribute.GetCustomization(parameter);
fixture.Customize(customization);
}
}
}
} | mit | C# |
cd86a29695a8d6afc48d736890cd74211d01f620 | Fix the using. Sometimes atom can be... | brycekbargar/Nilgiri,brycekbargar/Nilgiri | Nilgiri.Tests/Examples/Should/NotBeOk.cs | Nilgiri.Tests/Examples/Should/NotBeOk.cs | namespace Nilgiri.Examples
{
using Xunit;
using Nilgiri.Tests.Common;
using static Nilgiri.ShouldStyle;
public partial class ExampleOf_Should
{
public class Not_Be_Ok
{
[Fact]
public void Int32()
{
_(0).Should.Not.Be.Ok();
_(() => 0).Should.Not.Be.Ok();
}
[Fact]
public void Nullable()
{
_((bool?)false).Should.Not.Be.Ok();
_(() => (bool?)false).Should.Not.Be.Ok();
}
[Fact]
public void String()
{
_((string)null).Should.Not.Be.Ok();
_(() => (string)null).Should.Not.Be.Ok();
_(System.String.Empty).Should.Not.Be.Ok();
_(() => System.String.Empty).Should.Not.Be.Ok();
_("").Should.Not.Be.Ok();
_(() => "").Should.Not.Be.Ok();
_(" ").Should.Not.Be.Ok();
_(() => " ").Should.Not.Be.Ok();
}
[Fact]
public void ReferenceTypes()
{
_((StubClass)null).Should.Not.Be.Ok();
_(() => (StubClass)null).Should.Not.Be.Ok();
}
}
}
}
| namespace Nilgiri.Examples
{
using Xunit;
using Nilgiri.Tests.Common;
using static Nilgiri.ExpectStyle;
public partial class ExampleOf_Should
{
public class Not_Be_Ok
{
[Fact]
public void Int32()
{
_(0).Should.Not.Be.Ok();
_(() => 0).Should.Not.Be.Ok();
}
[Fact]
public void Nullable()
{
_((bool?)false).Should.Not.Be.Ok();
_(() => (bool?)false).Should.Not.Be.Ok();
}
[Fact]
public void String()
{
_((string)null).Should.Not.Be.Ok();
_(() => (string)null).Should.Not.Be.Ok();
_(System.String.Empty).Should.Not.Be.Ok();
_(() => System.String.Empty).Should.Not.Be.Ok();
_("").Should.Not.Be.Ok();
_(() => "").Should.Not.Be.Ok();
_(" ").Should.Not.Be.Ok();
_(() => " ").Should.Not.Be.Ok();
}
[Fact]
public void ReferenceTypes()
{
_((StubClass)null).Should.Not.Be.Ok();
_(() => (StubClass)null).Should.Not.Be.Ok();
}
}
}
}
| mit | C# |
a117b49b056b3ff5e0408737ccaf93fcd53b9fc1 | Fix in location resolving. | Corniel/DeadCode | test/DeadCode.UnitTests/VerifierTest.cs | test/DeadCode.UnitTests/VerifierTest.cs | using DeadCode.CodeAnalysis;
using NUnit.Framework;
using System;
using System.IO;
namespace DeadCode.UnitTests
{
public class VerifierTest
{
[Test]
public void Verify_XampleSln()
{
var root = new FileInfo(GetType().Assembly.Location).Directory;
var solution = new FileInfo(Path.Combine(root.FullName, @"..\..\..\..\xample\Xample.sln"));
var parts = new CodeParts();
var context = new VerifyContext(solution, parts);
Verifier.Verify(context);
foreach (var part in parts)
{
Console.WriteLine($"{part}, {part.Count}");
}
}
}
}
| using DeadCode.CodeAnalysis;
using NUnit.Framework;
using System;
using System.IO;
namespace DeadCode.UnitTests
{
public class VerifierTest
{
[Test]
public void Verify_XampleSln()
{
var solution = new FileInfo(@"xample\Xample.sln");
var parts = new CodeParts();
var context = new VerifyContext(solution, parts);
Verifier.Verify(context);
foreach (var part in parts)
{
Console.WriteLine($"{part}, {part.Count}");
}
}
}
}
| mit | C# |
406208e580e69968253af51c86cb3a370815aa35 | Fix failing daemon test build_aggregate_multiple_projections (#2024) | ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten | src/Marten/Events/Daemon/ShardStatusWatcher.cs | src/Marten/Events/Daemon/ShardStatusWatcher.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Marten.Events.Daemon
{
/// <summary>
/// Used mostly by tests to listen for expected shard events or progress
/// </summary>
internal class ShardStatusWatcher: IObserver<ShardState>
{
private readonly IDisposable _unsubscribe;
private readonly Func<ShardState, bool> _condition;
private readonly TaskCompletionSource<ShardState> _completion;
public ShardStatusWatcher(ShardStateTracker tracker, ShardState expected, TimeSpan timeout)
{
_condition = x => x.Equals(expected);
_completion = new TaskCompletionSource<ShardState>();
var timeout1 = new CancellationTokenSource(timeout);
timeout1.Token.Register(() =>
{
_completion.TrySetException(new TimeoutException(
$"Shard {expected.ShardName} did not reach sequence number {expected.Sequence} in the time allowed"));
});
_unsubscribe = tracker.Subscribe(this);
}
public ShardStatusWatcher(string description, Func<ShardState, bool> condition, ShardStateTracker tracker, TimeSpan timeout)
{
_condition = condition;
_completion = new TaskCompletionSource<ShardState>();
var timeout1 = new CancellationTokenSource(timeout);
timeout1.Token.Register(() =>
{
_completion.TrySetException(new TimeoutException(
$"{description} was not detected in the time allowed"));
});
_unsubscribe = tracker.Subscribe(this);
}
public Task<ShardState> Task => _completion.Task;
public void OnCompleted()
{
}
public void OnError(Exception error)
{
_completion.SetException(error);
}
public void OnNext(ShardState value)
{
if (_condition(value))
{
_completion.SetResult(value);
_unsubscribe.Dispose();
}
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace Marten.Events.Daemon
{
/// <summary>
/// Used mostly by tests to listen for expected shard events or progress
/// </summary>
internal class ShardStatusWatcher: IObserver<ShardState>
{
private readonly IDisposable _unsubscribe;
private readonly Func<ShardState, bool> _condition;
private readonly TaskCompletionSource<ShardState> _completion;
public ShardStatusWatcher(ShardStateTracker tracker, ShardState expected, TimeSpan timeout)
{
_condition = x => x.Equals(expected);
_completion = new TaskCompletionSource<ShardState>(TaskCreationOptions.RunContinuationsAsynchronously);
var timeout1 = new CancellationTokenSource(timeout);
timeout1.Token.Register(() =>
{
_completion.TrySetException(new TimeoutException(
$"Shard {expected.ShardName} did not reach sequence number {expected.Sequence} in the time allowed"));
});
_unsubscribe = tracker.Subscribe(this);
}
public ShardStatusWatcher(string description, Func<ShardState, bool> condition, ShardStateTracker tracker, TimeSpan timeout)
{
_condition = condition;
_completion = new TaskCompletionSource<ShardState>(TaskCreationOptions.RunContinuationsAsynchronously);
var timeout1 = new CancellationTokenSource(timeout);
timeout1.Token.Register(() =>
{
_completion.TrySetException(new TimeoutException(
$"{description} was not detected in the time allowed"));
});
_unsubscribe = tracker.Subscribe(this);
}
public Task<ShardState> Task => _completion.Task;
public void OnCompleted()
{
}
public void OnError(Exception error)
{
_completion.SetException(error);
}
public void OnNext(ShardState value)
{
if (_condition(value))
{
_completion.SetResult(value);
_unsubscribe.Dispose();
}
}
}
}
| mit | C# |
2e093c1cf35311419d6e5b4598661a4d4f618157 | Update MorpheusModification.cs | rmillikin/MetaMorpheus,hoffmann4/MetaMorpheus,lonelu/MetaMorpheus,zrolfs/MetaMorpheus,smith-chem-wisc/MetaMorpheus,XRSHEERAN/MetaMorpheus,lschaffer2/MetaMorpheus | OldInternalLogic/MorpheusModification.cs | OldInternalLogic/MorpheusModification.cs | using Chemistry;
namespace OldInternalLogic
{
public class MorpheusModification
{
#region Public Constructors
public MorpheusModification(string nameInXml, ModificationType type, char aminoAcid, string database, string databaseName, char prevAA, double alternativeMassShift, bool labile, ChemicalFormula cf)
{
this.NameInXml = nameInXml;
ThisModificationType = type;
AminoAcid = aminoAcid;
MonoisotopicMassShift = cf.MonoisotopicMass;
Database = database;
DatabaseName = databaseName;
PrevAminoAcid = prevAA;
this.AlternativeMassShift = alternativeMassShift;
this.Labile = labile;
this.ChemicalFormula = cf;
}
public MorpheusModification(string NameInXml)
{
this.NameInXml = NameInXml;
}
public MorpheusModification(double v)
{
this.MonoisotopicMassShift = v;
ThisModificationType = ModificationType.AminoAcidResidue;
PrevAminoAcid = '\0';
this.NameInXml = "";
}
#endregion Public Constructors
#region Public Properties
public string Description
{
get
{
return Database + (Labile ? ":labile" : "") + ":" + NameInXml;
}
}
public bool Labile { get; private set; }
public ModificationType ThisModificationType { get; private set; }
public char AminoAcid { get; private set; }
public double MonoisotopicMassShift { get; private set; }
public string Database { get; private set; }
public string DatabaseName { get; private set; }
public string NameInXml { get; private set; }
public char PrevAminoAcid { get; private set; }
public double AlternativeMassShift { get; private set; }
public ChemicalFormula ChemicalFormula { get; private set; }
#endregion Public Properties
#region Public Methods
public override string ToString()
{
return Description;
}
#endregion Public Methods
}
}
| using Chemistry;
namespace OldInternalLogic
{
public class MorpheusModification
{
private double v;
#region Public Constructors
public MorpheusModification(string nameInXml, ModificationType type, char aminoAcid, string database, string databaseName, char prevAA, double alternativeMassShift, bool labile, ChemicalFormula cf)
{
this.NameInXml = nameInXml;
ThisModificationType = type;
AminoAcid = aminoAcid;
MonoisotopicMassShift = cf.MonoisotopicMass;
Database = database;
DatabaseName = databaseName;
PrevAminoAcid = prevAA;
this.AlternativeMassShift = alternativeMassShift;
this.Labile = labile;
this.ChemicalFormula = cf;
}
public MorpheusModification(string NameInXml)
{
this.NameInXml = NameInXml;
}
public MorpheusModification(double v)
{
this.MonoisotopicMassShift = v;
ThisModificationType = ModificationType.AminoAcidResidue;
PrevAminoAcid = '\0';
this.NameInXml = "";
}
#endregion Public Constructors
#region Public Properties
public string Description
{
get
{
return Database + (Labile ? ":labile" : "") + ":" + NameInXml;
}
}
public bool Labile { get; private set; }
public ModificationType ThisModificationType { get; private set; }
public char AminoAcid { get; private set; }
public double MonoisotopicMassShift { get; private set; }
public string Database { get; private set; }
public string DatabaseName { get; private set; }
public string NameInXml { get; private set; }
public char PrevAminoAcid { get; private set; }
public double AlternativeMassShift { get; private set; }
public ChemicalFormula ChemicalFormula { get; private set; }
#endregion Public Properties
#region Public Methods
public override string ToString()
{
return Description;
}
#endregion Public Methods
}
} | mit | C# |
cbbd9b9bd2bb47c7acf960a0403da573310f34a6 | Stop spamming to console on each server response on client | neyrox/rarog | Client/Connection.cs | Client/Connection.cs | using System;
using System.Net.Sockets;
using Engine;
namespace Rarog
{
public class Connection
{
private TcpClient _tcpClient;
private NetworkStream _stream;
public Connection(string host, int port)
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
_tcpClient = new TcpClient(host, port);
// Get a client stream for reading and writing.
_stream = _tcpClient.GetStream();
}
public Result Perform(string query)
{
// Translate the passed message into UTF8 and store it as a Byte array.
var data = System.Text.Encoding.UTF8.GetBytes(query);
// Send the message to the connected TcpServer.
_stream.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
_stream.Write(data, 0, data.Length);
// Receive the Server response.
data = new byte[sizeof(int)];
var bytes = _stream.Read(data, 0, data.Length);
var bodyLength = BitConverter.ToInt32(data, 0);
// Buffer to store the response bytes.
var body = new byte[bodyLength];
bytes = _stream.Read(body, 0, body.Length);
//Console.WriteLine("Received: {0} bytes", bytes);
//var resultBytes = new byte[bytes];
// TODO: get rid of copying here
//Array.Copy(data, resultBytes, bytes);
var packer = new Engine.Serialization.MPackResultPacker();
var result = packer.UnpackResult(body);
return result;
}
public void Close()
{
// Close everything.
_stream.Close();
_tcpClient.Close();
}
}
} | using System;
using System.Net.Sockets;
using Engine;
namespace Rarog
{
public class Connection
{
private TcpClient _tcpClient;
private NetworkStream _stream;
public Connection(string host, int port)
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
_tcpClient = new TcpClient(host, port);
// Get a client stream for reading and writing.
_stream = _tcpClient.GetStream();
}
public Result Perform(string query)
{
// Translate the passed message into UTF8 and store it as a Byte array.
var data = System.Text.Encoding.UTF8.GetBytes(query);
// Send the message to the connected TcpServer.
_stream.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
_stream.Write(data, 0, data.Length);
// Receive the Server response.
data = new byte[sizeof(int)];
var bytes = _stream.Read(data, 0, data.Length);
var bodyLength = BitConverter.ToInt32(data, 0);
// Buffer to store the response bytes.
var body = new byte[bodyLength];
bytes = _stream.Read(body, 0, body.Length);
Console.WriteLine("Received: {0} bytes", bytes);
//var resultBytes = new byte[bytes];
// TODO: get rid of copying here
//Array.Copy(data, resultBytes, bytes);
var packer = new Engine.Serialization.MPackResultPacker();
var result = packer.UnpackResult(body);
return result;
}
public void Close()
{
// Close everything.
_stream.Close();
_tcpClient.Close();
}
}
} | mit | C# |
15411d9c6d3e8aacb9485d4a0af8b19eeae49fe3 | Use the new Delete command support in CslaDataProvider. | JasonBock/csla,JasonBock/csla,jonnybee/csla,BrettJaner/csla,rockfordlhotka/csla,ronnymgm/csla-light,MarimerLLC/csla,BrettJaner/csla,ronnymgm/csla-light,BrettJaner/csla,JasonBock/csla,MarimerLLC/csla,jonnybee/csla,MarimerLLC/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,rockfordlhotka/csla | ProjectTrackercs/PTWpf/RolesEdit.xaml.cs | ProjectTrackercs/PTWpf/RolesEdit.xaml.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ProjectTracker.Library.Admin;
namespace PTWpf
{
/// <summary>
/// Interaction logic for RolesEdit.xaml
/// </summary>
public partial class RolesEdit : EditForm
{
public RolesEdit()
{
InitializeComponent();
Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider;
dp.DataChanged += new EventHandler(base.DataChanged);
}
protected override void ApplyAuthorization()
{
if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles)))
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"];
}
else
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"];
((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ProjectTracker.Library.Admin;
namespace PTWpf
{
/// <summary>
/// Interaction logic for RolesEdit.xaml
/// </summary>
public partial class RolesEdit : EditForm
{
public RolesEdit()
{
InitializeComponent();
Csla.Wpf.CslaDataProvider dp = this.FindResource("RoleList") as Csla.Wpf.CslaDataProvider;
dp.DataChanged += new EventHandler(base.DataChanged);
}
protected override void ApplyAuthorization()
{
this.AuthPanel.Refresh();
if (Csla.Security.AuthorizationRules.CanEditObject(typeof(Roles)))
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbTemplate"];
}
else
{
this.RolesListBox.ItemTemplate = (DataTemplate)this.MainGrid.Resources["lbroTemplate"];
((Csla.Wpf.CslaDataProvider)this.FindResource("RoleList")).Cancel();
}
}
}
}
| mit | C# |
cb8c09b271738a165adfabe10a103ed599018bd9 | Add channel mute/unmute to LoadMidi | futurechris/MIDIM | Assets/Scripts/LoadMidi.cs | Assets/Scripts/LoadMidi.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using CSharpSynth.Effects;
using CSharpSynth.Sequencer;
using CSharpSynth.Synthesis;
using CSharpSynth.Midi;
[RequireComponent (typeof(AudioSource))]
public class LoadMidi : MonoBehaviour {
public string testMidiFile = "Midis/Video_Game_Themes_-_Secret_Of_Mana.mid";
public string bankFilePath = "FM Bank/gm";
public int bufferSize = 1024;
private float[] sampleBuffer;
private float gain = 1f;
private MidiSequencer midiSequencer;
private StreamSynthesizer midiStreamSynthesizer;
private bool allMute = false;
void Awake()
{
// For now, imitating the behavior of UnitySynthTest.cs with two goals:
// 1. Understand how UnitySynth loads and plays midi files
// 2. Figure out where in that process to get the data for the markov chain
// copied straight for UnitySynthTest.cs, almost
midiStreamSynthesizer = new StreamSynthesizer(44100, 2, bufferSize, 40);
sampleBuffer = new float[midiStreamSynthesizer.BufferSize];
midiStreamSynthesizer.LoadBank(bankFilePath);
midiSequencer = new MidiSequencer(midiStreamSynthesizer);
midiSequencer.LoadMidi(testMidiFile, false);
midiSequencer.NoteOnEvent += new MidiSequencer.NoteOnEventHandler (MidiNoteOnHandler);
midiSequencer.NoteOffEvent += new MidiSequencer.NoteOffEventHandler (MidiNoteOffHandler);
}
void Start()
{
}
// Keys:
// P/S: Play/Stop
// ` (tilde/backquote): Mute/Unmute all channels
// If any channel is not muted, this will mute all. Else it unmutes all.
// 1-9,0: Toggle mute for channel <key>
void Update()
{
// add some play/stop keys since I'm not using the GUILayout stuff.
if(Input.GetKeyDown(KeyCode.P))
{
midiSequencer.Play();
}
else if(Input.GetKeyDown(KeyCode.S))
{
midiSequencer.Stop(true);
}
if(Input.GetKeyDown(KeyCode.BackQuote))
{
if(allMute)
{
midiSequencer.UnMuteAllChannels();
}
else
{
midiSequencer.MuteAllChannels();
allMute = true;
}
}
for(int channel=0; channel<10; channel++)
{
checkSingleMuteKey(channel);
}
}
private void checkSingleMuteKey(int channel)
{
if(channel < 10)
{
if(Input.GetKeyDown(channel.ToString())){
if(midiSequencer.isChannelMuted(channel))
{
midiSequencer.UnMuteChannel(channel);
allMute = false;
}
else
{
midiSequencer.MuteChannel(channel);
// TODO: Update bookkeeping to so that if you individually mute
// each channel, allMute = false ends up true.
}
}
}
else
{
// convert to use QWERTY as 10-15
// Maybe ABCDEF would be better?
}
}
private void OnAudioFilterRead (float[] data, int channels)
{
midiStreamSynthesizer.GetNext (sampleBuffer);
for (int i = 0; i < data.Length; i++) {
data [i] = sampleBuffer [i] * gain;
}
}
public void MidiNoteOnHandler (int channel, int note, int velocity)
{
// In theory could get data here, but that means we need to play through the song
// to initialize the chain. Weird.
}
public void MidiNoteOffHandler (int channel, int note)
{
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using CSharpSynth.Effects;
using CSharpSynth.Sequencer;
using CSharpSynth.Synthesis;
using CSharpSynth.Midi;
//[RequireComponent (typeof(AudioSource))]
public class LoadMidi : MonoBehaviour {
public string testMidiFile = "Midis/Video_Game_Themes_-_Secret_Of_Mana.mid";
public string bankFilePath = "FM Bank/gm";
public int bufferSize = 1024;
private float[] sampleBuffer;
private float gain = 1f;
private MidiSequencer midiSequencer;
private StreamSynthesizer midiStreamSynthesizer;
void Awake()
{
// For now, imitating the behavior of UnitySynthTest.cs with two goals:
// 1. Understand how UnitySynth loads and plays midi files
// 2. Figure out where in that process to get the data for the markov chain
// copied straight for UnitySynthTest.cs, almost
midiStreamSynthesizer = new StreamSynthesizer(44100, 2, bufferSize, 40);
sampleBuffer = new float[midiStreamSynthesizer.BufferSize];
midiStreamSynthesizer.LoadBank(bankFilePath);
midiSequencer = new MidiSequencer(midiStreamSynthesizer);
midiSequencer.LoadMidi(testMidiFile, false);
midiSequencer.NoteOnEvent += new MidiSequencer.NoteOnEventHandler (MidiNoteOnHandler);
midiSequencer.NoteOffEvent += new MidiSequencer.NoteOffEventHandler (MidiNoteOffHandler);
}
void Start()
{
}
void Update()
{
// add some play/stop keys since I'm not using the GUILayout stuff.
if(Input.GetKeyDown(KeyCode.P))
{
midiSequencer.Play();
}
else if(Input.GetKeyDown(KeyCode.S))
{
midiSequencer.Stop(true);
}
}
private void OnAudioFilterRead (float[] data, int channels)
{
midiStreamSynthesizer.GetNext (sampleBuffer);
for (int i = 0; i < data.Length; i++) {
data [i] = sampleBuffer [i] * gain;
}
}
public void MidiNoteOnHandler (int channel, int note, int velocity)
{
}
public void MidiNoteOffHandler (int channel, int note)
{
}
}
| mit | C# |
505f4a4be610d6eb9401cf2707cd546213ff995f | Add UWP to Platforms enum | florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho | Bindings/Portable/Enums.cs | Bindings/Portable/Enums.cs | using System;
namespace Urho {
[Flags]
public enum ViewOverrideFlags {
None = 0,
LowMaterialQuality = 1,
DisableShadows = 2,
DisableOcclusion = 4
}
public enum LogLevel {
Raw = -1,
Debug = 0,
Info = 1,
Warning = 2,
Error = 3,
None = 4
}
[Flags]
public enum ElementMask : uint {
None = 0x0,
Position = 0x1,
Normal = 0x2,
Color = 0x4,
TexCoord1 = 0x8,
TexCoord2 = 0x10,
CubeTexCoord1 = 0x20,
CubeTexCoord2 = 0x40,
Tangent = 0x80,
BlendWeights = 0x100,
BlendIndices = 0x200,
InstanceMatrix1 = 0x400,
InstanceMatrix2 = 0x800,
InstanceMatrix3 = 0x1000,
Default = 0xffffffff,
}
public enum SoundType {
Master,
Effect,
Ambient,
Voice,
Music
}
public enum DrawableFlags : uint {
Geometry = 0x1,
Light = 0x2,
Zone = 0x4,
Geometry2D = 0x8,
Any = 0xff,
}
public enum Platforms {
Unknown,
Android,
iOS,
Windows,
MacOSX,
Linux,
UWP
}
internal static class PlatformsMap
{
public static Platforms FromString(string str)
{
switch (str)
{
// ProcessUtils.cpp:L349
case "Android": return Platforms.Android;
case "iOS": return Platforms.iOS;
case "Windows": return Platforms.Windows;
case "Mac OS X": return Platforms.MacOSX;
case "Linux": return Platforms.Linux;
}
#if UWP
return Platforms.UWP;
#endif
return Platforms.Unknown;
}
}
internal enum CallbackType
{
Component_OnSceneSet,
Component_SaveXml,
Component_LoadXml,
Component_AttachedToNode,
Component_OnNodeSetEnabled,
RefCounted_AddRef,
RefCounted_Delete
};
}
| using System;
namespace Urho {
[Flags]
public enum ViewOverrideFlags {
None = 0,
LowMaterialQuality = 1,
DisableShadows = 2,
DisableOcclusion = 4
}
public enum LogLevel {
Raw = -1,
Debug = 0,
Info = 1,
Warning = 2,
Error = 3,
None = 4
}
[Flags]
public enum ElementMask : uint {
None = 0x0,
Position = 0x1,
Normal = 0x2,
Color = 0x4,
TexCoord1 = 0x8,
TexCoord2 = 0x10,
CubeTexCoord1 = 0x20,
CubeTexCoord2 = 0x40,
Tangent = 0x80,
BlendWeights = 0x100,
BlendIndices = 0x200,
InstanceMatrix1 = 0x400,
InstanceMatrix2 = 0x800,
InstanceMatrix3 = 0x1000,
Default = 0xffffffff,
}
public enum SoundType {
Master,
Effect,
Ambient,
Voice,
Music
}
public enum DrawableFlags : uint {
Geometry = 0x1,
Light = 0x2,
Zone = 0x4,
Geometry2D = 0x8,
Any = 0xff,
}
public enum Platforms {
Unknown,
Android,
iOS,
Windows,
MacOSX,
Linux
}
internal static class PlatformsMap
{
public static Platforms FromString(string str)
{
switch (str)
{
// ProcessUtils.cpp:L349
case "Android": return Platforms.Android;
case "iOS": return Platforms.iOS;
case "Windows": return Platforms.Windows;
case "Mac OS X": return Platforms.MacOSX;
case "Linux": return Platforms.Linux;
}
return Platforms.Unknown;
}
}
internal enum CallbackType
{
Component_OnSceneSet,
Component_SaveXml,
Component_LoadXml,
Component_AttachedToNode,
Component_OnNodeSetEnabled,
RefCounted_AddRef,
RefCounted_Delete
};
}
| mit | C# |
00fd31b3c4440135ab18fbfec80e5f166ec4fb74 | improve code style. | Faithlife/FaithlifeUtility | src/Faithlife.Utility/Disposables.cs | src/Faithlife.Utility/Disposables.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Faithlife.Utility
{
/// <summary>
/// A collection of disposable objects, disposed in reverse order when the collection is disposed.
/// </summary>
/// <remarks>This class is thread-safe. Null disposables are legal and ignored. Objects cannot be
/// added to the collection after it has been disposed. The collection cannot be enumerated.</remarks>
[SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface", Justification = "Collection initialization syntax.")]
public sealed class Disposables : IDisposable, IEnumerable
{
/// <summary>
/// Initializes a new instance of the <see cref="Disposables"/> class.
/// </summary>
public Disposables()
{
m_lock = new object();
m_list = new List<IDisposable>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Disposables"/> class.
/// </summary>
/// <param name="disposables">The initial disposables.</param>
public Disposables(IEnumerable<IDisposable> disposables)
{
m_lock = new object();
m_list = new List<IDisposable>(disposables);
}
/// <summary>
/// Adds the specified disposable.
/// </summary>
/// <param name="disposable">The disposable.</param>
/// <exception cref="System.ObjectDisposedException">Illegal to add after Dispose.</exception>
public void Add(IDisposable disposable)
{
lock (m_lock)
{
if (m_list == null)
throw new ObjectDisposedException("Illegal to add after Dispose.");
m_list.Add(disposable);
}
}
/// <summary>
/// Adds the specified disposables.
/// </summary>
/// <param name="disposables">The disposables.</param>
/// <exception cref="System.ObjectDisposedException">AddRange called after Dispose.</exception>
public void AddRange(IEnumerable<IDisposable> disposables)
{
foreach (IDisposable disposable in disposables)
Add(disposable);
}
/// <summary>
/// Disposes all added disposables, in reverse order.
/// </summary>
public void Dispose()
{
List<IDisposable> list;
lock (m_lock)
{
list = m_list;
m_list = null;
}
if (list != null)
{
int count = list.Count;
for (int index = count - 1; index >= 0; index--)
list[index]?.Dispose();
}
}
/// <summary>
/// Implemented only for collection initialization syntax; throws if called.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => throw new NotSupportedException("IEnumerable.GetEnumerator implemented only for collection initialization syntax.");
readonly object m_lock;
List<IDisposable> m_list;
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Faithlife.Utility
{
/// <summary>
/// A collection of disposable objects, disposed in reverse order when the collection is disposed.
/// </summary>
/// <remarks>This class is thread-safe. Null disposables are legal and ignored. Objects cannot be
/// added to the collection after it has been disposed. The collection cannot be enumerated.</remarks>
[SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface", Justification = "Collection initialization syntax.")]
public sealed class Disposables : IDisposable, IEnumerable
{
/// <summary>
/// Initializes a new instance of the <see cref="Disposables"/> class.
/// </summary>
public Disposables()
{
m_lock = new object();
m_list = new List<IDisposable>();
}
/// <summary>
/// Initializes a new instance of the <see cref="Disposables"/> class.
/// </summary>
/// <param name="disposables">The initial disposables.</param>
public Disposables(IEnumerable<IDisposable> disposables)
{
m_lock = new object();
m_list = new List<IDisposable>(disposables);
}
/// <summary>
/// Adds the specified disposable.
/// </summary>
/// <param name="disposable">The disposable.</param>
/// <exception cref="System.ObjectDisposedException">Illegal to add after Dispose.</exception>
public void Add(IDisposable disposable)
{
lock (m_lock)
{
if (m_list == null)
throw new ObjectDisposedException("Illegal to add after Dispose.");
m_list.Add(disposable);
}
}
/// <summary>
/// Adds the specified disposables.
/// </summary>
/// <param name="disposables">The disposables.</param>
/// <exception cref="System.ObjectDisposedException">AddRange called after Dispose.</exception>
public void AddRange(IEnumerable<IDisposable> disposables)
{
foreach (IDisposable disposable in disposables)
Add(disposable);
}
/// <summary>
/// Disposes all added disposables, in reverse order.
/// </summary>
public void Dispose()
{
List<IDisposable> list;
lock (m_lock)
{
list = m_list;
m_list = null;
}
if (list != null)
{
int count = list.Count;
for (int index = count - 1; index >= 0; index--)
{
IDisposable disposable = list[index];
if (disposable != null)
disposable.Dispose();
}
}
}
/// <summary>
/// Implemented only for collection initialization syntax; throws if called.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotSupportedException("IEnumerable.GetEnumerator implemented only for collection initialization syntax.");
}
readonly object m_lock;
List<IDisposable> m_list;
}
}
| mit | C# |
f06576a15685a9a6417a950aab2980b9829e1435 | Implement RouteData resolvement while in wcf context | baseclass/nuserv,baseclass/nuserv,baseclass/nuserv | nuserv/Utility/HttpRouteDataResolver.cs | nuserv/Utility/HttpRouteDataResolver.cs | namespace nuserv.Utility
{
#region Usings
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Routing;
#endregion
public class HttpRouteDataResolver : IHttpRouteDataResolver
{
#region Public Methods and Operators
public IHttpRouteData Resolve()
{
if (HttpContext.Current != null)
{
if (HttpContext.Current.Items.Contains(""))
{
var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
if (requestMessage != null)
{
return requestMessage.GetRouteData();
}
}
else
{
return new RouteData(HttpContext.Current.Request.RequestContext.RouteData);
}
}
return null;
}
#endregion
private class RouteData : IHttpRouteData
{
#region Fields
private readonly System.Web.Routing.RouteData originalRouteData;
#endregion
#region Constructors and Destructors
public RouteData(System.Web.Routing.RouteData routeData)
{
if (routeData == null)
{
throw new ArgumentNullException("routeData");
}
this.originalRouteData = routeData;
this.Route = null;
}
#endregion
#region Public Properties
public IHttpRoute Route { get; private set; }
public IDictionary<string, object> Values
{
get
{
return this.originalRouteData.Values;
}
}
#endregion
}
}
} | namespace nuserv.Utility
{
using System.Net.Http;
using System.Web;
using System.Web.Http.Routing;
public class HttpRouteDataResolver : IHttpRouteDataResolver
{
#region Public Methods and Operators
public IHttpRouteData Resolve()
{
if (HttpContext.Current != null)
{
var requestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
return requestMessage.GetRouteData();
}
return null;
}
#endregion
}
} | mit | C# |
910fb91912df2c5a5e5fbff3cfc373b0dbfa9d24 | Improve parser | cwensley/maccore,jorik041/maccore,mono/maccore | src/Foundation/NSStream.cs | src/Foundation/NSStream.cs | //
// NSStream extensions
//
// Authors:
// Miguel de Icaza
//
// Copyright 2011, Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoMac.Foundation {
public partial class NSStream {
public NSObject this [NSString key] {
get {
return PropertyForKey (key);
}
set {
SetPropertyForKey (value, key);
}
}
}
} | //
// NSStream extensions
//
// Authors:
// Miguel de Icaza
//
// Copyright 2011, Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace MonoMac.Foundation {
public partial class NSStream {
public NSObject this [string key] {
get {
return PropertyForKey (key);
}
set {
SetPropertyForKey (value, key);
}
}
}
} | apache-2.0 | C# |
136ddab86dc6fb31da3e5092c9ca72b147c0b5f7 | Update _TermsAndConditionBody.cshtml | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Views/TermsAndConditions/_TermsAndConditionBody.cshtml | src/SFA.DAS.EmployerUsers.Web/Views/TermsAndConditions/_TermsAndConditionBody.cshtml | <p>To use this service you agree to:</p>
<ul class="list list-bullet">
<li>Sign out at the end of each session</li>
<li>Input truthful and accurate information</li>
<li>Adhere to the <a href="http://www.legislation.gov.uk/ukpga/1990/18/contents" target="_blank">Computer Misuse Act 1990</a></li>
<li>Use only a legitimate email address that you or people in your organisation has access to</li>
<li>Keep your sign in details secure and do not share them with third parties</li>
<li>Not use discriminatory wording as set out in the <a href="https://www.gov.uk/guidance/equality-act-2010-guidance#equalities-act-2010-legislation" target="_blank">Equality Act 2010</a></li>
<li>Make sure the published rates of pay comply with the <a href="https://www.gov.uk/national-minimum-wage-rates" target="_blank">National Minimum Wage</a> guidelines and are not misleading to candidates</li>
<li>Adhere to all relevant <a href="https://www.gov.uk/browse/employing-people" target="_blank">UK employment law</a></li>
<li>If you are a commercial organisation as defined in <a href="https://www.legislation.gov.uk/ukpga/2015/30/section/54/enacted" target="_blank">section 54 of the Modern Slavery Act 2015</a>, adhere to the annual reporting requirements</li>
<li>Your apprenticeship adverts being publicly accessible, including the possibility of partner websites displaying them</li>
<li>Comply with the government safeguarding policies for <a href="https://www.gov.uk/government/publications/ofsted-safeguarding-policy" target="_blank">children</a> and <a href="https://www.gov.uk/government/publications/safeguarding-policy-protecting-vulnerable-adults" target="_blank">vulnerable adults</a></li>
<li>Not provide feedback on a training provider when you are an employer provider</li>
<li>Be an active and trading business at the point of creating an apprenticeship service account</li>
<li>Only add apprentices that are linked to the PAYE scheme registered in your employer account</li>
<li>Comply at all times with the Apprenticeship Agreement for Employers and Apprenticeship Funding Rules</li>
</ul>
<p>When you sign up for an apprenticeship service account we may need to verify and validate your company. You may not be granted an account if you fail the checks conducted by ESFA.</p>
<p>Your contact details and information associated with your account will be collected and used for the support and administration of your account.</p>
<p>We will not:</p>
<ul class="list list-bullet">
<li>Use or disclose this information for other purposes (except where we’re legally required to do so)</li>
<li>Use your details for any marketing purposes or for any reason unrelated to the use of your account</li>
</ul>
<p>We may update these terms and conditions at any time without notice. You’ll agree to any changes if you continue to use this service after the terms and conditions have been updated.</p>
| <p>To use this service, you agree to:</p>
<ul class="list list-bullet">
<li>sign out at the end of each session</li>
<li>input truthful and accurate information</li>
<li>adhere to the <a href="http://www.legislation.gov.uk/ukpga/1990/18/contents" target="_blank">Computer Misuse Act 1990</a></li>
<li>keep your sign in details secure</li>
<li>not use discriminatory wording as set out in the <a href="https://www.gov.uk/guidance/equality-act-2010-guidance#equalities-act-2010-legislation" target="_blank">Equality Act 2010</a></li>
<li>make sure the published rates of pay comply with the <a href="https://www.gov.uk/national-minimum-wage-rates" target="_blank">National Minimum Wage</a> guidelines and are not misleading to candidates</li>
<li>adhere to all relevant <a href="https://www.gov.uk/browse/employing-people" target="_blank">UK employment law</a></li>
<li>only use the recruitment section of the service if you pay the apprenticeship levy or you are part of our testing phase</li>
<li>your apprenticeship adverts being publicly accessible, including the possibility of partner websites displaying them</li>
<li>comply with the government safeguarding policies for <a href="https://www.gov.uk/government/publications/ofsted-safeguarding-policy" target="_blank">children</a> and <a href="https://www.gov.uk/government/publications/safeguarding-policy-protecting-vulnerable-adults" target="_blank">vulnerable adults</a></li>
<li>not provide feedback on a training provider where there is a conflict of interest</li>
</ul>
<p>Your contact details and information associated with your account will be collected and used for the support and administration of your account.</p>
<p>We will not:</p>
<ul class="list list-bullet">
<li>use or disclose this information for other purposes (except where we're legally required to do so)</li>
<li>use your details for any marketing purposes or for any reason unrelated to the use of your account</li>
</ul>
<p>We may update these terms and conditions at any time without notice. You'll agree to any changes if you continue to use this service after the terms and conditions have been updated.</p>
| mit | C# |
11044221c65ca504223578bb3649f268ec86ce24 | Add support for `Amount` on `SessionPaymentIntentTransferDataOptions` | stripe/stripe-dotnet | src/Stripe.net/Services/Checkout/Sessions/SessionPaymentIntentTransferDataOptions.cs | src/Stripe.net/Services/Checkout/Sessions/SessionPaymentIntentTransferDataOptions.cs | namespace Stripe
{
using System;
using Newtonsoft.Json;
public class SessionPaymentIntentTransferDataOptions : INestedOptions
{
/// <summary>
/// The amount that will be transferred automatically when a charge succeeds.
/// </summary>
[JsonProperty("amount")]
public long? Amount { get; set; }
/// <summary>
/// If specified, successful charges will be attributed to the destination account for tax
/// reporting, and the funds from charges will be transferred to the destination account.
/// The ID of the resulting transfer will be returned on the successful charge’s
/// <see cref="Transfer"/> field.
/// </summary>
[JsonProperty("destination")]
public string Destination { get; set; }
}
}
| namespace Stripe
{
using System;
using Newtonsoft.Json;
public class SessionPaymentIntentTransferDataOptions : INestedOptions
{
[JsonProperty("destination")]
public string Destination { get; set; }
}
}
| apache-2.0 | C# |
40f918dce6a65a77589bd6a5800f510f82d1ff53 | Remove unused using | smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,ppy/osu,ppy/osu,2yangk23/osu,UselessToucan/osu,johnneijzen/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,peppy/osu-new | osu.Game/Rulesets/Mods/ModRateAdjust.cs | osu.Game/Rulesets/Mods/ModRateAdjust.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.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModRateAdjust : Mod, IApplicableToTrack
{
public abstract BindableNumber<double> SpeedChange { get; }
public virtual void ApplyToTrack(Track track)
{
track.AddAdjustment(AdjustableProperty.Tempo, SpeedChange);
}
}
}
| // 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 osu.Framework.Audio;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModRateAdjust : Mod, IApplicableToTrack
{
public abstract BindableNumber<double> SpeedChange { get; }
public virtual void ApplyToTrack(Track track)
{
track.AddAdjustment(AdjustableProperty.Tempo, SpeedChange);
}
}
}
| mit | C# |
256ea0920292077a1547be795cfd1d5507064cb3 | Make sure to only invoke defaults once | NServiceBusSqlPersistence/NServiceBus.SqlPersistence | src/SqlPersistence/SqlPersistence.cs | src/SqlPersistence/SqlPersistence.cs | namespace NServiceBus
{
using Settings;
using Features;
using Persistence;
using Persistence.Sql;
/// <summary>
/// The <see cref="PersistenceDefinition"/> for the SQL Persistence.
/// </summary>
public class SqlPersistence : PersistenceDefinition
{
/// <summary>
/// Initializes a new instance of <see cref="SqlPersistence"/>.
/// </summary>
public SqlPersistence()
{
Supports<StorageType.Outbox>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlOutboxFeature>();
});
Supports<StorageType.Timeouts>(s =>
{
s.EnableFeatureByDefault<SqlTimeoutFeature>();
});
Supports<StorageType.Sagas>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlSagaFeature>();
s.AddUnrecoverableException(typeof(SerializationException));
});
Supports<StorageType.Subscriptions>(s =>
{
s.EnableFeatureByDefault<SqlSubscriptionFeature>();
});
Defaults(s =>
{
var defaultsAppliedSettingsKey = "NServiceBus.Persistence.Sql.DefaultApplied";
if (s.HasSetting(defaultsAppliedSettingsKey))
{
return;
}
var dialect = s.GetSqlDialect();
var diagnostics = dialect.GetCustomDialectDiagnosticsInfo();
s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new
{
Name = dialect.Name,
CustomDiagnostics = diagnostics
});
s.EnableFeatureByDefault<InstallerFeature>();
s.Set(defaultsAppliedSettingsKey, true);
});
}
static void EnableSession(SettingsHolder s)
{
s.EnableFeatureByDefault<StorageSessionFeature>();
}
}
} | namespace NServiceBus
{
using Settings;
using Features;
using Persistence;
using Persistence.Sql;
/// <summary>
/// The <see cref="PersistenceDefinition"/> for the SQL Persistence.
/// </summary>
public class SqlPersistence : PersistenceDefinition
{
/// <summary>
/// Initializes a new instance of <see cref="SqlPersistence"/>.
/// </summary>
public SqlPersistence()
{
Supports<StorageType.Outbox>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlOutboxFeature>();
});
Supports<StorageType.Timeouts>(s =>
{
s.EnableFeatureByDefault<SqlTimeoutFeature>();
});
Supports<StorageType.Sagas>(s =>
{
EnableSession(s);
s.EnableFeatureByDefault<SqlSagaFeature>();
s.AddUnrecoverableException(typeof(SerializationException));
});
Supports<StorageType.Subscriptions>(s =>
{
s.EnableFeatureByDefault<SqlSubscriptionFeature>();
});
Defaults(s =>
{
var dialect = s.GetSqlDialect();
var diagnostics = dialect.GetCustomDialectDiagnosticsInfo();
s.AddStartupDiagnosticsSection("NServiceBus.Persistence.Sql.SqlDialect", new
{
Name = dialect.Name,
CustomDiagnostics = diagnostics
});
s.EnableFeatureByDefault<InstallerFeature>();
});
}
static void EnableSession(SettingsHolder s)
{
s.EnableFeatureByDefault<StorageSessionFeature>();
}
}
} | mit | C# |
00b6dd5c2fa240b7fb475abf2596597437a03ca6 | Remove unused property | bartlomiejwolk/AnimationPathAnimator | AnimatorEventsComponent/AnimatorEventsSettings.cs | AnimatorEventsComponent/AnimatorEventsSettings.cs | using UnityEngine;
namespace ATP.AnimationPathTools.AnimatorEventsComponent {
public sealed class AnimatorEventsSettings : ScriptableObject {
#region FIELDS
[SerializeField]
private int defaultNodeLabelHaight = 30;
[SerializeField]
private int defaultNodeLabelWidth = 100;
[SerializeField]
private int methodNameLabelOffsetX = 30;
[SerializeField]
private int methodNameLabelOffsetY = -20;
#endregion
#region PROPERTIES
public int DefaultNodeLabelHeight {
get { return defaultNodeLabelHaight; }
set { defaultNodeLabelHaight = value; }
}
public int DefaultNodeLabelWidth {
get { return defaultNodeLabelWidth; }
set { defaultNodeLabelWidth = value; }
}
public int MethodNameLabelOffsetX {
get { return methodNameLabelOffsetX; }
set { methodNameLabelOffsetX = value; }
}
public int MethodNameLabelOffsetY {
get { return methodNameLabelOffsetY; }
}
#endregion
}
} | using UnityEngine;
namespace ATP.AnimationPathTools.AnimatorEventsComponent {
public sealed class AnimatorEventsSettings : ScriptableObject {
#region FIELDS
[SerializeField]
private int defaultNodeLabelHaight = 30;
[SerializeField]
private int defaultNodeLabelWidth = 100;
[SerializeField]
private bool drawMethodNames = true;
[SerializeField]
private int methodNameLabelOffsetX = 30;
[SerializeField]
private int methodNameLabelOffsetY = -20;
#endregion
#region PROPERTIES
public int DefaultNodeLabelHeight {
get { return defaultNodeLabelHaight; }
set { defaultNodeLabelHaight = value; }
}
public int DefaultNodeLabelWidth {
get { return defaultNodeLabelWidth; }
set { defaultNodeLabelWidth = value; }
}
public bool DrawMethodNames {
get { return drawMethodNames; }
set { drawMethodNames = value; }
}
public int MethodNameLabelOffsetX {
get { return methodNameLabelOffsetX; }
set { methodNameLabelOffsetX = value; }
}
public int MethodNameLabelOffsetY {
get { return methodNameLabelOffsetY; }
}
#endregion
}
} | mit | C# |
fb97cf9108c64586bec49fb3b4541cbf6b1de4ba | Fix #7 - Forgot that PREFIX=(...) lists in descending order. Reverse the order of prefixes then compare indices | Genesis2001/Lantea | Atlantis/Atlantis.Net.Irc/IrcClient.Extensions.cs | Atlantis/Atlantis.Net.Irc/IrcClient.Extensions.cs | // -----------------------------------------------------------------------------
// <copyright file="IrcClientExtensions.cs" company="Zack Loveless">
// Copyright (c) Zack Loveless. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------------
namespace Atlantis.Net.Irc
{
using System;
public partial class IrcClient
{
public bool IsHigherOrEqualToPrefix(char prefixA, char prefixB)
{
if (prefixA == prefixB) return true;
char[] accessPrefixes = AccessPrefixes.ToCharArray();
Array.Reverse(accessPrefixes);
String prefixes = new string(accessPrefixes);
return prefixes.IndexOf(prefixA) >= prefixes.IndexOf(prefixB);
}
}
}
| // -----------------------------------------------------------------------------
// <copyright file="IrcClientExtensions.cs" company="Zack Loveless">
// Copyright (c) Zack Loveless. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------------
namespace Atlantis.Net.Irc
{
using System;
public partial class IrcClient
{
public bool IsHigherOrEqualToPrefix(char prefixA, char prefixB)
{
if (prefixA == prefixB) return true;
return AccessPrefixes.IndexOf(prefixA) >= AccessPrefixes.IndexOf(prefixB);
}
}
}
| mit | C# |
94a2b784b8a840fe07b98488796d3dd89cca0d47 | test commit 2 | dekloni/MarketPlace,dekloni/MarketPlace,dekloni/MarketPlace | MarketPlaceUI/App_Start/BundleConfig.cs | MarketPlaceUI/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace MarketPlaceUI
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-theme.css",
"~/Content/site.css"));
}
}
}
| using System.Web;
using System.Web.Optimization;
namespace MarketPlaceUI
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-theme.css",
"~/Content/site.css"));
}
}
}
| unlicense | C# |
bc67de2a34d204cb7456320d6db1c2d1b7e87b45 | Fix a type error in the default constructor | IrvingtonProgramming/InteractApp,IrvingtonProgramming/InteractApp,IrvingtonProgramming/InteractApp | InteractApp/Event.cs | InteractApp/Event.cs | using System;
using System.Collections.Generic;
namespace InteractApp
{
public class Event
{
public int Id { get; private set; }
public String ImageUri { get; private set; }
public String Name { get; private set; }
public DateTime Date { get; private set; }
public String Location { get; private set; }
public String Desc { get; private set; }
public List<String> Tags { get; private set; }
public Event() {
this.Id = -1;
this.ImageUri = "http://bloggingtips.moneyreigninc.netdna-cdn.com/wp-content/uploads/2014/12/Event-Blogging-Strategies.jpg";
this.Name = "Test Event";
this.Date = new DateTime();
this.Location = "Hooli Headquarters";
this.Desc = "Test Event. If you are seeing this and you're a user, we probably screwed up.";
this.Tags = new List<String>() {"Testing", "Event"};
}
public Event(int EId, String EImageUri, String EName, DateTime EDate, String ELocation, String EDesc, List<String> ETags) {
this.Id = EId;
this.ImageUri = EImageUri;
this.Name = EName;
this.Date = EDate;
this.Location = ELocation;
this.Desc = EDesc;
this.Tags = ETags;
}
public static Event newEvent(int EId, String EImageUri, String EName, DateTime EDate, String ELocation, String EDesc, List<String> ETags) {
Event e = new Event(EId, EImageUri, EName, EDate, ELocation, EDesc, ETags);
// TODO: Add restrictions?
return e;
}
}
}
| using System;
using System.Collections.Generic;
namespace InteractApp
{
public class Event
{
public int Id { get; private set; }
public String ImageUri { get; private set; }
public String Name { get; private set; }
public DateTime Date { get; private set; }
public String Location { get; private set; }
public String Desc { get; private set; }
public List<String> Tags { get; private set; }
public Event() {
this.Id = "-1";
this.ImageUri = "http://bloggingtips.moneyreigninc.netdna-cdn.com/wp-content/uploads/2014/12/Event-Blogging-Strategies.jpg";
this.Name = "Test Event";
this.Date = new DateTime();
this.Location = "Hooli Headquarters";
this.Desc = "Test Event. If you are seeing this and you're a user, we probably screwed up.";
this.Tags = new List<String>() {"Testing", "Event"};
}
public Event(int EId, String EImageUri, String EName, DateTime EDate, String ELocation, String EDesc, List<String> ETags) {
this.Id = EId;
this.ImageUri = EImageUri;
this.Name = EName;
this.Date = EDate;
this.Location = ELocation;
this.Desc = EDesc;
this.Tags = ETags;
}
public static Event newEvent(int EId, String EImageUri, String EName, DateTime EDate, String ELocation, String EDesc, List<String> ETags) {
Event e = new Event(EId, EImageUri, EName, EDate, ELocation, EDesc, ETags);
// TODO: Add restrictions?
return e;
}
}
}
| mit | C# |
22bb5ac4290e2b2cfee5003e6606c87a8a6674d6 | Update LoginForm.cs | redeqn/RedConn | RedConn/LoginForm.cs | RedConn/LoginForm.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace RedConn
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
IE.Navigate("https://starkappcloud.appspot.com/app/?api=1");
while (IE.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
public void ShowLogin()
{
IE.Refresh()
mShowAllowed = true;
this.ShowDialog();
}
private bool mShowAllowed = false;
protected override void SetVisibleCore(bool value)
{
if (!mShowAllowed) value = false;
base.SetVisibleCore(value);
}
public WebBrowser Explorer
{
get { return this.IE; }
}
private void Browser_Load(object sender, EventArgs e)
{
}
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
this.Hide();
e.Cancel = true;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace RedConn
{
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
IE.Navigate("https://starkappcloud.appspot.com/app/?api=1");
while (IE.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
}
public void ShowLogin()
{
mShowAllowed = true;
this.ShowDialog();
}
private bool mShowAllowed = false;
protected override void SetVisibleCore(bool value)
{
if (!mShowAllowed) value = false;
base.SetVisibleCore(value);
}
public WebBrowser Explorer
{
get { return this.IE; }
}
private void Browser_Load(object sender, EventArgs e)
{
}
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
this.Hide();
e.Cancel = true;
}
}
}
}
| mit | C# |
6f4c14bb92603ac9147816618f19c1fc86b3c175 | Change error message | gblue1223/redux-unity3d | Redux/CreateStore.cs | Redux/CreateStore.cs | using System;
using System.Linq;
public static partial class Redux {
internal static class ActionType {
public const string INIT = "@@redux/C#/INIT";
};
internal static ActionCreator initialAction = () => {
return new Action{ type = ActionType.INIT };
};
public static CreateStore createStore = (finalReducer, initialStateTree, enhancer) => {
if (enhancer != null) {
return enhancer (createStore) (finalReducer, initialStateTree, null);
}
var currentReducer = finalReducer;
var currentStateTree = initialStateTree;
var currentListeners = new Listeners ();
var nextListeners = currentListeners;
var isDispatching = false;
Store store = new Store();
System.Action ensureCanMutateNextListeners = () => {
if (nextListeners.Equals (currentListeners)) {
nextListeners = new Listeners (currentListeners);
}
};
store.getStateTree = () => {
return currentStateTree;
};
store.getState = (reducer) => {
if (!currentStateTree.ContainsKey (reducer.GetHashCode ())) {
throw new Error ("Reducer '" + reducer.GetHashCode () + "' not found.");
}
return currentStateTree [reducer.GetHashCode ()];
};
store.subscribe = (listener) => {
if (listener == null) {
throw new Error ("Expected listener to be a function.");
}
var isSubscribed = true;
ensureCanMutateNextListeners ();
nextListeners.AddLast (listener);
Unsubscribe unsubscribe = () => {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners ();
nextListeners.Remove (listener);
};
return unsubscribe;
};
store.dispatch = (action) => {
if (action == null) {
throw new Error ("Actions not defined");
}
if (isDispatching) {
throw new Error ("Reducers may not dispatch actions.");
}
try {
isDispatching = true;
currentStateTree = currentReducer (currentStateTree, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
foreach (var listener in listeners) {
listener (store);
}
return action;
};
store.replaceReducer = (nextReducer) => {
currentReducer = nextReducer;
store.dispatch(initialAction ());
};
store.dispatch (initialAction ());
return store;
};
}
| using System;
using System.Linq;
public static partial class Redux {
internal static class ActionType {
public const string INIT = "@@redux/C#/INIT";
};
internal static ActionCreator initialAction = () => {
return new Action{ type = ActionType.INIT };
};
public static CreateStore createStore = (finalReducer, initialStateTree, enhancer) => {
if (enhancer != null) {
return enhancer (createStore) (finalReducer, initialStateTree, null);
}
var currentReducer = finalReducer;
var currentStateTree = initialStateTree;
var currentListeners = new Listeners ();
var nextListeners = currentListeners;
var isDispatching = false;
Store store = new Store();
System.Action ensureCanMutateNextListeners = () => {
if (nextListeners.Equals (currentListeners)) {
nextListeners = new Listeners (currentListeners);
}
};
store.getStateTree = () => {
return currentStateTree;
};
store.getState = (reducer) => {
if (!currentStateTree.ContainsKey (reducer.GetHashCode ())) {
throw new Error ("Reducer '" + reducer.GetHashCode () + "' removed.");
}
return currentStateTree [reducer.GetHashCode ()];
};
store.subscribe = (listener) => {
if (listener == null) {
throw new Error ("Expected listener to be a function.");
}
var isSubscribed = true;
ensureCanMutateNextListeners ();
nextListeners.AddLast (listener);
Unsubscribe unsubscribe = () => {
if (!isSubscribed) {
return;
}
isSubscribed = false;
ensureCanMutateNextListeners ();
nextListeners.Remove (listener);
};
return unsubscribe;
};
store.dispatch = (action) => {
if (action == null) {
throw new Error ("Actions not defined");
}
if (isDispatching) {
throw new Error ("Reducers may not dispatch actions.");
}
try {
isDispatching = true;
currentStateTree = currentReducer (currentStateTree, action);
} finally {
isDispatching = false;
}
var listeners = currentListeners = nextListeners;
foreach (var listener in listeners) {
listener (store);
}
return action;
};
store.replaceReducer = (nextReducer) => {
currentReducer = nextReducer;
store.dispatch(initialAction ());
};
store.dispatch (initialAction ());
return store;
};
} | mit | C# |
59d4c06d9d1a5b4d1df5f58f17ec361549aff744 | add support for do not fail on delete directory task | flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core | FlubuCore/Tasks/FileSystem/DeleteDirectoryTask.cs | FlubuCore/Tasks/FileSystem/DeleteDirectoryTask.cs | using System;
using System.IO;
using FlubuCore.Context;
namespace FlubuCore.Tasks.FileSystem
{
public class DeleteDirectoryTask : TaskBase<int>
{
private readonly string _directoryPath;
private readonly bool _failIfNotExists;
public DeleteDirectoryTask(string directoryPath, bool failIfNotExists)
{
_directoryPath = directoryPath;
_failIfNotExists = failIfNotExists;
}
public static void Execute(
ITaskContextInternal context,
string directoryPath,
bool failIfNotExists)
{
var task = new DeleteDirectoryTask(directoryPath, failIfNotExists);
task.ExecuteVoid(context);
}
protected override int DoExecute(ITaskContextInternal context)
{
context.LogInfo($"Delete directory '{_directoryPath}'");
if (!Directory.Exists(_directoryPath))
{
if (!_failIfNotExists)
return 0;
}
try
{
Directory.Delete(_directoryPath, true);
}
catch (Exception)
{
if (!DoNotFail)
throw;
}
return 0;
}
}
} | using System.IO;
using FlubuCore.Context;
namespace FlubuCore.Tasks.FileSystem
{
public class DeleteDirectoryTask : TaskBase<int>
{
private readonly string _directoryPath;
private readonly bool _failIfNotExists;
public DeleteDirectoryTask(string directoryPath, bool failIfNotExists)
{
_directoryPath = directoryPath;
_failIfNotExists = failIfNotExists;
}
public static void Execute(
ITaskContextInternal context,
string directoryPath,
bool failIfNotExists)
{
var task = new DeleteDirectoryTask(directoryPath, failIfNotExists);
task.ExecuteVoid(context);
}
protected override int DoExecute(ITaskContextInternal context)
{
context.LogInfo($"Delete directory '{_directoryPath}'");
if (!Directory.Exists(_directoryPath))
{
if (!_failIfNotExists)
return 0;
}
Directory.Delete(_directoryPath, true);
return 0;
}
}
} | bsd-2-clause | C# |
7af0a2c025a63d1f95941e2063db76c3700cd787 | Refactor in validator | mikemajesty/coolvalidator | CoolValidator/Validator.cs | CoolValidator/Validator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace CoolValidator
{
public static class formValidator
{
public static List<TextBox> ValidateTextBox(this Form form, Func<TextBox, bool> predicate = null)
{
var txtList = new List<TextBox>();
var txtInPanel = GetTextBoxInGroupBox<Panel>(form);
var txtInManyPanel = GetInHierarchicalGroupBox<Panel>(form);
var txtInGroupBox = GetTextBoxInGroupBox<GroupBox>(form);
var txtInManyGroupBox = GetInHierarchicalGroupBox<GroupBox>(form);
var txtInForm = GetTextBoxInForm(form);
txtList.AddRange(txtInGroupBox);
txtList.AddRange(txtInManyGroupBox);
txtList.AddRange(txtInPanel);
txtList.AddRange(txtInManyPanel);
txtList.AddRange(txtInForm);
return predicate == null ? txtList.OrderBy(t => t.TabIndex).ToList() : txtList.Where(predicate).OrderBy(t => t.TabIndex).ToList();
}
private static List<TextBox> GetTextBoxInForm(Form form)
{
return form.Controls.OfType<TextBox>().Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInGroupBox<T>(Form form) where T : Control
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetInHierarchicalGroupBox<T>(Form form) where T : Control
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<GroupBox>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace CoolValidator
{
public static class formValidator
{
public static List<TextBox> GetTextBoxInComponent(this Form form, Func<TextBox, bool> predicate = null)
{
var txtList = new List<TextBox>();
var txtInPanel = GetTextBoxInPanel(form);
var txtInManyPanel = GetInHierarchicalPanel(form);
var txtInGroupBox = GetTextBoxInGroupBox(form);
var txtInManyGroupBox = GetInHierarchicalGroupBox(form);
var txtInForm = GetTextBoxInForm(form);
txtList.AddRange(txtInGroupBox);
txtList.AddRange(txtInManyGroupBox);
txtList.AddRange(txtInPanel);
txtList.AddRange(txtInManyPanel);
txtList.AddRange(txtInForm);
return predicate == null ? txtList.OrderBy(t => t.TabIndex).ToList() : txtList.Where(predicate).OrderBy(t => t.TabIndex).ToList();
}
private static List<TextBox> GetTextBoxInForm(Form form)
{
return form.Controls.OfType<TextBox>().Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInGroupBox(Form form)
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetInHierarchicalGroupBox(Form form)
{
return form.Controls.OfType<GroupBox>().SelectMany(panel => panel.Controls.OfType<GroupBox>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInPanel(Form form)
{
return form.Controls.OfType<Panel>().SelectMany(panel => panel.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetInHierarchicalPanel(Form form)
{
return form.Controls.OfType<Panel>().SelectMany(panel => panel.Controls.OfType<Panel>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
}
}
| mit | C# |
8e5b7d257863d4def36b578a5d5cec03455ff559 | Fix crash of payment request list (Fix #3392) | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Data/PaymentRequestDataExtensions.cs | BTCPayServer/Data/PaymentRequestDataExtensions.cs | using System;
using BTCPayServer.Client.Models;
using NBXplorer;
using Newtonsoft.Json.Linq;
namespace BTCPayServer.Data
{
public static class PaymentRequestDataExtensions
{
public static PaymentRequestBaseData GetBlob(this PaymentRequestData paymentRequestData)
{
var result = paymentRequestData.Blob == null
? new PaymentRequestBaseData()
: ParseBlob(paymentRequestData.Blob);
return result;
}
private static PaymentRequestBaseData ParseBlob(byte[] blob)
{
var jobj = JObject.Parse(ZipUtils.Unzip(blob));
// Fixup some legacy payment requests
if (jobj["expiryDate"].Type == JTokenType.Date)
jobj["expiryDate"] = new JValue(NBitcoin.Utils.DateTimeToUnixTime(jobj["expiryDate"].Value<DateTime>()));
return jobj.ToObject<PaymentRequestBaseData>();
}
public static bool SetBlob(this PaymentRequestData paymentRequestData, PaymentRequestBaseData blob)
{
var original = new Serializer(null).ToString(paymentRequestData.GetBlob());
var newBlob = new Serializer(null).ToString(blob);
if (original == newBlob)
return false;
paymentRequestData.Blob = ZipUtils.Zip(newBlob);
return true;
}
}
}
| using BTCPayServer.Client.Models;
using NBXplorer;
using Newtonsoft.Json.Linq;
namespace BTCPayServer.Data
{
public static class PaymentRequestDataExtensions
{
public static PaymentRequestBaseData GetBlob(this PaymentRequestData paymentRequestData)
{
var result = paymentRequestData.Blob == null
? new PaymentRequestBaseData()
: JObject.Parse(ZipUtils.Unzip(paymentRequestData.Blob)).ToObject<PaymentRequestBaseData>();
return result;
}
public static bool SetBlob(this PaymentRequestData paymentRequestData, PaymentRequestBaseData blob)
{
var original = new Serializer(null).ToString(paymentRequestData.GetBlob());
var newBlob = new Serializer(null).ToString(blob);
if (original == newBlob)
return false;
paymentRequestData.Blob = ZipUtils.Zip(newBlob);
return true;
}
}
}
| mit | C# |
761ca0ccaf2f5c9235047b1d356190cef6ecabea | add missing indexes on startup | couchbaselabs/try-cb-dotnet,couchbaselabs/try-cb-dotnet | src/try-cb-dotnet/App_Start/CouchbaseConfig.cs | src/try-cb-dotnet/App_Start/CouchbaseConfig.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Couchbase;
using Couchbase.Configuration.Client;
namespace try_cb_dotnet
{
public static class CouchbaseConfig
{
public static void Register()
{
var couchbaseServer = ConfigurationManager.AppSettings.Get("couchbaseServer");
ClusterHelper.Initialize(new ClientConfiguration
{
Servers = new List<Uri> { new Uri(couchbaseServer) }
});
EnsureIndexes();
}
private static void EnsureIndexes()
{
var indexNames = new List<string>
{"def_sourceairport", "def_airportname", "def_type", "def_faa", "def_icao", "def_city"};
var bucket = ClusterHelper.GetBucket("travel-sample");
var result = bucket.Query<dynamic>("SELECT indexes.* FROM system:indexes WHERE keyspace_id = 'travel-sample';");
var foundIndexes = new List<string>();
var hasPrimary = false;
foreach (var row in result.Rows)
{
if (row.is_primary == "true")
{
hasPrimary = true;
}
else
{
foundIndexes.Add((string) row.name);
}
}
if (!hasPrimary)
{
bucket.Query<dynamic>("CREATE PRIMARY INDEX `def_primary` ON `travel-sample`;");
}
var missingIndexes = indexNames.Where(index => !foundIndexes.Contains(index)).ToList();
if (!missingIndexes.Any())
{
return;
}
foreach (var missingIndex in missingIndexes)
{
var propertyName = missingIndex.Replace("def_", string.Empty);
bucket.Query<dynamic>($"CREATE INDEX `{missingIndex}` ON `travel-sample`(`{propertyName}`);");
}
bucket.Query<dynamic>($"BUILD INDEX ON `travel-sample` ({string.Join(", ", missingIndexes)});");
}
public static void CleanUp()
{
ClusterHelper.Close();
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using Couchbase;
using Couchbase.Configuration.Client;
namespace try_cb_dotnet
{
public static class CouchbaseConfig
{
public static void Register()
{
var couchbaseServer = ConfigurationManager.AppSettings.Get("couchbaseServer");
ClusterHelper.Initialize(new ClientConfiguration
{
Servers = new List<Uri> { new Uri(couchbaseServer) }
});
}
public static void CleanUp()
{
ClusterHelper.Close();
}
}
} | apache-2.0 | C# |
3b48e65181f055cb36f067db2e30f63f1d711254 | Modify app name | hug3id/Xamarin.Forms.BaiduMaps,hug3id/Xamarin.Forms.BaiduMaps | Droid/MainActivity.cs | Droid/MainActivity.cs | using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Xamarin.Forms.BaiduMaps.Sample.Droid
{
[Activity(Label = "BaiduMaps Sample", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
Xamarin.FormsBaiduMaps.Init(null);
LoadApplication(new App());
}
}
}
| using System;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Xamarin.Forms.BaiduMaps.Sample.Droid
{
[Activity(Label = "Xamarin.Forms.BaiduMaps.Sample.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
Xamarin.FormsBaiduMaps.Init(null);
LoadApplication(new App());
}
}
}
| apache-2.0 | C# |
be002091f283f0c6beedc780853e477ca18fbcf1 | Add default ApiException constructor | appharbor/appharbor-cli | src/AppHarbor/ApiException.cs | src/AppHarbor/ApiException.cs | using System;
namespace AppHarbor
{
public class ApiException : Exception
{
public ApiException()
{
}
}
}
| using System;
namespace AppHarbor
{
public class ApiException : Exception
{
}
}
| mit | C# |
a028f24b10c4ccf9549187dd4b151f665e741822 | save inflected value to Petrovich while inflecting names separately | petrovich/petrovich-net | NPetrovich/Petrovich.cs | NPetrovich/Petrovich.cs | using NPetrovich.Inflection;
using NPetrovich.Rules;
using NPetrovich.Rules.Loader;
using NPetrovich.Rules.Loader.Yaml;
using NPetrovich.Utils;
namespace NPetrovich
{
public class Petrovich
{
public Petrovich()
{
loader = new YamlRulesLoader("rules.yml");
provider = new RulesProvider(loader);
}
private readonly IRulesLoader loader;
private readonly RulesProvider provider;
public Gender Gender { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public Petrovich InflectTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(FirstName, "FirstName", "First name was not provided");
Guard.IfArgumentNullOrWhitespace(LastName, "LastName", "Last name was not provided");
Guard.IfArgumentNullOrWhitespace(MiddleName, "MiddleName", "Middle name was not provided");
var inflection = new CaseInflection(provider, Gender);
FirstName = inflection.InflectFirstNameTo(FirstName, @case);
LastName = inflection.InflectLastNameTo(LastName, @case);
MiddleName = inflection.InflectMiddleNameTo(MiddleName, @case);
return this;
}
public string InflectFirstNameTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(FirstName, "FirstName", "First name was not provided");
return FirstName = new CaseInflection(provider, Gender).InflectFirstNameTo(FirstName, @case);
}
public string InflectLastNameTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(LastName, "FirstName", "Last name was not provided");
return LastName = new CaseInflection(provider, Gender).InflectLastNameTo(LastName, @case);
}
public string InflectMiddleNameTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(MiddleName, "FirstName", "Middle name was not provided");
return MiddleName = new CaseInflection(provider, Gender).InflectMiddleNameTo(MiddleName, @case);
}
public void DetectGender()
{
Gender = GenderUtils.Detect(MiddleName);
}
public override string ToString()
{
return string.Format("{0} {1} {2}", LastName, FirstName, MiddleName);
}
}
}
| using NPetrovich.Inflection;
using NPetrovich.Rules;
using NPetrovich.Rules.Loader;
using NPetrovich.Rules.Loader.Yaml;
using NPetrovich.Utils;
namespace NPetrovich
{
public class Petrovich
{
public Petrovich()
{
loader = new YamlRulesLoader("rules.yml");
provider = new RulesProvider(loader);
}
private readonly IRulesLoader loader;
private readonly RulesProvider provider;
public Gender Gender { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public Petrovich InflectTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(FirstName, "FirstName", "First name was not provided");
Guard.IfArgumentNullOrWhitespace(LastName, "LastName", "Last name was not provided");
Guard.IfArgumentNullOrWhitespace(MiddleName, "MiddleName", "Middle name was not provided");
var inflection = new CaseInflection(provider, Gender);
FirstName = inflection.InflectFirstNameTo(FirstName, @case);
LastName = inflection.InflectLastNameTo(LastName, @case);
MiddleName = inflection.InflectMiddleNameTo(MiddleName, @case);
return this;
}
public string InflectFirstNameTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(FirstName, "FirstName", "First name was not provided");
return new CaseInflection(provider, Gender).InflectFirstNameTo(FirstName, @case);
}
public string InflectLastNameTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(LastName, "FirstName", "Last name was not provided");
return new CaseInflection(provider, Gender).InflectLastNameTo(LastName, @case);
}
public string InflectMiddleNameTo(Case @case)
{
Guard.IfArgumentNullOrWhitespace(MiddleName, "FirstName", "Middle name was not provided");
return new CaseInflection(provider, Gender).InflectMiddleNameTo(MiddleName, @case);
}
public void DetectGender()
{
Gender = GenderUtils.Detect(MiddleName);
}
public override string ToString()
{
return string.Format("{0} {1} {2}", LastName, FirstName, MiddleName);
}
}
}
| mit | C# |
ccafc50b6fdb9abf0189fb34057f42a62e2915db | add details about the gauge interface | alhardy/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,alhardy/Metrics.NET,mnadel/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET | Src/Metrics/Gauge.cs | Src/Metrics/Gauge.cs |
namespace Metrics
{
/// <summary>
/// A gauge is the simplest metric type. It just returns a value.
/// No operation can be triggered on the metric directly.
/// Custom implementations can hook into any value provider.
/// <see cref="Core.FunctionGauge"/> and <see cref="Core.DerivedGauge"/>
/// </summary>
public interface Gauge : Utils.IHideObjectMembers
{
}
/// <summary>
/// Combines the value of a gauge with the defined unit for the value.
/// </summary>
public sealed class GaugeValueSource : MetricValueSource<double>
{
public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit)
: base(name, value, unit)
{ }
}
}
|
namespace Metrics
{
/// <summary>
/// A gauge is the simplest metric type. It just returns a value.
/// </summary>
public interface Gauge : Utils.IHideObjectMembers
{
}
/// <summary>
/// Combines the value of a gauge with the defined unit for the value.
/// </summary>
public sealed class GaugeValueSource : MetricValueSource<double>
{
public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit)
: base(name, value, unit)
{ }
}
}
| apache-2.0 | C# |
570126de3f7fbe4af565a2a8421f10ee0f12d12f | make future awaitable | icarus-consulting/Yaapii.Atoms | tests/Yaapii.Atoms.Tests/Func/AsyncFuncTest.cs | tests/Yaapii.Atoms.Tests/Func/AsyncFuncTest.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Yaapii.Atoms.Func;
namespace Yaapii.Atoms.Tests.Func
{
public sealed class AsyncFuncTest
{
[Fact]
public void RunsInBackground()
{
var future =
new AsyncFunc<bool, string>(
input =>
{
Thread.Sleep(new TimeSpan(1, 0, 0, 0)); //sleep for a day
return "done!";
}
).Invoke(true);
Assert.True(!future.IsCompleted);
}
[Fact]
public async Task RunsInBackgroundWithoutFuture()
{
var future = await
new AsyncFunc<bool, string>(
input =>
{
Thread.Sleep(new TimeSpan(0, 0, 0, 0, 100)); //sleep for a second
return "done!";
}
).Invoke(true);
Assert.True(future == "done!","cannot await future");
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Xunit;
using Yaapii.Atoms.Func;
namespace Yaapii.Atoms.Tests.Func
{
public sealed class AsyncFuncTest
{
[Fact]
public void RunsInBackground()
{
var future =
new AsyncFunc<bool, string>(
input =>
{
Thread.Sleep(new TimeSpan(1, 0, 0, 0)); //sleep for a day
return "done!";
}
).Invoke(true);
Assert.True(!future.IsCompleted);
}
[Fact]
public void RunsInBackgroundWithoutFuture()
{
var future =
new AsyncFunc<bool, string>(
input =>
{
Thread.Sleep(new TimeSpan(0, 0, 0, 0, 100)); //sleep for a second
return "done!";
}
).Invoke(true);
Thread.Sleep(1000);
Assert.True(future.IsCompleted,"cannot await future");
Assert.True(future.Result == "done!");
}
}
}
| mit | C# |
da6e8efda7ead1c79358540a7330f809a45de07f | Update ExportVisibleRowsData.cs | asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Articles/ExportVisibleRowsData.cs | Examples/CSharp/Articles/ExportVisibleRowsData.cs | using System.IO;
using Aspose.Cells;
using System.Data;
namespace Aspose.Cells.Examples.Articles
{
public class ExportVisibleRowsData
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir+ "aspose-sample.xlsx";
//Load the source workbook
Workbook workbook = new Workbook(filePath);
//Access the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Specify export table options
ExportTableOptions exportOptions = new ExportTableOptions();
exportOptions.PlotVisibleRows = true;
exportOptions.ExportColumnName = true;
//Export the data from worksheet with export options
DataTable dataTable = worksheet.Cells.ExportDataTable(0, 0, 10, 4, exportOptions);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using System.Data;
namespace Aspose.Cells.Examples.Articles
{
public class ExportVisibleRowsData
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir+ "aspose-sample.xlsx";
//Load the source workbook
Workbook workbook = new Workbook(filePath);
//Access the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Specify export table options
ExportTableOptions exportOptions = new ExportTableOptions();
exportOptions.PlotVisibleRows = true;
exportOptions.ExportColumnName = true;
//Export the data from worksheet with export options
DataTable dataTable = worksheet.Cells.ExportDataTable(0, 0, 10, 4, exportOptions);
}
}
} | mit | C# |
cf6539332e346d82e59f1c969e9ea6fb53ff5896 | Fix Queue's toCustomString (#237) | florinciubotariu/RiotSharp,Oucema90/RiotSharp,aktai0/RiotSharp,jono-90/RiotSharp,Challengermode/RiotSharp,JanOuborny/RiotSharp,BenFradet/RiotSharp,Shidesu/RiotSharp,frederickrogan/RiotSharp,oisindoherty/RiotSharp | RiotSharp/Misc/Queue.cs | RiotSharp/Misc/Queue.cs | using Newtonsoft.Json;
namespace RiotSharp
{
/// <summary>
/// Queue of the league (League API).
/// </summary>
[JsonConverter(typeof(QueueConverter))]
public enum Queue
{
/// <summary>
/// Solo queue 5 vs 5.
/// </summary>
RankedSolo5x5,
/// <summary>
/// Team 3 vs 3.
/// </summary>
RankedTeam3x3,
/// <summary>
/// Team 5 vs 5.
/// </summary>
RankedTeam5x5,
/// <summary>
/// Team 5 v 5 - Dynamic Queue - Ranked
/// </summary>
TeamBuilderDraftRanked5x5,
/// <summary>
/// Team 5 v 5 - Dynamic Queue - Unranked
/// </summary>
TeamBuilderDraftUnranked5x5
}
static class QueueExtension
{
public static string ToCustomString(this Queue queue)
{
switch (queue)
{
case Queue.RankedSolo5x5:
return "RANKED_SOLO_5x5";
case Queue.RankedTeam3x3:
return "RANKED_TEAM_3x3";
case Queue.RankedTeam5x5:
return "RANKED_TEAM_5x5";
case Queue.TeamBuilderDraftRanked5x5:
return "TEAM_BUILDER_DRAFT_RANKED_5x5";
case Queue.TeamBuilderDraftUnranked5x5:
return "TEAM_BUILDER_DRAFT_UNRANKED_5x5";
default:
return string.Empty;
}
}
}
}
| using Newtonsoft.Json;
namespace RiotSharp
{
/// <summary>
/// Queue of the league (League API).
/// </summary>
[JsonConverter(typeof(QueueConverter))]
public enum Queue
{
/// <summary>
/// Solo queue 5 vs 5.
/// </summary>
RankedSolo5x5,
/// <summary>
/// Team 3 vs 3.
/// </summary>
RankedTeam3x3,
/// <summary>
/// Team 5 vs 5.
/// </summary>
RankedTeam5x5,
/// <summary>
/// Team 5 v 5 - Dynamic Queue - Ranked
/// </summary>
TeamBuilderDraftRanked5x5,
/// <summary>
/// Team 5 v 5 - Dynamic Queue - Unranked
/// </summary>
TeamBuilderDraftUnranked5x5
}
static class QueueExtension
{
public static string ToCustomString(this Queue queue)
{
switch (queue)
{
case Queue.RankedSolo5x5:
return "RANKED_SOLO_5x5";
case Queue.RankedTeam3x3:
return "RANKED_TEAM_3x3";
case Queue.RankedTeam5x5:
return "RANKED_TEAM_5x5";
default:
return string.Empty;
}
}
}
}
| mit | C# |
923c9f480ac176c3f734fa3eb6c5bfe95f05b09a | Add support for specifying buffer capacity. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Helpers/ByteArrayBuilder.cs | WalletWasabi/Helpers/ByteArrayBuilder.cs | using System.Text;
namespace System
{
public class ByteArrayBuilder
{
private byte[] _buffer;
public ByteArrayBuilder(): this(4096)
{
}
public ByteArrayBuilder(int capacity)
{
_buffer = new byte[capacity];
Length = 0;
}
public int Length { get; set; }
public ByteArrayBuilder Append(byte b)
{
if (GetUnusedBufferLength() == 0)
{
_buffer = IncreaseCapacity(_buffer, _buffer.Length * 2);
}
_buffer[Length] = b;
Length++;
return this;
}
public ByteArrayBuilder Append(byte[] buffer)
{
var unusedBufferLength = GetUnusedBufferLength();
if (unusedBufferLength < buffer.Length)
{
_buffer = IncreaseCapacity(_buffer, _buffer.Length + buffer.Length);
}
Array.Copy(buffer, 0, _buffer, Length, buffer.Length);
Length += buffer.Length;
return this;
}
public byte[] ToArray()
{
var unusedBufferLength = GetUnusedBufferLength();
if (unusedBufferLength == 0)
{
return _buffer;
}
var result = new byte[Length];
Array.Copy(_buffer, result, result.Length);
return result;
}
/// <summary>
/// UTF8 encoding
/// </summary>
public override string ToString()
{
return ToString(Encoding.UTF8);
}
public string ToString(Encoding encoding)
{
if (Length == 0)
{
return "";
}
return encoding.GetString(ToArray());
}
private int GetUnusedBufferLength()
{
return _buffer.Length - Length;
}
private static byte[] IncreaseCapacity(byte[] buffer, int targetLength)
{
var result = new byte[targetLength];
Array.Copy(buffer, result, buffer.Length);
return result;
}
}
}
| using System.Text;
namespace System
{
public class ByteArrayBuilder
{
private byte[] _buffer;
public ByteArrayBuilder()
{
_buffer = new byte[4096];
Length = 0;
}
public int Length { get; set; }
public ByteArrayBuilder Append(byte b)
{
if (GetUnusedBufferLength() == 0)
{
_buffer = IncreaseCapacity(_buffer, _buffer.Length * 2);
}
_buffer[Length] = b;
Length++;
return this;
}
public ByteArrayBuilder Append(byte[] buffer)
{
var unusedBufferLength = GetUnusedBufferLength();
if (unusedBufferLength < buffer.Length)
{
_buffer = IncreaseCapacity(_buffer, _buffer.Length + buffer.Length);
}
Array.Copy(buffer, 0, _buffer, Length, buffer.Length);
Length += buffer.Length;
return this;
}
public byte[] ToArray()
{
var unusedBufferLength = GetUnusedBufferLength();
if (unusedBufferLength == 0)
{
return _buffer;
}
var result = new byte[Length];
Array.Copy(_buffer, result, result.Length);
return result;
}
/// <summary>
/// UTF8 encoding
/// </summary>
public override string ToString()
{
return ToString(Encoding.UTF8);
}
public string ToString(Encoding encoding)
{
if (Length == 0)
{
return "";
}
return encoding.GetString(ToArray());
}
private int GetUnusedBufferLength()
{
return _buffer.Length - Length;
}
private static byte[] IncreaseCapacity(byte[] buffer, int targetLength)
{
var result = new byte[targetLength];
Array.Copy(buffer, result, buffer.Length);
return result;
}
}
}
| mit | C# |
f3ea5e2226635d2f01dca44bcd923d364f638897 | Rename ClipID to MediaReference | MiXTelematics/MiX.Integrate.Api.Client | MiX.Integrate.Shared/Entities/Events/EventClip.cs | MiX.Integrate.Shared/Entities/Events/EventClip.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace MiX.Integrate.Shared.Entities.Events
{
public class EventClip
{
public long EventId { get; set; }
public string MediaReference { get; set; }
public long AssetId { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace MiX.Integrate.Shared.Entities.Events
{
public class EventClip
{
public long EventId { get; set; }
public string ClipId { get; set; }
public long AssetId { get; set; }
}
}
| mit | C# |
42ff77f26bf073cc7e80a7c46ec1f92736c4a812 | Fix #123 | kjac/FormEditor,kjac/FormEditor,kjac/FormEditor | Source/Umbraco/Views/Partials/FormEditor/FieldsAsync/core.utils.validationerror.cshtml | Source/Umbraco/Views/Partials/FormEditor/FieldsAsync/core.utils.validationerror.cshtml | @inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation>
<div class="text-danger validation-error" ng-show="shouldShowValidationError('@(Model.FormSafeName)', @(ViewBag.FormEditorPageNumber))">
@Model.ErrorMessage
</div>
| @inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.IFieldWithValidation>
<div class="text-danger validation-error hide" ng-class="{show: shouldShowValidationError('@(Model.FormSafeName)', @(ViewBag.FormEditorPageNumber))}">
@Model.ErrorMessage
</div>
| mit | C# |
545c0585e0697190da6b023d5310e17588745c8a | Change order of update operation in RecordRun | lpatalas/ExpressRunner | ExpressRunner/TestItem.cs | ExpressRunner/TestItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using ExpressRunner.Api;
namespace ExpressRunner
{
public class TestItem : PropertyChangedBase, IRunnableTest
{
public string Name
{
get { return Test.Name; }
}
private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>();
public IObservableCollection<TestRun> Runs
{
get { return runs; }
}
private TestStatus status = TestStatus.NotRun;
public TestStatus Status
{
get { return status; }
private set
{
if (status != value)
{
status = value;
NotifyOfPropertyChange("Status");
}
}
}
private readonly Test test;
public Test Test
{
get { return test; }
}
public TestItem(Test test)
{
if (test == null)
throw new ArgumentNullException("test");
this.test = test;
}
public void RecordRun(TestRun run)
{
UpdateStatus(run);
runs.Add(run);
}
private void UpdateStatus(TestRun run)
{
if (run.Status == TestStatus.Failed)
Status = TestStatus.Failed;
else if (Status == TestStatus.NotRun)
Status = run.Status;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
using ExpressRunner.Api;
namespace ExpressRunner
{
public class TestItem : PropertyChangedBase, IRunnableTest
{
public string Name
{
get { return Test.Name; }
}
private readonly BindableCollection<TestRun> runs = new BindableCollection<TestRun>();
public IObservableCollection<TestRun> Runs
{
get { return runs; }
}
private TestStatus status = TestStatus.NotRun;
public TestStatus Status
{
get { return status; }
private set
{
if (status != value)
{
status = value;
NotifyOfPropertyChange("Status");
}
}
}
private readonly Test test;
public Test Test
{
get { return test; }
}
public TestItem(Test test)
{
if (test == null)
throw new ArgumentNullException("test");
this.test = test;
}
public void RecordRun(TestRun run)
{
runs.Add(run);
UpdateStatus(run);
}
private void UpdateStatus(TestRun run)
{
if (run.Status == TestStatus.Failed)
Status = TestStatus.Failed;
else if (Status == TestStatus.NotRun)
Status = run.Status;
}
}
}
| mit | C# |
583a790d97758fcf8ff7ff0da37f82cb38ef4604 | Update SleepLog.cs | amammay/Fitbit.NET,WestDiscGolf/Fitbit.NET,AlexGhiondea/Fitbit.NET,WestDiscGolf/Fitbit.NET,aarondcoleman/Fitbit.NET,aarondcoleman/Fitbit.NET,aarondcoleman/Fitbit.NET,WestDiscGolf/Fitbit.NET,amammay/Fitbit.NET,AlexGhiondea/Fitbit.NET,AlexGhiondea/Fitbit.NET,amammay/Fitbit.NET | Fitbit/Models/SleepLog.cs | Fitbit/Models/SleepLog.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Fitbit.Models
{
public class SleepLog
{
public int AwakeningsCount { get; set; }
public int Duration { get; set; }
public int Efficiency { get; set; }
public bool IsMainSleep { get; set; }
public int LogId { get; set; }
public List<MinuteData> MinuteData { get; set; }
public int MinutesAfterWakeup { get; set; }
public int MinutesAsleep { get; set; }
public int MinutesAwake { get; set; }
public int MinutesToFallAsleep { get; set; }
public DateTime StartTime { get; set; }
public int TimeInBed { get; set; }
public int AwakeCount { get; set; }
public int AwakeDuration { get; set; }
public int RestlessCount { get; set; }
public int RestlessDuration { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Fitbit.Models
{
public class SleepLog
{
public int AwakeningsCount { get; set; }
public int Duration { get; set; }
public int Efficiency { get; set; }
public bool IsMainSleep { get; set; }
public int LogId { get; set; }
public List<MinuteData> MinuteData { get; set; }
public int MinutesAfterWakeup { get; set; }
public int MinutesAsleep { get; set; }
public int MinutesAwake { get; set; }
public int MinutesToFallAsleep { get; set; }
public DateTime StartTime { get; set; }
public int TimeInBed { get; set; }
}
}
| mit | C# |
7527730eb521d8c9375eacb8d7257ef7c49c3a61 | Optimize the detection of IDisposable test classes. Array.Contains performs fewer allocations than the LINQ Any extension method. | fixie/fixie | src/Fixie/Execution/MethodDiscoverer.cs | src/Fixie/Execution/MethodDiscoverer.cs | namespace Fixie.Execution
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class MethodDiscoverer
{
readonly Filter filter;
readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions;
public MethodDiscoverer(Filter filter, Convention convention)
{
this.filter = filter;
testMethodConditions = convention.Config.TestMethodConditions;
}
public IReadOnlyList<MethodInfo> TestMethods(Type testClass)
{
try
{
bool testClassIsDisposable = IsDisposable(testClass);
return testClass
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(method => method.DeclaringType != typeof(object))
.Where(method => !(testClassIsDisposable && HasDisposeSignature(method)))
.Where(IsMatch)
.Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method)))
.ToArray();
}
catch (Exception exception)
{
throw new Exception(
"Exception thrown while attempting to run a custom method-discovery predicate. " +
"Check the inner exception for more details.", exception);
}
}
bool IsMatch(MethodInfo candidate)
=> testMethodConditions.All(condition => condition(candidate));
static bool IsDisposable(Type type)
=> type.GetInterfaces().Contains(typeof(IDisposable));
static bool HasDisposeSignature(MethodInfo method)
=> method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0;
}
} | namespace Fixie.Execution
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
class MethodDiscoverer
{
readonly Filter filter;
readonly IReadOnlyList<Func<MethodInfo, bool>> testMethodConditions;
public MethodDiscoverer(Filter filter, Convention convention)
{
this.filter = filter;
testMethodConditions = convention.Config.TestMethodConditions;
}
public IReadOnlyList<MethodInfo> TestMethods(Type testClass)
{
try
{
bool testClassIsDisposable = IsDisposable(testClass);
return testClass
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(method => method.DeclaringType != typeof(object))
.Where(method => !(testClassIsDisposable && HasDisposeSignature(method)))
.Where(IsMatch)
.Where(method => filter.IsSatisfiedBy(new MethodGroup(testClass, method)))
.ToArray();
}
catch (Exception exception)
{
throw new Exception(
"Exception thrown while attempting to run a custom method-discovery predicate. " +
"Check the inner exception for more details.", exception);
}
}
bool IsMatch(MethodInfo candidate)
=> testMethodConditions.All(condition => condition(candidate));
static bool IsDisposable(Type type)
=> type.GetInterfaces().Any(interfaceType => interfaceType == typeof(IDisposable));
static bool HasDisposeSignature(MethodInfo method)
=> method.Name == "Dispose" && method.IsVoid() && method.GetParameters().Length == 0;
}
} | mit | C# |
bd68ab67e2574353f6fc4486a07b7744dbac72ec | Add parent and child app skeleton | brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync | projects/AlertSample/source/AlertSample.App/Program.cs | projects/AlertSample/source/AlertSample.App/Program.cs | //-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace AlertSample
{
using System;
internal sealed class Program
{
private static int Main(string[] args)
{
if (args.Length == 0)
{
return RunParent();
}
else if (args.Length == 1)
{
return RunChild(args[0]);
}
else
{
Console.WriteLine("Invalid arguments.");
return 1;
}
}
private static int RunParent()
{
Alert alert = new Alert("AlertSample", 5.0d, 10.0d);
try
{
alert.Start();
}
catch (Exception e)
{
Console.WriteLine("ERROR: {0}", e);
throw;
}
finally
{
alert.Stop();
}
return 0;
}
private static int RunChild(string name)
{
Console.WriteLine("TODO: " + name);
return 0;
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace AlertSample
{
using System;
internal sealed class Program
{
private static void Main(string[] args)
{
Alert alert = new Alert("AlertSample", 5.0d, 10.0d);
try
{
alert.Start();
}
catch (Exception e)
{
Console.WriteLine("ERROR: {0}", e);
throw;
}
finally
{
alert.Stop();
}
}
}
}
| unlicense | C# |
043512d204ee12df98c8e176169ed1cd360a72fa | fix faulty razor code in view | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.Web/Views/Transfers/TransferConnectionInvitationAuthorization.cshtml | src/SFA.DAS.EmployerAccounts.Web/Views/Transfers/TransferConnectionInvitationAuthorization.cshtml | @using SFA.DAS.EmployerAccounts.Authorisation
@using SFA.DAS.EmployerAccounts.Web.Helpers
@model TransferConnectionInvitationAuthorizationViewModel
<p>Employers who pay the apprenticeship levy can connect with other employers and transfer up to @Model.TransferAllowancePercentage.ToString("N0")% of their previous year's annual funds.</p>
@if (Model.AuthorizationResult.IsAuthorized)
{
<p>Before starting a connection, both the sending and receiving employers need to read and understand the <a href="https://www.gov.uk/government/publications/apprenticeship-funding-and-performance-management-rules-2017-to-2018" class="govuk-link" rel="nofollow">rules for sending and receiving transfers</a>.</p>
<div class="govuk-inset-text">
<p>Only the sending employer can start a connection.</p>
</div>
if (Model.IsValidSender)
{
<a class="govuk-button" href="@Url.Action("Index", "TransferConnectionInvitations" )">Connect to a receiving employer</a>
}
}
else if (Model.AuthorizationResult.HasError<EmployerFeatureAgreementNotSigned>())
{
<p>Before starting a connection, both the sending and receiving employers need to read and understand the <a href="https://www.gov.uk/guidance/apprenticeship-funding-rules" class="govuk-link" rel="nofollow">rules for sending and receiving transfers</a> and accept the updated organisation agreement with ESFA.</p>
<a class="govuk-button" href="@Url.Action("Index", "EmployerAgreement" )">Accept ESFA agreement</a>
}
else
{
throw new ArgumentOutOfRangeException();
}
| @using SFA.DAS.EmployerAccounts.Authorisation
@using SFA.DAS.EmployerAccounts.Web.Helpers
@model TransferConnectionInvitationAuthorizationViewModel
<p>Employers who pay the apprenticeship levy can connect with other employers and transfer up to @Model.TransferAllowancePercentage.ToString("N0")% of their previous year's annual funds.</p>
if (Model.AuthorizationResult.IsAuthorized)
{
<p>Before starting a connection, both the sending and receiving employers need to read and understand the <a href="https://www.gov.uk/government/publications/apprenticeship-funding-and-performance-management-rules-2017-to-2018" class="govuk-link" rel="nofollow">rules for sending and receiving transfers</a>.</p>
<div class="govuk-inset-text">
<p>Only the sending employer can start a connection.</p>
</div>
if (Model.IsValidSender)
{
<a class="govuk-button" href="@Url.Action("Index", "TransferConnectionInvitations" )">Connect to a receiving employer</a>
}
}
else if (Model.AuthorizationResult.HasError<EmployerFeatureAgreementNotSigned>())
{
<p>Before starting a connection, both the sending and receiving employers need to read and understand the <a href="https://www.gov.uk/guidance/apprenticeship-funding-rules" class="govuk-link" rel="nofollow">rules for sending and receiving transfers</a> and accept the updated organisation agreement with ESFA.</p>
<a class="govuk-button" href="@Url.Action("Index", "EmployerAgreement" )">Accept ESFA agreement</a>
}
else
{
throw new ArgumentOutOfRangeException();
}
| mit | C# |
2cf565eba5464b2527fd94f8c507dbbb1cd2b1a5 | Change build script to run MSTest v2 | fwinkelbauer/Jeeves | Source/build.cake | Source/build.cake | #load "artifact.cake"
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
Task("Clean")
.Does(() =>
{
CleanArtifacts();
CleanDirectories($"Jeeves*/bin/{configuration}");
CleanDirectory("TestResults");
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore("Jeeves.sln");
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
MSBuild("Jeeves.sln", new MSBuildSettings { Configuration = configuration, WarningsAsError = true });
StoreBuildArtifacts("Jeeves", $"Jeeves/bin/{configuration}/**/*");
StoreBuildArtifacts("Jeeves.Core", $"Jeeves.Core/bin/{configuration}/**/*");
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
VSTest($"*.UnitTests/bin/{configuration}/*.UnitTests.dll", new VSTestSettings { Logger = "trx", TestAdapterPath = "." });
});
Task("Pack")
.IsDependentOn("Test")
.Does(() =>
{
StoreChocolateyArtifact("NuSpec/Chocolatey/Jeeves.nuspec");
StoreNuGetArtifact("NuSpec/NuGet/Jeeves.Core.nuspec");
});
Task("Publish")
.IsDependentOn("Pack")
.Does(() =>
{
PublishNuGetArtifact("Jeeves.Core", "https://www.nuget.org/api/v2/package");
});
Task("Default").IsDependentOn("Pack").Does(() => { });
RunTarget(target);
| #load "artifact.cake"
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
Task("Clean")
.Does(() =>
{
CleanArtifacts();
CleanDirectories($"Jeeves*/bin/{configuration}");
CleanDirectory("TestResults");
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
NuGetRestore("Jeeves.sln");
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
MSBuild("Jeeves.sln", new MSBuildSettings { Configuration = configuration, WarningsAsError = true });
StoreBuildArtifacts("Jeeves", $"Jeeves/bin/{configuration}/**/*");
StoreBuildArtifacts("Jeeves.Core", $"Jeeves.Core/bin/{configuration}/**/*");
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
MSTest($"*.UnitTests/bin/{configuration}/*.UnitTests.dll");
});
Task("Pack")
.IsDependentOn("Test")
.Does(() =>
{
StoreChocolateyArtifact("NuSpec/Chocolatey/Jeeves.nuspec");
StoreNuGetArtifact("NuSpec/NuGet/Jeeves.Core.nuspec");
});
Task("Publish")
.IsDependentOn("Pack")
.Does(() =>
{
PublishNuGetArtifact("Jeeves.Core", "https://www.nuget.org/api/v2/package");
});
Task("Default").IsDependentOn("Pack").Does(() => { });
RunTarget(target);
| mit | C# |
c533fc0085eea2f7f43d85e826c6ce7bafcb2a01 | add fields to authrequest | FirebrandTech/fcs-sdk-net,FirebrandTech/fcs-sdk-net,FirebrandTech/fcs-sdk-net | Src/Model/Auth.cs | Src/Model/Auth.cs | // Copyright © 2010-2014 Firebrand Technologies
using System;
using ServiceStack;
namespace Fcs.Model {
[Route("/auth", "GET", Summary = "Get Authorization or Redirect if not Authenticated")]
[Route("/auth", "POST", Summary = "Authenticate or Login User")]
[Route("/auth", "DELETE", Summary = "Unauthenticate or Log off User")]
public class AuthRequest : IReturn<AuthResponse> {
public string UserName { get; set; }
public string Password { get; set; }
//public string ImpersonateUserName { get; set; }
//public string AccessToken { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Continue { get; set; }
public string Uri { get; set; }
public string SessionId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
[Route("/auth/uri", "GET", Summary = "Redirect to Login Page")]
public class AuthUriRequest {
public string Site { get; set; }
public string Email { get; set; }
}
public class AuthUriResponse {
public string Uri { get; set; }
}
public class AuthResponse {
public string Token { get; set; }
public DateTime? Expires { get; set; }
public string Session { get; set; }
public string UserName { get; set; }
public string Continue { get; set; }
}
} | // Copyright © 2010-2014 Firebrand Technologies
using System;
using ServiceStack;
namespace Fcs.Model {
[Route("/auth", "GET", Summary = "Get Authorization or Redirect if not Authenticated")]
[Route("/auth", "POST", Summary = "Authenticate or Login User")]
[Route("/auth", "DELETE", Summary = "Unauthenticate or Log off User")]
public class AuthRequest : IReturn<AuthResponse> {
public string UserName { get; set; }
public string Password { get; set; }
//public string ImpersonateUserName { get; set; }
//public string AccessToken { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Continue { get; set; }
public string Uri { get; set; }
}
[Route("/auth/uri", "GET", Summary = "Redirect to Login Page")]
public class AuthUriRequest {
public string Site { get; set; }
public string Email { get; set; }
}
public class AuthUriResponse {
public string Uri { get; set; }
}
public class AuthResponse {
public string Token { get; set; }
public DateTime? Expires { get; set; }
public string Session { get; set; }
public string UserName { get; set; }
public string Continue { get; set; }
}
} | mit | C# |
178b50b8c548a6a3931382784494ac72c44d7b02 | Fix paging for vacancies | dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua | src/WebSite/Views/Home/Vacancies.cshtml | src/WebSite/Views/Home/Vacancies.cshtml | @using X.PagedList;
@using X.PagedList.Mvc.Core;
@model IPagedList<Core.ViewModels.VacancyViewModel>
@{
var categoryId = ViewBag.CategoryId as int?;
}
@section head {
<meta property="og:title" content="@Core.Settings.Current.WebSiteTitle" />
<meta property="og:type" content="website" />
<meta property="og:image" content="@Core.Settings.Current.FacebookImage" />
<meta property="og:description" content="@Core.Settings.Current.DefaultDescription" />
<meta name="keywords" content="@Core.Settings.Current.DefaultKeywords" />
<meta name="description" content="@Core.Settings.Current.DefaultDescription" />
}
<h1>@ViewData["Title"]</h1>
@foreach (var v in Model)
{
@Html.Partial("_Vacancy", v)
}
@if (categoryId != null){
@Html.PagedListPager(Model, page => $"/vacancies/{page}?categoryId={categoryId}")
} else {
@Html.PagedListPager(Model, page => $"/vacancies/{page}")
}
| @using X.PagedList;
@using X.PagedList.Mvc.Core;
@model IPagedList<Core.ViewModels.VacancyViewModel>
@{
var categoryId = ViewBag.CategoryId as int?;
}
@section head {
<meta property="og:title" content="@Core.Settings.Current.WebSiteTitle" />
<meta property="og:type" content="website" />
<meta property="og:image" content="@Core.Settings.Current.FacebookImage" />
<meta property="og:description" content="@Core.Settings.Current.DefaultDescription" />
<meta name="keywords" content="@Core.Settings.Current.DefaultKeywords" />
<meta name="description" content="@Core.Settings.Current.DefaultDescription" />
}
<h1>@ViewData["Title"]</h1>
@foreach (var v in Model)
{
@Html.Partial("_Vacancy", v)
}
@if (categoryId != null){
@Html.PagedListPager(Model, page => $"/page/{page}?categoryId={categoryId}")
} else {
@Html.PagedListPager(Model, page => $"/page/{page}")
}
| mit | C# |
fbcc612fbdef66a614cb211dccbabf40736ddde6 | Add blocking statement to ensure service remains alive | timclipsham/tfs-hipchat | TfsHipChat/Program.cs | TfsHipChat/Program.cs | using System;
using System.ServiceModel;
namespace TfsHipChat
{
class Program
{
static void Main()
{
using (var host = new ServiceHost(typeof(CheckinEventService)))
{
host.Open();
Console.WriteLine("TfsHipChat started!");
Console.ReadLine();
}
}
}
}
| using System.ServiceModel;
namespace TfsHipChat
{
class Program
{
static void Main()
{
using (var host = new ServiceHost(typeof(CheckinEventService)))
{
host.Open();
}
}
}
}
| mit | C# |
5104195f27f3fdcfe3bca338df7fa72e402d8120 | Update field enumeration for order processor | Suneco/Suneco.SitecoreBlogs.CustomExperienceProfile,Suneco/Suneco.SitecoreBlogs.CustomExperienceProfile | Suneco.SitecoreBlogs.CustomExperienceProfile/Pipelines/Reporting/ExperienceProfile/GetOrderData.cs | Suneco.SitecoreBlogs.CustomExperienceProfile/Pipelines/Reporting/ExperienceProfile/GetOrderData.cs | namespace Suneco.SitecoreBlogs.CustomExperienceProfile.Pipelines.Reporting.ExperienceProfile
{
using System;
using System.Data;
using Extensions;
using Services;
using Sitecore.Cintel.Reporting;
using Sitecore.Cintel.Reporting.Processors;
public class GetOrderData : ReportProcessorBase
{
public enum OrderFields
{
Number = 0,
Date = 1,
TotalExclTax = 2,
TotalInclTax = 3
}
public override void Process(ReportProcessorArgs args)
{
var result = args.QueryResult;
args.ResultTableForView = new DataTable();
this.InitializeDataTable(args.ResultTableForView);
this.PopulateData(args.ResultTableForView, args.ReportParameters.ContactId);
args.ResultSet.Data.Dataset[args.ReportParameters.ViewName] = args.ResultTableForView;
}
private void InitializeDataTable(DataTable table)
{
table.AddViewField<long>(OrderFields.Number.ToString());
table.AddViewField<string>(OrderFields.Date.ToString());
table.AddViewField<decimal>(OrderFields.TotalExclTax.ToString());
table.AddViewField<decimal>(OrderFields.TotalInclTax.ToString());
}
private void PopulateData(DataTable table, Guid contactId)
{
var orders = ShopService.GetOrders(contactId);
foreach (var order in orders)
{
var row = table.NewRow();
row.SetField(OrderFields.Number.ToString(), order.Number);
row.SetField(OrderFields.Date.ToString(), order.OrderDate);
row.SetField(OrderFields.TotalExclTax.ToString(), order.TotalExclTax);
row.SetField(OrderFields.TotalInclTax.ToString(), order.TotalInclTax);
table.Rows.Add(row);
}
}
}
} | namespace Suneco.SitecoreBlogs.CustomExperienceProfile.Pipelines.Reporting.ExperienceProfile
{
using System;
using System.Data;
using Extensions;
using Services;
using Sitecore.Cintel.Reporting;
using Sitecore.Cintel.Reporting.Processors;
public class GetOrderData : ReportProcessorBase
{
public enum CustomDataFields
{
Number = 0,
Date = 1,
TotalExclTax = 2,
TotalInclTax = 3
}
public override void Process(ReportProcessorArgs args)
{
var result = args.QueryResult;
args.ResultTableForView = new DataTable();
this.InitializeDataTable(args.ResultTableForView);
this.PopulateData(args.ResultTableForView, args.ReportParameters.ContactId);
args.ResultSet.Data.Dataset[args.ReportParameters.ViewName] = args.ResultTableForView;
}
private void InitializeDataTable(DataTable table)
{
table.AddViewField<long>(CustomDataFields.Number.ToString());
table.AddViewField<string>(CustomDataFields.Date.ToString());
table.AddViewField<decimal>(CustomDataFields.TotalExclTax.ToString());
table.AddViewField<decimal>(CustomDataFields.TotalInclTax.ToString());
}
private void PopulateData(DataTable table, Guid contactId)
{
var orders = ShopService.GetOrders(contactId);
foreach (var order in orders)
{
var row = table.NewRow();
row.SetField(CustomDataFields.Number.ToString(), order.Number);
row.SetField(CustomDataFields.Date.ToString(), order.OrderDate);
row.SetField(CustomDataFields.TotalExclTax.ToString(), order.TotalExclTax);
row.SetField(CustomDataFields.TotalInclTax.ToString(), order.TotalInclTax);
table.Rows.Add(row);
}
}
}
} | mit | C# |
8ca50aa111f2ef07067f3a00103c2b34d85aec9e | Update using Linq | nmtoan07/AspNetCoreSPA,nmtoan07/AspNetCoreSPA,nmtoan07/AspNetCoreSPA | src/AspNetCoreSPA.Web/Controllers/StudentController.cs | src/AspNetCoreSPA.Web/Controllers/StudentController.cs | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCoreSPA.Web.Controllers
{
[Route("api/student")]
public class StudentController : Controller
{
private static List<Student> _students = new List<Student>
{
new Student { FirstName = "John", LastName = "Doe", Email = "john@example.com"},
new Student { FirstName = "Mary", LastName = "Moe", Email = "mary@example.com"},
new Student { FirstName = "July", LastName = "Dooley", Email = "july@example.com"}
};
[Route("getAll")]
[HttpGet]
public IActionResult GetAll()
{
return Json(_students);
}
[Route("createStudent")]
[HttpPost]
public IActionResult CreateStudent([FromBody] Student student)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_students.Add(student);
return Json(_students);
}
[Route("searchStudent")]
[HttpGet]
public IActionResult Search([FromQuery] string firstName)
{
return Json(_students.Where(student => student.FirstName.Equals(firstName)));
}
}
public class Student
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCoreSPA.Web.Controllers
{
[Route("api/student")]
public class StudentController : Controller
{
private static List<Student> _students = new List<Student>
{
new Student { FirstName = "John", LastName = "Doe", Email = "john@example.com"},
new Student { FirstName = "Mary", LastName = "Moe", Email = "mary@example.com"},
new Student { FirstName = "July", LastName = "Dooley", Email = "july@example.com"}
};
[Route("getAll")]
[HttpGet]
public IActionResult GetAll()
{
return Json(_students);
}
[Route("createStudent")]
[HttpPost]
public IActionResult CreateStudent([FromBody] Student student)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
_students.Add(student);
return Json(_students);
}
[Route("searchStudent")]
[HttpGet]
public IActionResult Search([FromQuery] string firstName)
{
return Json(_students.Where(student => student.FirstName.Equals(firstName)));
}
}
public class Student
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
}
}
| mit | C# |
7328eec1115f4622ee3fcc698f9d244380a96b38 | add test around internally-used class | fluffynuts/PeanutButter,fluffynuts/PeanutButter,fluffynuts/PeanutButter | source/Utils/PeanutButter.DuckTyping.Tests/Extensions/TestDictionaryWrappingNameValueCollection.cs | source/Utils/PeanutButter.DuckTyping.Tests/Extensions/TestDictionaryWrappingNameValueCollection.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using NUnit.Framework;
using PeanutButter.DuckTyping.Extensions;
using PeanutButter.Utils;
using static PeanutButter.RandomGenerators.RandomValueGen;
namespace PeanutButter.DuckTyping.Tests.Extensions
{
[TestFixture]
public class TestDictionaryWrappingNameValueCollection: AssertionHelper
{
[Test]
public void ExplicitIEnumerator_GetEnumerator_ShouldReturnSameAs_GenericMethod()
{
// Arrange
var sut = Create();
// Pre-Assert
// Act
var reference = sut.GetEnumerator();
var result = (sut as IEnumerable).GetEnumerator();
// Assert
Expect(reference, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(result, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(reference.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
Expect(result.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
}
[Test]
public void Add_GivenKeyValuePair_ShouldAddItToTheUnderlyingCollection()
{
// Arrange
var collection = new NameValueCollection();
var sut = Create(collection);
var kvp = GetRandom<KeyValuePair<string, object>>();
// Pre-Assert
// Act
sut.Add(kvp);
// Assert
Expect(collection[kvp.Key], Is.EqualTo(kvp.Value));
}
private DictionaryWrappingNameValueCollection Create(
NameValueCollection collection = null,
bool caseInsensitive = false
) {
return new DictionaryWrappingNameValueCollection(
collection ?? new NameValueCollection(),
caseInsensitive
);
}
}
}
| using System.Collections;
using System.Collections.Specialized;
using NUnit.Framework;
using PeanutButter.DuckTyping.Extensions;
using PeanutButter.Utils;
namespace PeanutButter.DuckTyping.Tests.Extensions
{
[TestFixture]
public class TestDictionaryWrappingNameValueCollection: AssertionHelper
{
[Test]
public void ExplicitIEnumerator_GetEnumerator_ShouldReturnSameAs_GenericMethod()
{
// Arrange
var sut = Create();
// Pre-Assert
// Act
var reference = sut.GetEnumerator();
var result = (sut as IEnumerable).GetEnumerator();
// Assert
Expect(reference, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(result, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(reference.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
Expect(result.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
}
private DictionaryWrappingNameValueCollection Create(
NameValueCollection collection = null,
bool caseInsensitive = false
) {
return new DictionaryWrappingNameValueCollection(
collection ?? new NameValueCollection(),
caseInsensitive
);
}
}
}
| bsd-3-clause | C# |
f8d8073dcfb5355eaa523a0d3eb542bc026f5e9f | Use nullable | physhi/roslyn,wvdd007/roslyn,tannergooding/roslyn,aelij/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,abock/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,agocke/roslyn,mgoertz-msft/roslyn,aelij/roslyn,stephentoub/roslyn,tannergooding/roslyn,KevinRansom/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,abock/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,panopticoncentral/roslyn,eriawan/roslyn,reaction1989/roslyn,weltkante/roslyn,wvdd007/roslyn,physhi/roslyn,eriawan/roslyn,abock/roslyn,weltkante/roslyn,jmarolf/roslyn,sharwell/roslyn,diryboy/roslyn,panopticoncentral/roslyn,genlu/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,AmadeusW/roslyn,dotnet/roslyn,brettfo/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,genlu/roslyn,weltkante/roslyn,agocke/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,aelij/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,stephentoub/roslyn,diryboy/roslyn,gafter/roslyn,reaction1989/roslyn,davkean/roslyn,gafter/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,tmat/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,eriawan/roslyn,tmat/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,gafter/roslyn,bartdesmet/roslyn,mavasani/roslyn,brettfo/roslyn,brettfo/roslyn,agocke/roslyn,bartdesmet/roslyn,physhi/roslyn,mavasani/roslyn,dotnet/roslyn,davkean/roslyn,AlekseyTs/roslyn,tmat/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,diryboy/roslyn,sharwell/roslyn | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | src/Workspaces/Core/Portable/Workspace/Host/PersistentStorage/IPersistentStorageLocationService.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#nullable enable
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
string? TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public string? TryGetStorageLocation(Solution solution)
{
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(appDataFolder, "Roslyn", kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Composition;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Serialization;
namespace Microsoft.CodeAnalysis.Host
{
interface IPersistentStorageLocationService : IWorkspaceService
{
string TryGetStorageLocation(Solution solution);
}
[ExportWorkspaceService(typeof(IPersistentStorageLocationService)), Shared]
internal class DefaultPersistentStorageLocationService : IPersistentStorageLocationService
{
[ImportingConstructor]
public DefaultPersistentStorageLocationService()
{
}
public string TryGetStorageLocation(Solution solution)
{
if (string.IsNullOrWhiteSpace(solution.FilePath))
return null;
// Ensure that each unique workspace kind for any given solution has a unique
// folder to store their data in.
// Store in the LocalApplicationData/Roslyn/hash folder (%appdatalocal%/... on Windows,
// ~/.local/share/... on unix). This will place the folder in a location we can trust
// to be able to get back to consistently as long as we're working with the same
// solution and the same workspace kind.
var appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.Create);
var kind = StripInvalidPathChars(solution.Workspace.Kind ?? "");
var hash = StripInvalidPathChars(Checksum.Create(solution.FilePath).ToString());
return Path.Combine(appDataFolder, "Roslyn", kind, hash);
static string StripInvalidPathChars(string val)
{
var invalidPathChars = Path.GetInvalidPathChars();
val = new string(val.Where(c => !invalidPathChars.Contains(c)).ToArray());
return string.IsNullOrWhiteSpace(val) ? "None" : val;
}
}
}
}
| mit | C# |
93457df44c4ec18e97dbfa6f54058b406e055353 | Add one line in RestApiHelper | LordZoltan/docfx,928PJY/docfx,928PJY/docfx,LordZoltan/docfx,dotnet/docfx,dotnet/docfx,928PJY/docfx,superyyrrzz/docfx,superyyrrzz/docfx,DuncanmaMSFT/docfx,pascalberger/docfx,pascalberger/docfx,hellosnow/docfx,LordZoltan/docfx,LordZoltan/docfx,DuncanmaMSFT/docfx,hellosnow/docfx,hellosnow/docfx,superyyrrzz/docfx,pascalberger/docfx,dotnet/docfx | src/Microsoft.DocAsCode.Build.RestApi/RestApiHelper.cs | src/Microsoft.DocAsCode.Build.RestApi/RestApiHelper.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.RestApi
{
using System;
using Microsoft.DocAsCode.Utility;
public static class RestApiHelper
{
/// <summary>
/// Reverse to reference unescape described in http://tools.ietf.org/html/rfc6901#section-4
/// </summary>
/// <param name="reference"></param>
/// <returns></returns>
public static string FormatDefinitionSinglePath(string reference)
{
return reference.Replace("~", "~0").Replace("/", "~1");
}
/// <summary>
/// When the reference starts with '#/', treat it as URI Fragment Identifier Representation and decode.
/// When the reference starts with '/', treat it as JSON String Representation and keep it as.
/// Refer to: https://tools.ietf.org/html/rfc6901#section-5
/// </summary>
/// <param name="reference"></param>
/// <returns></returns>
public static string FormatReferenceFullPath(string reference)
{
// Decode for URI Fragment Identifier Representation
if (reference.StartsWith("#/"))
{
// Reuse relative path, to decode the values inside '/'.
var path = reference.Substring(2);
return "/" + ((RelativePath)path).UrlDecode();
}
// Not decode for JSON String Representation
if (reference.StartsWith("/"))
{
return reference;
}
throw new InvalidOperationException($"Full reference path \"{reference}\" must start with '/' or '#/'");
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.RestApi
{
using System;
using Microsoft.DocAsCode.Utility;
public static class RestApiHelper
{
/// <summary>
/// Reverse to reference unescape described in http://tools.ietf.org/html/rfc6901#section-4
/// </summary>
/// <param name="reference"></param>
/// <returns></returns>
public static string FormatDefinitionSinglePath(string reference)
{
return reference.Replace("~", "~0").Replace("/", "~1");
}
/// <summary>
/// When the reference starts with '#/', treat it as URI Fragment Identifier Representation and decode.
/// When the reference starts with '/', treat it as JSON String Representation and keep it as.
/// Refer to: https://tools.ietf.org/html/rfc6901#section-5
/// </summary>
/// <param name="reference"></param>
/// <returns></returns>
public static string FormatReferenceFullPath(string reference)
{
// Decode for URI Fragment Identifier Representation
if (reference.StartsWith("#/"))
{
// Reuse relative path, to decode the values inside '/'.
var path = reference.Substring(2);
return "/" + ((RelativePath)path).UrlDecode();
}
// Not decode for JSON String Representation
if (reference.StartsWith("/"))
{
return reference;
}
throw new InvalidOperationException($"Full reference path \"{reference}\" must start with '/' or '#/'");
}
}
}
| mit | C# |
8e3112d4f116cca791f92e4d3010eaeb153f8737 | correct sheard to shared | mschray/CalendarHelper | shared/LogHelper.csx | shared/LogHelper.csx | public static class LogHelper
{
private static TraceWriter logger;
public static void Initialize(TraceWriter log)
{
if (!logger) logger = log;
}
public static void Info(TraceWriter log, string logtext)
{
logger.Info(logtext);
}
public static void Error(TraceWriter log, string logtext)
{
logger.Error(logtext);
}
} | public static class LogHelper
{
private static TraceWriter logger;
public static void InitializeLogger(TraceWriter log)
{
if (!logger) logger = log;
}
public static void Info(TraceWriter log, string logtext)
{
logger.Info(logtext);
}
public static void Error(TraceWriter log, string logtext)
{
logger.Error(logtext);
}
} | mit | C# |
58993c32a6d02349af50c5961cebacce88fdf9f7 | add ztlog folder | asmrobot/ZTImage | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ZTImage")]
[assembly: AssemblyDescription("base libs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ZTImage.com")]
[assembly: AssemblyProduct("ZTImage")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("5951906a-f1c5-4b70-a695-4ec905d2dd21")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.4.5")]
[assembly: AssemblyFileVersion("1.0.4.5")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ZTImage")]
[assembly: AssemblyDescription("base libs")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ZTImage.com")]
[assembly: AssemblyProduct("ZTImage")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("5951906a-f1c5-4b70-a695-4ec905d2dd21")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.4.4")]
[assembly: AssemblyFileVersion("1.0.4.4")]
| apache-2.0 | C# |
573627e463751ab35896a1546474c2993f6ef75b | update hello.cs | honux77/prostar,honux77/prostar | week2/hello/hello.cs | week2/hello/hello.cs | using System;
namespace Hoyoung {
class HelloNext {
static void Main(String[] args) {
Console.WriteLine("Hello, Next");
if(args.Length !=0)
Print(args);
else
Console.WriteLine("Usage> " +AppDomain.CurrentDomain.FriendlyName + " NAME");
}
static void Print(String[] hi) {
Console.Write("Hello, ");
for (int i = 0; i < hi.Length; i++)
Console.Write(hi[i] +" ");
Console.Write("\n");
}
}
}
| using System;
namespace Hoyoung {
class HelloNext {
static void Main(String[] args) {
Console.WriteLine("Hello, Next");
Console.WriteLine("Hello, {0}!", args[0]);
}
}
}
| mit | C# |
3c48f7537ce3e44e875d42c47ebec12add2026cf | Improve exception catching in integration tests | Jericho/CakeMail.RestClient | CakeMail.RestClient.IntegrationTests/Program.cs | CakeMail.RestClient.IntegrationTests/Program.cs | using System;
using System.Configuration;
namespace CakeMail.RestClient.IntegrationTests
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0} Executing all CakeMail API methods ... {0}", new string('=', 10));
try
{
ExecuteAllMethods();
}
catch (Exception e)
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("An error has occured: {0}", (e.InnerException ?? e).Message);
}
finally
{
// Clear the keyboard buffer
while (Console.KeyAvailable) { Console.ReadKey(); }
Console.WriteLine("");
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
static void ExecuteAllMethods()
{
var apiKey = ConfigurationManager.AppSettings["ApiKey"];
var userName = ConfigurationManager.AppSettings["UserName"];
var password = ConfigurationManager.AppSettings["Password"];
var overrideClientId = ConfigurationManager.AppSettings["OverrideClientId"];
var api = new CakeMailRestClient(apiKey);
var loginInfo = api.Users.LoginAsync(userName, password).Result;
var clientId = string.IsNullOrEmpty(overrideClientId) ? loginInfo.ClientId : long.Parse(overrideClientId);
var userKey = loginInfo.UserKey;
TimezonesTests.ExecuteAllMethods(api).Wait();
CountriesTests.ExecuteAllMethods(api).Wait();
ClientsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
UsersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
PermissionsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
CampaignsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
ListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TemplatesTests.ExecuteAllMethods(api, userKey, clientId).Wait();
SuppressionListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
RelaysTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TriggersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
MailingsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
}
}
}
| using System;
using System.Configuration;
namespace CakeMail.RestClient.IntegrationTests
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0} Executing all CakeMail API methods ... {0}", new string('=', 10));
try
{
ExecuteAllMethods();
}
catch (Exception e)
{
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("An error has occured: {0}", e.Message);
}
finally
{
// Clear the keyboard buffer
while (Console.KeyAvailable) { Console.ReadKey(); }
Console.WriteLine("");
Console.WriteLine("Press any key...");
Console.ReadKey();
}
}
static void ExecuteAllMethods()
{
var apiKey = ConfigurationManager.AppSettings["ApiKey"];
var userName = ConfigurationManager.AppSettings["UserName"];
var password = ConfigurationManager.AppSettings["Password"];
var overrideClientId = ConfigurationManager.AppSettings["OverrideClientId"];
var api = new CakeMailRestClient(apiKey);
var loginInfo = api.Users.LoginAsync(userName, password).Result;
var clientId = string.IsNullOrEmpty(overrideClientId) ? loginInfo.ClientId : long.Parse(overrideClientId);
var userKey = loginInfo.UserKey;
TimezonesTests.ExecuteAllMethods(api).Wait();
CountriesTests.ExecuteAllMethods(api).Wait();
ClientsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
UsersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
PermissionsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
CampaignsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
ListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TemplatesTests.ExecuteAllMethods(api, userKey, clientId).Wait();
SuppressionListsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
RelaysTests.ExecuteAllMethods(api, userKey, clientId).Wait();
TriggersTests.ExecuteAllMethods(api, userKey, clientId).Wait();
MailingsTests.ExecuteAllMethods(api, userKey, clientId).Wait();
}
}
}
| mit | C# |
e6a35e0b1396e5436225039664ca256dd2c8fa24 | Update AtataContext configuring in SetUpFixture of AtataSamples.MultipleBrowsersViaFixtureArguments project | atata-framework/atata-samples | MultipleBrowsersViaFixtureArguments/AtataSamples.MultipleBrowsersViaFixtureArguments/SetUpFixture.cs | MultipleBrowsersViaFixtureArguments/AtataSamples.MultipleBrowsersViaFixtureArguments/SetUpFixture.cs | using System;
using Atata;
using NUnit.Framework;
namespace AtataSamples.MultipleBrowsersViaFixtureArguments
{
[SetUpFixture]
public class SetUpFixture
{
[OneTimeSetUp]
public void GlobalSetUp()
{
AtataContext.GlobalConfiguration.
UseChrome().
WithArguments("start-maximized").
UseInternetExplorer().
// TODO: Specify Internet Explorer settings, like:
// WithOptions(x => x.EnableNativeEvents = true).
WithDriverPath(Environment.GetEnvironmentVariable("IEWebDriver") ?? AppDomain.CurrentDomain.BaseDirectory).
UseFirefox().
// TODO: You can also specify remote driver configuration(s):
WithDriverPath(Environment.GetEnvironmentVariable("GeckoWebDriver") ?? AppDomain.CurrentDomain.BaseDirectory).
// UseRemoteDriver().
// WithAlias("chrome_remote").
// WithRemoteAddress("http://127.0.0.1:4444/wd/hub").
// WithOptions(new ChromeOptions()).
UseBaseUrl("https://atata-framework.github.io/atata-sample-app/#!/").
AddNUnitTestContextLogging().
LogNUnitError();
}
}
}
| using Atata;
using NUnit.Framework;
namespace AtataSamples.MultipleBrowsersViaFixtureArguments
{
[SetUpFixture]
public class SetUpFixture
{
[OneTimeSetUp]
public void GlobalSetUp()
{
AtataContext.GlobalConfiguration.
UseChrome().
WithArguments("start-maximized").
UseInternetExplorer().
// TODO: Specify Internet Explorer settings, like:
// WithOptions(x => x.EnableNativeEvents = true).
UseFirefox().
// TODO: You can also specify remote driver configuration(s):
// UseRemoteDriver().
// WithAlias("chrome_remote").
// WithRemoteAddress("http://127.0.0.1:4444/wd/hub").
// WithOptions(new ChromeOptions()).
UseBaseUrl("https://atata-framework.github.io/atata-sample-app/#!/").
AddNUnitTestContextLogging().
LogNUnitError();
}
}
}
| apache-2.0 | C# |
7ec7a5d16bd8a94cdc7c4df97135a958bbb1fc21 | 添加微信支付V3单元测试(尚未完成) | JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,lishewen/WeiXinMPSDK,lishewen/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK | src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3.Test/Apis/BasePay/BasePayApisTests.cs | src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3.Test/Apis/BasePay/BasePayApisTests.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.TenPayV3.Apis;
using Senparc.Weixin.TenPayV3.Apis.BasePay;
using Senparc.Weixin.TenPayV3.Entities;
using Senparc.Weixin.TenPayV3.Helpers;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
namespace Senparc.Weixin.TenPayV3.Apis.Tests
{
[TestClass()]
public class BasePayApisTests
{
[TestMethod()]
public void JsAPiAsyncTest()
{
var key = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);
var TenPayV3Info = TenPayV3InfoCollection.Data[key];
var price = 100;
var name = "单元测试-" + DateTime.Now.ToString();
var openId = "olPjZjsXuQPJoV0HlruZkNzKc91E";//换成测试人的 OpenId
var sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId/*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"),
TenPayV3Util.BuildRandomStr(6));
JsApiRequestData jsApiRequestData = new(new TenpayDateTime(DateTime.Now), new JsApiRequestData.Amount() { currency = "CNY", total = price },
TenPayV3Info.MchId, name, TenPayV3Info.TenPayV3Notify, new JsApiRequestData.Payer() { openid = openId }, sp_billno, null, TenPayV3Info.AppId,
null, null, null, null);
var result = BasePayApis.JsApiAsync(jsApiRequestData).GetAwaiter().GetResult();
Console.WriteLine(result);
Assert.IsNotNull(result);
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin.TenPayV3.Apis;
using Senparc.Weixin.TenPayV3.Apis.BasePay;
using System;
using System.Collections.Generic;
using System.Text;
namespace Senparc.Weixin.TenPayV3.Apis.Tests
{
[TestClass()]
public class BasePayApisTests
{
[TestMethod()]
public void JsAPiTest()
{
var json = @$"{{
""time_expire"": ""2018-06-08T10:34:56+08:00"",
""amount"": {{
""total"": 100,
""currency"": ""CNY""
}}}},
""mchid"": ""{{}}"",
""description"": ""Image形象店-深圳腾大-QQ公仔"",
""notify_url"": ""http://sdk.weixin.senparc.com/TenpayV3/PayNotifyUrl"",
""payer"": {{
""openid"": ""oUpF8uMuAJO_M2pxb1Q9zNjWeS6o""
}},
""out_trade_no"": ""121775250120140v7033233368018"",
""goods_tag"": ""WXG"",
""appid"": ""wxd678efh567hg6787"",
""attach"": ""自定义数据说明"",
""detail"": {{
""invoice_id"": ""wx123"",
""goods_detail"": [{{
""goods_name"": ""iPhoneX 256G"",
""wechatpay_goods_id"": ""1001"",
""quantity"": 1,
""merchant_goods_id"": ""商品编码"",
""unit_price"": 828800
}}, {{
""goods_name"": ""iPhoneX 256G"",
""wechatpay_goods_id"": ""1001"",
""quantity"": 1,
""merchant_goods_id"": ""商品编码"",
""unit_price"": 828800
}}],
""cost_price"": 608800
}},
""scene_info"": {{
""store_info"": {{
""address"": ""广东省深圳市南山区科技中一道10000号"",
""area_code"": ""440305"",
""name"": ""腾讯大厦分店"",
""id"": ""0001""
}},
""device_id"": ""013467007045764"",
""payer_client_ip"": ""14.23.150.211""
}}
}}";
JsApiRequestData data = Senparc.CO2NET.Helpers.SerializerHelper.GetObject<JsApiRequestData>(json);
}
}
} | apache-2.0 | C# |
1f4afb1eb02d9874f4c1755ec3864f3b6ae8a89f | Format Timestamp | carbon/Amazon | src/Amazon.DynamoDb/Models/Timestamp.cs | src/Amazon.DynamoDb/Models/Timestamp.cs | using System.Text.Json.Serialization;
using Amazon.DynamoDb.JsonConverters;
namespace Amazon.DynamoDb;
[JsonConverter(typeof(TimestampConverter))]
public readonly struct Timestamp
{
public Timestamp(double value)
{
Value = value;
}
public double Value { get; }
public static implicit operator DateTime(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds).UtcDateTime;
}
public static implicit operator DateTimeOffset(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds);
}
}
| using System.Text.Json.Serialization;
using Amazon.DynamoDb.JsonConverters;
namespace Amazon.DynamoDb
{
[JsonConverter(typeof(TimestampConverter))]
public readonly struct Timestamp
{
public Timestamp(double value)
{
Value = value;
}
public double Value { get; }
public static implicit operator DateTime(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds).UtcDateTime;
}
public static implicit operator DateTimeOffset(Timestamp timestamp)
{
long unixTimeMillseconds = (long)(timestamp.Value * 1000d);
return DateTimeOffset.FromUnixTimeMilliseconds(unixTimeMillseconds);
}
}
}
| mit | C# |
d5df48be378f9223170106938be75bf04d531b74 | Address ProcessStartInfo envvar case sensitivite issue | mholo65/cake,ferventcoder/cake,daveaglick/cake,daveaglick/cake,Julien-Mialon/cake,devlead/cake,mholo65/cake,Sam13/cake,RehanSaeed/cake,DixonD-git/cake,phenixdotnet/cake,patriksvensson/cake,thomaslevesque/cake,phrusher/cake,phenixdotnet/cake,ferventcoder/cake,gep13/cake,robgha01/cake,vlesierse/cake,Julien-Mialon/cake,cake-build/cake,thomaslevesque/cake,phrusher/cake,vlesierse/cake,Sam13/cake,patriksvensson/cake,cake-build/cake,adamhathcock/cake,robgha01/cake,gep13/cake,adamhathcock/cake,RehanSaeed/cake,devlead/cake | src/Cake.Core/Polyfill/ProcessHelper.cs | src/Cake.Core/Polyfill/ProcessHelper.cs | using System;
using System.Diagnostics;
using System.Linq;
namespace Cake.Core.Polyfill
{
internal static class ProcessHelper
{
public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value)
{
#if NETCORE
var envKey = info.Environment.Keys.FirstOrDefault(exisitingKey => StringComparer.OrdinalIgnoreCase.Equals(exisitingKey, key)) ?? key;
info.Environment[envKey] = value;
#else
var envKey = info.EnvironmentVariables.Keys.Cast<string>().FirstOrDefault(existingKey => StringComparer.OrdinalIgnoreCase.Equals(existingKey, key)) ?? key;
info.EnvironmentVariables[key] = value;
#endif
}
}
}
| using System.Diagnostics;
namespace Cake.Core.Polyfill
{
internal static class ProcessHelper
{
public static void SetEnvironmentVariable(ProcessStartInfo info, string key, string value)
{
#if NETCORE
info.Environment[key] = value;
#else
info.EnvironmentVariables[key] = value;
#endif
}
}
}
| mit | C# |
b5a7cfcfb502aa2d5f4bbc0e86d60a4e6d178701 | unify end of line | locatw/LocaHealthLog | LocaHealthLog/LocaHealthLog/WeeklyChartImage.cs | LocaHealthLog/LocaHealthLog/WeeklyChartImage.cs | using LocaHealthLog.HealthPlanet;
using LocaHealthLog.Storage;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LocaHealthLog
{
public static class WeeklyChartImage
{
// start on Saturday at 07:00 JST.
[FunctionName("WeeklyChartImage")]
public static async Task Run([TimerTrigger("0 0 22 * * 5")]TimerInfo myTimer, TraceWriter log)
{
log.Info($"Start WeeklyChartImage at: {DateTime.Now}");
try
{
var appConfig = AppConfig.Load();
var storageClient = new StorageClient();
log.Info("Start connect to table storage");
await storageClient.ConnectAsync(appConfig.StorageConnectionString);
var now = DateTimeOffset.UtcNow;
var acquisitionPeriod = new TimeSpan(7, 0, 0, 0);
var end = new DateTimeOffset(now.Year, now.Month, now.Day, 0, 0, 0,
AppConfig.LocalTimeZone.BaseUtcOffset);
var begin = end - acquisitionPeriod;
IEnumerable<InnerScanStatusEntity> last7DatesScanData =
storageClient.LoadMeasurementData(InnerScanTag.Weight.ToString(), begin, end);
}
catch (Exception e)
{
log.Error($"Exception: {e.ToString()}");
}
finally
{
log.Info($"Finish WeeklyChartImage at: {DateTime.Now}");
}
}
}
}
| using LocaHealthLog.HealthPlanet;
using LocaHealthLog.Storage;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LocaHealthLog
{
public static class WeeklyChartImage
{
// start on Saturday at 07:00 JST.
[FunctionName("WeeklyChartImage")]
public static async Task Run([TimerTrigger("0 0 22 * * 5")]TimerInfo myTimer, TraceWriter log)
{
log.Info($"Start WeeklyChartImage at: {DateTime.Now}");
try
{
var appConfig = AppConfig.Load();
var storageClient = new StorageClient();
log.Info("Start connect to table storage");
await storageClient.ConnectAsync(appConfig.StorageConnectionString);
var now = DateTimeOffset.UtcNow;
var acquisitionPeriod = new TimeSpan(7, 0, 0, 0);
var end = new DateTimeOffset(now.Year, now.Month, now.Day, 0, 0, 0,
AppConfig.LocalTimeZone.BaseUtcOffset);
var begin = end - acquisitionPeriod;
IEnumerable<InnerScanStatusEntity> last7DatesScanData =
storageClient.LoadMeasurementData(InnerScanTag.Weight.ToString(), begin, end);
}
catch (Exception e)
{
log.Error($"Exception: {e.ToString()}");
}
finally
{
log.Info($"Finish WeeklyChartImage at: {DateTime.Now}");
}
}
}
}
| mit | C# |
099679a3a6d9490289d8767910c6116528d8fe0e | Fix compilation error when building w/ .NET 4.0 | nwoolls/MultiMiner,nwoolls/MultiMiner | MultiMiner.Engine/Installers/AvailableMiners.cs | MultiMiner.Engine/Installers/AvailableMiners.cs | using MultiMiner.Engine.Data;
using MultiMiner.Utility.Net;
using MultiMiner.Utility.OS;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
namespace MultiMiner.Engine.Installers
{
public static class AvailableMiners
{
public static List<AvailableMiner> GetAvailableMiners(string userAgent)
{
WebClient webClient = new ApiWebClient();
webClient.Headers.Add("user-agent", userAgent);
string platform = "win32";
if (OSVersionPlatform.GetConcretePlatform() == PlatformID.MacOSX)
platform = "osx64";
//include www. to avoid redirect
string url = "http://www.multiminerapp.com/miners?platform=" + platform;
string response = webClient.DownloadString(new Uri(url));
List<AvailableMiner> availableMiners = JsonConvert.DeserializeObject<List<AvailableMiner>>(response);
FixDownloadUrls(availableMiners);
return availableMiners;
}
private static void FixDownloadUrls(List<AvailableMiner> availableMiners)
{
FixBFGMinerDownloadUrl(availableMiners);
}
private static void FixBFGMinerDownloadUrl(List<AvailableMiner> availableMiners)
{
// BFGMiner files are no longer hosted on luke.dashjr.org - see: http://luke.dashjr.org/programs/bitcoin/files/bfgminer/
// Fixing the URL client-side rather than server-side as the server has not been touched in ~6 years
var oldMinerUrl = "http://luke.dashjr.org/programs/bitcoin/files/bfgminer/";
var newMinerUrl = "http://bfgminer.org/files/";
foreach (var miner in availableMiners)
{
miner.Url = miner.Url.Replace(oldMinerUrl, newMinerUrl);
}
}
}
}
| using MultiMiner.Engine.Data;
using MultiMiner.Utility.Net;
using MultiMiner.Utility.OS;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net;
namespace MultiMiner.Engine.Installers
{
public static class AvailableMiners
{
public static List<AvailableMiner> GetAvailableMiners(string userAgent)
{
WebClient webClient = new ApiWebClient();
webClient.Headers.Add("user-agent", userAgent);
string platform = "win32";
if (OSVersionPlatform.GetConcretePlatform() == PlatformID.MacOSX)
platform = "osx64";
//include www. to avoid redirect
string url = "http://www.multiminerapp.com/miners?platform=" + platform;
string response = webClient.DownloadString(new Uri(url));
List<AvailableMiner> availableMiners = JsonConvert.DeserializeObject<List<AvailableMiner>>(response);
FixDownloadUrls(availableMiners);
return availableMiners;
}
private static void FixDownloadUrls(List<AvailableMiner> availableMiners) => FixBFGMinerDownloadUrl(availableMiners);
private static void FixBFGMinerDownloadUrl(List<AvailableMiner> availableMiners)
{
// BFGMiner files are no longer hosted on luke.dashjr.org - see: http://luke.dashjr.org/programs/bitcoin/files/bfgminer/
// Fixing the URL client-side rather than server-side as the server has not been touched in ~6 years
var oldMinerUrl = "http://luke.dashjr.org/programs/bitcoin/files/bfgminer/";
var newMinerUrl = "http://bfgminer.org/files/";
foreach (var miner in availableMiners)
{
miner.Url = miner.Url.Replace(oldMinerUrl, newMinerUrl);
}
}
}
}
| mit | C# |
2638f5dddb08f12655b24dad74a2b0a615031069 | Set initial page to LoginPage | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey/App.xaml.cs | client/BlueMonkey/BlueMonkey/App.xaml.cs | using BlueMonkey.ExpenceServices;
using BlueMonkey.ExpenceServices.Local;
using BlueMonkey.Model;
using Prism.Unity;
using BlueMonkey.Views;
using Xamarin.Forms;
using Microsoft.Practices.Unity;
namespace BlueMonkey
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("LoginPage");
}
protected override void RegisterTypes()
{
Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager());
Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager());
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<AddExpensePage>();
Container.RegisterTypeForNavigation<ExpenseListPage>();
Container.RegisterTypeForNavigation<ChartPage>();
Container.RegisterTypeForNavigation<ReportPage>();
Container.RegisterTypeForNavigation<ReceiptPage>();
Container.RegisterTypeForNavigation<AddReportPage>();
Container.RegisterTypeForNavigation<ReportListPage>();
Container.RegisterTypeForNavigation<ExpenseSelectionPage>();
Container.RegisterTypeForNavigation<LoginPage>();
}
}
}
| using BlueMonkey.ExpenceServices;
using BlueMonkey.ExpenceServices.Local;
using BlueMonkey.Model;
using Prism.Unity;
using BlueMonkey.Views;
using Xamarin.Forms;
using Microsoft.Practices.Unity;
namespace BlueMonkey
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("NavigationPage/MainPage");
}
protected override void RegisterTypes()
{
Container.RegisterType<IExpenseService, ExpenseService>(new ContainerControlledLifetimeManager());
Container.RegisterType<IEditReport, EditReport>(new ContainerControlledLifetimeManager());
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterTypeForNavigation<AddExpensePage>();
Container.RegisterTypeForNavigation<ExpenseListPage>();
Container.RegisterTypeForNavigation<ChartPage>();
Container.RegisterTypeForNavigation<ReportPage>();
Container.RegisterTypeForNavigation<ReceiptPage>();
Container.RegisterTypeForNavigation<AddReportPage>();
Container.RegisterTypeForNavigation<ReportListPage>();
Container.RegisterTypeForNavigation<ExpenseSelectionPage>();
Container.RegisterTypeForNavigation<LoginPage>();
}
}
}
| mit | C# |
fff3bcba6dfb5453805fe238811931ccb51ff2aa | Test stability improve | linkelf/GridDomain,andreyleskov/GridDomain | GridDomain.Tests.Acceptance/EventsUpgrade/Future_events_class_upgraded_by_object_adapter.cs | GridDomain.Tests.Acceptance/EventsUpgrade/Future_events_class_upgraded_by_object_adapter.cs | using System;
using System.Threading.Tasks;
using GridDomain.Common;
using GridDomain.CQRS;
using GridDomain.EventSourcing.Adapters;
using GridDomain.Scheduling.Quartz.Configuration;
using GridDomain.Tests.Acceptance.Snapshots;
using GridDomain.Tests.Common;
using GridDomain.Tests.Unit;
using GridDomain.Tests.Unit.EventsUpgrade;
using GridDomain.Tests.Unit.EventsUpgrade.Domain.Commands;
using GridDomain.Tests.Unit.EventsUpgrade.Domain.Events;
using Serilog.Events;
using Xunit;
using Xunit.Abstractions;
namespace GridDomain.Tests.Acceptance.EventsUpgrade
{
public class Future_events_class_upgraded_by_object_adapter : NodeTestKit
{
public Future_events_class_upgraded_by_object_adapter(ITestOutputHelper output)
: base(output,
new BalanceFixture(new PersistedQuartzConfig()).UseSqlPersistence().
InitFastRecycle().
UseAdaper(new BalanceChanged_eventdapter1())) { }
private class BalanceChanged_eventdapter1 : ObjectAdapter<BalanceChangedEvent_V0, BalanceChangedEvent_V1>
{
public override BalanceChangedEvent_V1 Convert(BalanceChangedEvent_V0 evt)
{
return new BalanceChangedEvent_V1(evt.AmplifiedAmountChange, evt.SourceId);
}
}
[Fact]
public async Task Future_event_is_upgraded_by_event_adapter()
{
await Node.Prepare(new ChangeBalanceInFuture(1, Guid.NewGuid(), BusinessDateTime.Now.AddSeconds(2), true)).
Expect<BalanceChangedEvent_V1>().
Execute(TimeSpan.FromSeconds(10));
}
}
} | using System;
using System.Threading.Tasks;
using GridDomain.Common;
using GridDomain.CQRS;
using GridDomain.EventSourcing.Adapters;
using GridDomain.Scheduling.Quartz.Configuration;
using GridDomain.Tests.Acceptance.Snapshots;
using GridDomain.Tests.Common;
using GridDomain.Tests.Unit;
using GridDomain.Tests.Unit.EventsUpgrade;
using GridDomain.Tests.Unit.EventsUpgrade.Domain.Commands;
using GridDomain.Tests.Unit.EventsUpgrade.Domain.Events;
using Serilog.Events;
using Xunit;
using Xunit.Abstractions;
namespace GridDomain.Tests.Acceptance.EventsUpgrade
{
public class Future_events_class_upgraded_by_object_adapter : NodeTestKit
{
public Future_events_class_upgraded_by_object_adapter(ITestOutputHelper output)
: base(output,
new BalanceFixture(new PersistedQuartzConfig()).UseSqlPersistence().
InitFastRecycle().
UseAdaper(new BalanceChanged_eventdapter1())) { }
private class BalanceChanged_eventdapter1 : ObjectAdapter<BalanceChangedEvent_V0, BalanceChangedEvent_V1>
{
public override BalanceChangedEvent_V1 Convert(BalanceChangedEvent_V0 evt)
{
return new BalanceChangedEvent_V1(evt.AmplifiedAmountChange, evt.SourceId);
}
}
[Fact]
public async Task Future_event_is_upgraded_by_event_adapter()
{
await Node.Prepare(new ChangeBalanceInFuture(1, Guid.NewGuid(), BusinessDateTime.Now.AddSeconds(2), true)).
Expect<BalanceChangedEvent_V1>().
Execute();
}
}
} | apache-2.0 | C# |
65443d401ac92c61d4bd2cc80a5cac5af95d6b48 | Fix issue with namespace. | malaysf/RestApiClient,symphonyoss/RestApiClient | test/SymphonyOSS.RestApiClient.Tests/UtilApiTest.cs | test/SymphonyOSS.RestApiClient.Tests/UtilApiTest.cs | namespace SymphonyOSS.RestApiClient.Tests
{
using System;
using Api;
using Api.AgentApi;
using Authentication;
using Generated.OpenApi.AgentApi.Client;
using Generated.OpenApi.AgentApi.Model;
using Moq;
using Xunit;
/// <summary>
/// Summary description for UtilApiTest
/// </summary>
public class UtilApiTest
{
private readonly UtilApi _utilApi;
private readonly Mock<IApiExecutor> _apiExecutorMock;
public UtilApiTest()
{
var sessionManagerMock = new Mock<IAuthTokens>();
sessionManagerMock.Setup(obj => obj.SessionToken).Returns("sessionToken");
var configuration = new Configuration();
_apiExecutorMock = new Mock<IApiExecutor>();
_utilApi = new UtilApi(sessionManagerMock.Object, configuration, _apiExecutorMock.Object);
}
[Fact]
public void EnsureEcho_uses_retry_strategy()
{
const string msg = "Hello!";
_utilApi.Echo(msg);
_apiExecutorMock.Verify(obj => obj.Execute(It.IsAny<Func<string, string, string, SimpleMessage>>(), "sessionToken", "keyManagerToken", msg));
}
[Fact]
public void EnsureObsolete_uses_retry_strategy()
{
const string msg = "Obsolete!";
_utilApi.Obsolete(msg);
_apiExecutorMock.Verify(obj => obj.Execute(It.IsAny<Func<string, string, string, SimpleMessage>>(), "sessionToken", "keyManagerToken", msg));
}
}
}
| using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace SymphonyOSS.RestApiClient.Tests
{
using Api;
using Api.AgentApi;
using Authentication;
using Generated.OpenApi.AgentApi.Client;
using Generated.OpenApi.AgentApi.Model;
using Moq;
using Xunit;
/// <summary>
/// Summary description for UtilApiTest
/// </summary>
public class UtilApiTest
{
private readonly UtilApi _utilApi;
private readonly Mock<IApiExecutor> _apiExecutorMock;
public UtilApiTest()
{
var sessionManagerMock = new Mock<IAuthTokens>();
sessionManagerMock.Setup(obj => obj.SessionToken).Returns("sessionToken");
var configuration = new Configuration();
_apiExecutorMock = new Mock<IApiExecutor>();
_utilApi = new UtilApi(sessionManagerMock.Object, configuration, _apiExecutorMock.Object);
}
[Fact]
public void EnsureEcho_uses_retry_strategy()
{
const string msg = "Hello!";
_utilApi.Echo(msg);
_apiExecutorMock.Verify(obj => obj.Execute(It.IsAny<Func<string, string, string, SimpleMessage>>(), "sessionToken", "keyManagerToken", msg));
}
[Fact]
public void EnsureObsolete_uses_retry_strategy()
{
const string msg = "Obsolete!";
_utilApi.Obsolete(msg);
_apiExecutorMock.Verify(obj => obj.Execute(It.IsAny<Func<string, string, string, SimpleMessage>>(), "sessionToken", "keyManagerToken", msg));
}
}
}
| apache-2.0 | C# |
46dcf7632088f583ebc40d5a2a3f0254910d80c4 | Remove unnecessary method. | jkotas/roslyn,VSadov/roslyn,panopticoncentral/roslyn,Hosch250/roslyn,robinsedlaczek/roslyn,tmeschter/roslyn,dotnet/roslyn,lorcanmooney/roslyn,nguerrera/roslyn,mattwar/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,nguerrera/roslyn,AnthonyDGreen/roslyn,OmarTawfik/roslyn,robinsedlaczek/roslyn,AnthonyDGreen/roslyn,mmitche/roslyn,khyperia/roslyn,jmarolf/roslyn,wvdd007/roslyn,dpoeschl/roslyn,jamesqo/roslyn,panopticoncentral/roslyn,Hosch250/roslyn,jamesqo/roslyn,pdelvo/roslyn,MichalStrehovsky/roslyn,robinsedlaczek/roslyn,wvdd007/roslyn,KirillOsenkov/roslyn,kelltrick/roslyn,orthoxerox/roslyn,cston/roslyn,khyperia/roslyn,OmarTawfik/roslyn,reaction1989/roslyn,AmadeusW/roslyn,drognanar/roslyn,jcouv/roslyn,xasx/roslyn,akrisiun/roslyn,DustinCampbell/roslyn,tvand7093/roslyn,stephentoub/roslyn,dpoeschl/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,jeffanders/roslyn,lorcanmooney/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,yeaicc/roslyn,physhi/roslyn,tvand7093/roslyn,genlu/roslyn,CaptainHayashi/roslyn,mattwar/roslyn,abock/roslyn,akrisiun/roslyn,KevinRansom/roslyn,tannergooding/roslyn,brettfo/roslyn,lorcanmooney/roslyn,jeffanders/roslyn,tvand7093/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,aelij/roslyn,mattwar/roslyn,CyrusNajmabadi/roslyn,cston/roslyn,mgoertz-msft/roslyn,jkotas/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,zooba/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,CyrusNajmabadi/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,mattscheffer/roslyn,mavasani/roslyn,mattscheffer/roslyn,AlekseyTs/roslyn,davkean/roslyn,genlu/roslyn,MattWindsor91/roslyn,Giftednewt/roslyn,amcasey/roslyn,gafter/roslyn,amcasey/roslyn,sharwell/roslyn,jcouv/roslyn,srivatsn/roslyn,DustinCampbell/roslyn,DustinCampbell/roslyn,Giftednewt/roslyn,weltkante/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tmat/roslyn,nguerrera/roslyn,dpoeschl/roslyn,eriawan/roslyn,MattWindsor91/roslyn,akrisiun/roslyn,AlekseyTs/roslyn,VSadov/roslyn,paulvanbrenk/roslyn,bkoelman/roslyn,orthoxerox/roslyn,swaroop-sridhar/roslyn,Giftednewt/roslyn,mavasani/roslyn,abock/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,tmeschter/roslyn,heejaechang/roslyn,weltkante/roslyn,mmitche/roslyn,drognanar/roslyn,gafter/roslyn,aelij/roslyn,davkean/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,kelltrick/roslyn,bartdesmet/roslyn,kelltrick/roslyn,TyOverby/roslyn,agocke/roslyn,jkotas/roslyn,eriawan/roslyn,xasx/roslyn,pdelvo/roslyn,khyperia/roslyn,CaptainHayashi/roslyn,brettfo/roslyn,dotnet/roslyn,TyOverby/roslyn,zooba/roslyn,AnthonyDGreen/roslyn,genlu/roslyn,jamesqo/roslyn,drognanar/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,diryboy/roslyn,xasx/roslyn,davkean/roslyn,TyOverby/roslyn,abock/roslyn,stephentoub/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,bkoelman/roslyn,mavasani/roslyn,MichalStrehovsky/roslyn,ErikSchierboom/roslyn,tannergooding/roslyn,jcouv/roslyn,jmarolf/roslyn,KevinRansom/roslyn,mmitche/roslyn,AmadeusW/roslyn,diryboy/roslyn,physhi/roslyn,MattWindsor91/roslyn,dotnet/roslyn,swaroop-sridhar/roslyn,mattscheffer/roslyn,bkoelman/roslyn,yeaicc/roslyn,aelij/roslyn,panopticoncentral/roslyn,sharwell/roslyn,sharwell/roslyn,paulvanbrenk/roslyn,wvdd007/roslyn,orthoxerox/roslyn,reaction1989/roslyn,tmat/roslyn,reaction1989/roslyn,pdelvo/roslyn,yeaicc/roslyn,paulvanbrenk/roslyn,brettfo/roslyn,MattWindsor91/roslyn,diryboy/roslyn,srivatsn/roslyn,zooba/roslyn,OmarTawfik/roslyn,VSadov/roslyn,mgoertz-msft/roslyn,gafter/roslyn,agocke/roslyn,AmadeusW/roslyn,amcasey/roslyn,swaroop-sridhar/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,agocke/roslyn,cston/roslyn,jeffanders/roslyn,heejaechang/roslyn,srivatsn/roslyn | src/EditorFeatures/Core/Implementation/IntelliSense/Completion/CompletionFilterReason.cs | src/EditorFeatures/Core/Implementation/IntelliSense/Completion/CompletionFilterReason.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion
{
internal enum CompletionFilterReason
{
Insertion,
Deletion,
NonInsertionOrDeletion,
#if false
// If necessary, we could add additional filter reasons. For example, for the below items.
// However, we have no need for them currently. That somewhat makes sense. We only want
// to really customize our filtering behavior depending on if a user was typing/deleting
// in the buffer.
Snippets,
ItemFiltersChanged,
CaretPositionChanged,
Invoke,
InvokeAndCommitIfUnique
#endif
}
internal static class CompletionTriggerExtensions
{
public static CompletionFilterReason GetFilterReason(this CompletionTrigger trigger)
=> trigger.Kind.GetFilterReason();
}
internal static class CompletionTriggerKindExtensions
{
public static CompletionFilterReason GetFilterReason(this CompletionTriggerKind kind)
{
switch (kind)
{
case CompletionTriggerKind.Insertion:
return CompletionFilterReason.Insertion;
case CompletionTriggerKind.Deletion:
return CompletionFilterReason.Deletion;
case CompletionTriggerKind.Snippets:
case CompletionTriggerKind.Invoke:
case CompletionTriggerKind.InvokeAndCommitIfUnique:
return CompletionFilterReason.NonInsertionOrDeletion;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Completion
{
internal enum CompletionFilterReason
{
Insertion,
Deletion,
NonInsertionOrDeletion,
#if false
// If necessary, we could add additional filter reasons. For example, for the below items.
// However, we have no need for them currently. That somewhat makes sense. We only want
// to really customize our filtering behavior depending on if a user was typing/deleting
// in the buffer.
Snippets,
ItemFiltersChanged,
CaretPositionChanged,
Invoke,
InvokeAndCommitIfUnique
#endif
}
internal static class CompletionTriggerExtensions
{
public static CompletionFilterReason GetFilterReason(this CompletionTrigger trigger)
=> trigger.Kind.GetFilterReason();
}
internal static class CompletionTriggerKindExtensions
{
public static CompletionFilterReason GetFilterReason(this CompletionTriggerKind kind)
{
switch (kind)
{
case CompletionTriggerKind.Insertion:
return CompletionFilterReason.Insertion;
case CompletionTriggerKind.Deletion:
return CompletionFilterReason.Deletion;
case CompletionTriggerKind.Snippets:
case CompletionTriggerKind.Invoke:
case CompletionTriggerKind.InvokeAndCommitIfUnique:
return CompletionFilterReason.NonInsertionOrDeletion;
default:
throw ExceptionUtilities.UnexpectedValue(kind);
}
}
public static bool ShouldFilterAgainstUserText(this CompletionTriggerKind kind)
=> kind != CompletionTriggerKind.Invoke && kind != CompletionTriggerKind.Deletion;
}
} | mit | C# |
ea1809006f38412deb398c24e8eb892824ceab32 | Update SwaggerToCSharpClientGeneratorSettings.cs | quails4Eva/NSwag,aelbatal/NSwag,NSwag/NSwag,quails4Eva/NSwag,RSuter/NSwag,aelbatal/NSwag,NSwag/NSwag,RSuter/NSwag,quails4Eva/NSwag,quails4Eva/NSwag,RSuter/NSwag,NSwag/NSwag,NSwag/NSwag,RSuter/NSwag,RSuter/NSwag,aelbatal/NSwag,aelbatal/NSwag | src/NSwag.CodeGeneration/CodeGenerators/CSharp/SwaggerToCSharpClientGeneratorSettings.cs | src/NSwag.CodeGeneration/CodeGenerators/CSharp/SwaggerToCSharpClientGeneratorSettings.cs | //-----------------------------------------------------------------------
// <copyright file="SwaggerToCSharpClientGeneratorSettings.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NSwag.CodeGeneration.CodeGenerators.CSharp
{
/// <summary>Settings for the <see cref="SwaggerToCSharpClientGenerator"/>.</summary>
public class SwaggerToCSharpClientGeneratorSettings : SwaggerToCSharpGeneratorSettings
{
/// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpClientGeneratorSettings"/> class.</summary>
public SwaggerToCSharpClientGeneratorSettings()
{
ClassName = "{controller}Client";
}
/// <summary>Gets or sets the full name of the base class.</summary>
public string ClientBaseClass { get; set; }
/// <summary>Gets or sets a value indicating whether to call CreateHttpClientAsync on the base class to create a new HttpClient instance.</summary>
public bool UseHttpClientCreationMethod { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="SwaggerToCSharpClientGeneratorSettings.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NSwag.CodeGeneration.CodeGenerators.CSharp
{
/// <summary>Settings for the <see cref="SwaggerToCSharpClientGenerator"/>.</summary>
public class SwaggerToCSharpClientGeneratorSettings : SwaggerToCSharpGeneratorSettings
{
/// <summary>Initializes a new instance of the <see cref="SwaggerToCSharpClientGeneratorSettings"/> class.</summary>
public SwaggerToCSharpClientGeneratorSettings()
{
ClassName = "{controller}Client";
}
/// <summary>Gets or sets the full name of the base class.</summary>
public string ClientBaseClass { get; set; }
/// <summary>Gets or sets a value indicating whether to call CreateHttpClientAsync on the base class to create a new HttpClient.</summary>
public bool UseHttpClientCreationMethod { get; set; }
}
} | mit | C# |
fb5bf5e62b76688b93cb8892ac9cc31bbb5ca3b5 | Add comment to backwards compat alias | hungmai-msft/azure-powershell,krkhan/azure-powershell,AzureRT/azure-powershell,rohmano/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,jtlibing/azure-powershell,yoavrubin/azure-powershell,zhencui/azure-powershell,AzureAutomationTeam/azure-powershell,rohmano/azure-powershell,atpham256/azure-powershell,seanbamsft/azure-powershell,yoavrubin/azure-powershell,yantang-msft/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,yoavrubin/azure-powershell,AzureRT/azure-powershell,naveedaz/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,AzureRT/azure-powershell,yoavrubin/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,atpham256/azure-powershell,yantang-msft/azure-powershell,rohmano/azure-powershell,AzureRT/azure-powershell,ClogenyTechnologies/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,krkhan/azure-powershell,AzureAutomationTeam/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,jtlibing/azure-powershell,yantang-msft/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,alfantp/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,seanbamsft/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,zhencui/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,alfantp/azure-powershell,krkhan/azure-powershell,zhencui/azure-powershell,jtlibing/azure-powershell,yoavrubin/azure-powershell,yantang-msft/azure-powershell,AzureRT/azure-powershell,devigned/azure-powershell,alfantp/azure-powershell,hungmai-msft/azure-powershell,zhencui/azure-powershell,devigned/azure-powershell,devigned/azure-powershell,rohmano/azure-powershell,zhencui/azure-powershell,ClogenyTechnologies/azure-powershell,yantang-msft/azure-powershell,atpham256/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,jtlibing/azure-powershell,krkhan/azure-powershell,seanbamsft/azure-powershell,AzureRT/azure-powershell,pankajsn/azure-powershell,zhencui/azure-powershell | src/ResourceManager/AzureBatch/Commands.Batch/Locations/GetBatchLocationQuotasCommand.cs | src/ResourceManager/AzureBatch/Commands.Batch/Locations/GetBatchLocationQuotasCommand.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 Microsoft.Azure.Commands.Batch.Models;
using System.Management.Automation;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;
namespace Microsoft.Azure.Commands.Batch
{
[Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))]
// This alias was added in 10/2016 for backwards compatibility
[Alias("Get-AzureRmBatchSubscriptionQuotas")]
public class GetBatchLocationQuotasCommand : BatchCmdletBase
{
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
public override void ExecuteCmdlet()
{
PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location);
WriteObject(quotas);
}
}
}
| // ----------------------------------------------------------------------------------
//
// 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 Microsoft.Azure.Commands.Batch.Models;
using System.Management.Automation;
using Constants = Microsoft.Azure.Commands.Batch.Utils.Constants;
namespace Microsoft.Azure.Commands.Batch
{
[Cmdlet(VerbsCommon.Get, Constants.AzureRmBatchLocationQuotas), OutputType(typeof(PSBatchLocationQuotas))]
[Alias("Get-AzureRmBatchSubscriptionQuotas")]
public class GetBatchLocationQuotasCommand : BatchCmdletBase
{
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true,
HelpMessage = "The region to get the quotas of the subscription in the Batch Service from.")]
[ValidateNotNullOrEmpty]
public string Location { get; set; }
public override void ExecuteCmdlet()
{
PSBatchLocationQuotas quotas = BatchClient.GetLocationQuotas(this.Location);
WriteObject(quotas);
}
}
}
| apache-2.0 | C# |
e010058e1564c6ace6afc33e64aa967942cc362b | comment change | uncas/core,uncas/core | tests/Uncas.Core.Tests/Ioc/BaseBootstrapperTests.cs | tests/Uncas.Core.Tests/Ioc/BaseBootstrapperTests.cs | namespace Uncas.Core.Tests.Ioc
{
using Moq;
using NUnit.Framework;
using Uncas.Core.Data.Migration;
using Uncas.Core.Ioc;
[TestFixture]
public class BaseBootstrapperTests
{
[Test]
public void BaseBootstrapper_WithBasicSetupOfTestAssembly_RunsWithoutFailing()
{
var containerMock = new Mock<IIocContainer>();
var baseBootstrapper = new BaseBootstrapper(
containerMock.Object,
GetType().Assembly);
}
[Test]
public void BaseBootstrapper_TestAssembly_RunsWithoutRegisteringMigrationChange()
{
var containerMock = new Mock<IIocContainer>();
var baseBootstrapper = new BaseBootstrapper(
containerMock.Object,
GetType().Assembly);
containerMock.Verify(
x => x.RegisterType(typeof(MigrationChange), typeof(IMigrationChange)),
Times.Never());
}
[Test]
public void BaseBootstrapper_TestAssembly_RunsWithRegisteringMigrationService()
{
var containerMock = new Mock<IIocContainer>();
var baseBootstrapper = new BaseBootstrapper(
containerMock.Object,
GetType().Assembly);
containerMock.Verify(
x => x.RegisterType(typeof(MigrationService), typeof(IMigrationService)),
Times.Once());
}
// TODO: Test resolving all registered types...
}
}
| namespace Uncas.Core.Tests.Ioc
{
using Moq;
using NUnit.Framework;
using Uncas.Core.Data.Migration;
using Uncas.Core.Ioc;
[TestFixture]
public class BaseBootstrapperTests
{
[Test]
public void BaseBootstrapper_WithBasicSetupOfTestAssembly_RunsWithoutFailing()
{
var containerMock = new Mock<IIocContainer>();
var baseBootstrapper = new BaseBootstrapper(
containerMock.Object,
GetType().Assembly);
}
[Test]
public void BaseBootstrapper_TestAssembly_RunsWithoutRegisteringMigrationChange()
{
var containerMock = new Mock<IIocContainer>();
var baseBootstrapper = new BaseBootstrapper(
containerMock.Object,
GetType().Assembly);
containerMock.Verify(
x => x.RegisterType(typeof(MigrationChange), typeof(IMigrationChange)),
Times.Never());
}
[Test]
public void BaseBootstrapper_TestAssembly_RunsWithRegisteringMigrationService()
{
var containerMock = new Mock<IIocContainer>();
var baseBootstrapper = new BaseBootstrapper(
containerMock.Object,
GetType().Assembly);
containerMock.Verify(
x => x.RegisterType(typeof(MigrationService), typeof(IMigrationService)),
Times.Once());
}
// TODO: Test resolving all registered...
}
}
| mit | C# |
81f9283dbc49edfb9dead422b86871e462112c53 | Add hovering flag | DMagic1/KSP_Contract_Window | Source/ContractsWindow.Unity/TextHighlighter.cs | Source/ContractsWindow.Unity/TextHighlighter.cs |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace ContractsWindow.Unity
{
[RequireComponent(typeof(Text))]
public class TextHighlighter : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IScrollHandler
{
[SerializeField]
private Color NormalColor = Color.white;
[SerializeField]
private Color HighlightColor = Color.yellow;
private ScrollRect scroller;
private Text AttachedText;
private bool _hover;
public bool Hover
{
get { return _hover; }
}
private void Awake()
{
AttachedText = GetComponent<Text>();
}
public void setScroller(ScrollRect s)
{
scroller = s;
}
public void setNormalColor(Color c)
{
NormalColor = c;
}
public void OnPointerEnter(PointerEventData eventData)
{
if (AttachedText == null)
return;
_hover = true;
AttachedText.color = HighlightColor;
eventData.Reset();
}
public void OnPointerExit(PointerEventData eventData)
{
_hover = false;
if (AttachedText == null)
return;
AttachedText.color = NormalColor;
}
public void OnScroll(PointerEventData eventData)
{
if (scroller == null)
return;
scroller.OnScroll(eventData);
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace ContractsWindow.Unity
{
[RequireComponent(typeof(Text))]
public class TextHighlighter : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IScrollHandler
{
[SerializeField]
private Color NormalColor = Color.white;
[SerializeField]
private Color HighlightColor = Color.yellow;
private ScrollRect scroller;
private Text AttachedText;
private void Awake()
{
AttachedText = GetComponent<Text>();
}
public void setScroller(ScrollRect s)
{
scroller = s;
}
public void setNormalColor(Color c)
{
NormalColor = c;
}
public void OnPointerEnter(PointerEventData eventData)
{
if (AttachedText == null)
return;
AttachedText.color = HighlightColor;
eventData.Reset();
}
public void OnPointerExit(PointerEventData eventData)
{
if (AttachedText == null)
return;
AttachedText.color = NormalColor;
}
public void OnScroll(PointerEventData eventData)
{
if (scroller == null)
return;
scroller.OnScroll((PointerEventData)eventData);
}
}
}
| mit | C# |
c0533d2f7623075a1dd5c8a1ab6801af0c16ceed | Check if the workitem if a jira issue, before logging time. | n-develop/tickettimer | TicketTimer.Jira/Services/DefaultJiraService.cs | TicketTimer.Jira/Services/DefaultJiraService.cs | using Atlassian.Jira;
using TicketTimer.Core.Infrastructure;
using TicketTimer.Jira.Extensions;
namespace TicketTimer.Jira.Services
{
public class DefaultJiraService : JiraService
{
private readonly WorkItemStore _workItemStore;
// TODO Insert correct parameters
public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword");
public DefaultJiraService(WorkItemStore workItemStore)
{
_workItemStore = workItemStore;
}
public async void WriteEntireArchive()
{
var archive = _workItemStore.GetState().WorkItemArchive;
foreach (var workItem in archive)
{
var jiraIssue = await JiraClient.Issues.GetIssueAsync(workItem.TicketNumber);
if (jiraIssue != null)
{
TrackTime(workItem);
}
}
}
private void TrackTime(WorkItem workItem)
{
var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment);
JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog);
}
}
}
| using Atlassian.Jira;
using TicketTimer.Core.Infrastructure;
using TicketTimer.Jira.Extensions;
namespace TicketTimer.Jira.Services
{
public class DefaultJiraService : JiraService
{
private readonly WorkItemStore _workItemStore;
// TODO Insert correct parameters
public Atlassian.Jira.Jira JiraClient => Atlassian.Jira.Jira.CreateRestClient("JiraUrl", "JiraUserName", "JiraPassword");
public DefaultJiraService(WorkItemStore workItemStore)
{
_workItemStore = workItemStore;
}
public void WriteEntireArchive()
{
var archive = _workItemStore.GetState().WorkItemArchive;
foreach (var workItem in archive)
{
// TODO Check if work item is jira-item.
TrackTime(workItem);
}
}
private void TrackTime(WorkItem workItem)
{
var workLog = new Worklog(workItem.Duration.ToJiraFormat(), workItem.Started.Date, workItem.Comment);
JiraClient.Issues.AddWorklogAsync(workItem.TicketNumber, workLog);
}
}
}
| mit | C# |
85bd20e827a53112fb831002c524ae0f5d7ad5bd | Correct 'hearth' to 'heart' | FormsCommunityToolkit/FormsCommunityToolkit | Toolkit/Animations/Animations/HeartAnimation.cs | Toolkit/Animations/Animations/HeartAnimation.cs | using System;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Xamarin.Toolkit.Animations
{
public class HeartAnimation : AnimationBase
{
protected override Task BeginAnimation()
{
if (Target == null)
{
throw new NullReferenceException("Null Target property.");
}
return Task.Run(() =>
{
Device.BeginInvokeOnMainThread(() =>
{
Target.Animate("Heart", Heart(), 16, Convert.ToUInt32(Duration));
});
});
}
internal Animation Heart()
{
var animation = new Animation();
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale, Target.Scale, Forms.Easing.Linear, 0, 0.1);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale, Target.Scale * 1.1, Xamarin.Forms.Easing.Linear, 0.1, 0.4);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale * 1.1, Target.Scale, Xamarin.Forms.Easing.Linear, 0.4, 0.5);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale, Target.Scale * 1.1, Xamarin.Forms.Easing.Linear, 0.5, 0.8);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale * 1.1, Target.Scale, Xamarin.Forms.Easing.Linear, 0.8, 1);
return animation;
}
}
}
| using System;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace Xamarin.Toolkit.Animations
{
public class HeartAnimation : AnimationBase
{
protected override Task BeginAnimation()
{
if (Target == null)
{
throw new NullReferenceException("Null Target property.");
}
return Task.Run(() =>
{
Device.BeginInvokeOnMainThread(() =>
{
Target.Animate("Hearth", Hearth(), 16, Convert.ToUInt32(Duration));
});
});
}
internal Animation Hearth()
{
var animation = new Animation();
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale, Target.Scale, Forms.Easing.Linear, 0, 0.1);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale, Target.Scale * 1.1, Xamarin.Forms.Easing.Linear, 0.1, 0.4);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale * 1.1, Target.Scale, Xamarin.Forms.Easing.Linear, 0.4, 0.5);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale, Target.Scale * 1.1, Xamarin.Forms.Easing.Linear, 0.5, 0.8);
animation.WithConcurrent((f) => Target.Scale = f, Target.Scale * 1.1, Target.Scale, Xamarin.Forms.Easing.Linear, 0.8, 1);
return animation;
}
}
}
| mit | C# |
08678d9217d43e7537713ba68824666951405507 | Remove test code | sailro/LLZipLib | ZipEntry.cs | ZipEntry.cs | using System.Diagnostics;
using System.IO;
namespace Llziplib
{
public class ZipEntry
{
public CentralDirectoryHeader CentralDirectoryHeader { get; }
public LocalFileHeader LocalFileHeader { get; }
public byte[] Data { get; set; }
public DataDescriptor DataDescriptor { get; set; }
public bool HasDataDescriptor => (LocalFileHeader.Flags & 4) != 0;
public ZipEntry(BinaryReader reader, CentralDirectoryHeader header)
{
CentralDirectoryHeader = header;
reader.BaseStream.Seek(header.LocalHeaderOffset, SeekOrigin.Begin);
LocalFileHeader = new LocalFileHeader(reader);
Data = reader.ReadBytes(LocalFileHeader.CompressedSize);
if (HasDataDescriptor)
DataDescriptor = new DataDescriptor(reader);
}
internal void Write(BinaryWriter writer)
{
LocalFileHeader.Write(writer);
if (Data != null)
writer.Write(Data, 0, Data.Length);
if (HasDataDescriptor)
DataDescriptor?.Write(writer);
}
}
} | using System.Diagnostics;
using System.IO;
namespace Llziplib
{
public class ZipEntry
{
public CentralDirectoryHeader CentralDirectoryHeader { get; }
public LocalFileHeader LocalFileHeader { get; }
public byte[] Data { get; set; }
public DataDescriptor DataDescriptor { get; set; }
public bool HasDataDescriptor => (LocalFileHeader.Flags & 4) != 0;
public ZipEntry(BinaryReader reader, CentralDirectoryHeader header)
{
CentralDirectoryHeader = header;
reader.BaseStream.Seek(header.LocalHeaderOffset, SeekOrigin.Begin);
LocalFileHeader = new LocalFileHeader(reader);
Data = reader.ReadBytes(LocalFileHeader.CompressedSize);
if (HasDataDescriptor)
DataDescriptor = new DataDescriptor(reader);
}
internal void Write(BinaryWriter writer)
{
LocalFileHeader.Write(writer);
if (Data.Length != CentralDirectoryHeader.CompressedSize)
Debugger.Break();
if (Data.Length != LocalFileHeader.CompressedSize)
Debugger.Break();
if (Data != null)
writer.Write(Data, 0, Data.Length);
if (HasDataDescriptor)
DataDescriptor?.Write(writer);
}
}
} | mit | C# |
cc29101b88b927e3fbe5c54c8abdf985dd92146d | Remove diagnostics page from perf app, not implemented. | HongJunRen/katanaproject,HongJunRen/katanaproject,eocampo/KatanaProject301,tomi85/Microsoft.Owin,julianpaulozzi/katanaproject,eocampo/KatanaProject301,HongJunRen/katanaproject,julianpaulozzi/katanaproject,eocampo/KatanaProject301,HongJunRen/katanaproject,eocampo/KatanaProject301,eocampo/KatanaProject301,abrodersen/katana,abrodersen/katana,evicertia/Katana,abrodersen/katana,julianpaulozzi/katanaproject,julianpaulozzi/katanaproject,monkeysquare/katana,tomi85/Microsoft.Owin,HongJunRen/katanaproject,HongJunRen/katanaproject,PxAndy/Katana,monkeysquare/katana,abrodersen/katana,evicertia/Katana,evicertia/Katana,PxAndy/Katana,abrodersen/katana,abrodersen/katana,eocampo/KatanaProject301,evicertia/Katana,evicertia/Katana,monkeysquare/katana,tomi85/Microsoft.Owin,evicertia/Katana,julianpaulozzi/katanaproject,julianpaulozzi/katanaproject,PxAndy/Katana,tomi85/Microsoft.Owin,PxAndy/Katana | tests/Katana.Performance.ReferenceApp/Startup.cs | tests/Katana.Performance.ReferenceApp/Startup.cs | // <copyright file="Startup.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using Katana.Performance.ReferenceApp;
using Microsoft.Owin;
using Microsoft.Owin.Diagnostics;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace Katana.Performance.ReferenceApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// app.UseFilter(req => req.TraceOutput.WriteLine(
// "{0} {1}{2} {3}",
// req.Method, req.PathBase, req.Path, req.QueryString));
app.UseErrorPage(new ErrorPageOptions { SourceCodeLineCount = 20 });
// app.Use(typeof(AutoTuneMiddleware), app.Properties["Microsoft.Owin.Host.HttpListener.OwinHttpListener"]);
app.UseSendFileFallback();
app.Use<CanonicalRequestPatterns>();
app.UseFileServer(opt => opt.WithPhysicalPath("Public"));
app.Map("/static-compression", map => map
.UseStaticCompression()
.UseFileServer(opt =>
{
opt.WithDirectoryBrowsing();
opt.WithPhysicalPath("Public");
}));
app.Map("/danger", map => map
.UseStaticCompression()
.UseFileServer(opt =>
{
opt.WithDirectoryBrowsing();
opt.StaticFileOptions.ServeUnknownFileTypes = true;
}));
app.UseWelcomePage("/Welcome");
}
}
}
| // <copyright file="Startup.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using Katana.Performance.ReferenceApp;
using Microsoft.Owin;
using Microsoft.Owin.Diagnostics;
using Owin;
[assembly: OwinStartup(typeof(Startup))]
namespace Katana.Performance.ReferenceApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// app.UseFilter(req => req.TraceOutput.WriteLine(
// "{0} {1}{2} {3}",
// req.Method, req.PathBase, req.Path, req.QueryString));
app.UseErrorPage(new ErrorPageOptions { SourceCodeLineCount = 20 });
// app.Use(typeof(AutoTuneMiddleware), app.Properties["Microsoft.Owin.Host.HttpListener.OwinHttpListener"]);
app.UseSendFileFallback();
app.Use<CanonicalRequestPatterns>();
app.UseFileServer(opt => opt.WithPhysicalPath("Public"));
app.Map("/static-compression", map => map
.UseStaticCompression()
.UseFileServer(opt =>
{
opt.WithDirectoryBrowsing();
opt.WithPhysicalPath("Public");
}));
app.Map("/danger", map => map
.UseStaticCompression()
.UseFileServer(opt =>
{
opt.WithDirectoryBrowsing();
opt.StaticFileOptions.ServeUnknownFileTypes = true;
}));
app.UseDiagnosticsPage("/testpage");
app.UseWelcomePage("/Welcome");
}
}
}
| apache-2.0 | C# |
15762abf323aad07126a9d0b2f2e8d94302a48ee | fix whitespace in EnumTests.cs | gerryhigh/ServiceStack.Text,NServiceKit/NServiceKit.Text,mono/ServiceStack.Text,gerryhigh/ServiceStack.Text,mono/ServiceStack.Text,NServiceKit/NServiceKit.Text | tests/ServiceStack.Text.Net40.Tests/EnumTests.cs | tests/ServiceStack.Text.Net40.Tests/EnumTests.cs | using System;
using NUnit.Framework;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class EnumTests
{
[SetUp]
public void SetUp()
{
JsConfig.Reset();
}
public enum EnumWithoutFlags
{
One = 1,
Two = 2
}
[Flags]
public enum EnumWithFlags
{
One = 1,
Two = 2
}
public class ClassWithEnums
{
public EnumWithFlags FlagsEnum { get; set; }
public EnumWithoutFlags NoFlagsEnum { get; set; }
public EnumWithFlags? NullableFlagsEnum { get; set; }
public EnumWithoutFlags? NullableNoFlagsEnum { get; set; }
}
[Test]
public void Can_correctly_serialize_enums()
{
var item = new ClassWithEnums
{
FlagsEnum = EnumWithFlags.One,
NoFlagsEnum = EnumWithoutFlags.One,
NullableFlagsEnum = EnumWithFlags.Two,
NullableNoFlagsEnum = EnumWithoutFlags.Two
};
var expected = "{\"FlagsEnum\":1,\"NoFlagsEnum\":\"One\",\"NullableFlagsEnum\":2,\"NullableNoFlagsEnum\":\"Two\"}";
var text = JsonSerializer.SerializeToString(item);
Assert.AreEqual(expected, text);
}
}
}
| using System;
using NUnit.Framework;
namespace ServiceStack.Text.Tests
{
[TestFixture]
public class EnumTests
{
[SetUp]
public void SetUp()
{
JsConfig.Reset();
}
public enum EnumWithoutFlags
{
One = 1,
Two = 2
}
[Flags]
public enum EnumWithFlags
{
One = 1,
Two = 2
}
public class ClassWithEnums
{
public EnumWithFlags FlagsEnum { get; set; }
public EnumWithoutFlags NoFlagsEnum { get; set; }
public EnumWithFlags? NullableFlagsEnum { get; set; }
public EnumWithoutFlags? NullableNoFlagsEnum { get; set; }
}
[Test]
public void Can_correctly_serialize_enums()
{
var item = new ClassWithEnums
{
FlagsEnum = EnumWithFlags.One,
NoFlagsEnum = EnumWithoutFlags.One,
NullableFlagsEnum = EnumWithFlags.Two,
NullableNoFlagsEnum = EnumWithoutFlags.Two
};
var expected = "{\"FlagsEnum\":1,\"NoFlagsEnum\":\"One\",\"NullableFlagsEnum\":2,\"NullableNoFlagsEnum\":\"Two\"}";
var text = JsonSerializer.SerializeToString(item);
Assert.AreEqual(expected, text);
}
}
}
| bsd-3-clause | C# |
7e7eddea70e0c495a949c208d7867308b2ab76f3 | Bump to v0.10.0 | viagogo/gogokit.net | SolutionInfo.cs | SolutionInfo.cs | // <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProductAttribute("GogoKit")]
[assembly: AssemblyCompanyAttribute("viagogo")]
[assembly: AssemblyCopyrightAttribute("Copyright viagogo 2016")]
[assembly: AssemblyVersionAttribute("0.10.0")]
[assembly: AssemblyFileVersionAttribute("0.10.0")]
[assembly: AssemblyInformationalVersionAttribute("0.10.0")]
[assembly: ComVisibleAttribute(false)]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.10.0";
}
}
| // <auto-generated/>
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProductAttribute("GogoKit")]
[assembly: AssemblyCompanyAttribute("viagogo")]
[assembly: AssemblyCopyrightAttribute("Copyright viagogo 2016")]
[assembly: AssemblyVersionAttribute("0.9.0")]
[assembly: AssemblyFileVersionAttribute("0.9.0")]
[assembly: AssemblyInformationalVersionAttribute("0.9.0")]
[assembly: ComVisibleAttribute(false)]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.0";
}
}
| mit | C# |
49a10f4fba2fc1d405f5ebf6ec5cafb8b76c7dd4 | Update development to 7.3.1. | robsiera/Dnn.Platform,yiji/Dnn.Platform,RichardHowells/Dnn.Platform,51Degrees/Dnn.Platform,AugustKarlstedt/Dnn.Platform,abukres/Dnn.Platform,mitchelsellers/Dnn.Platform,moshefi/Dnn.Platform,ohine/Dnn.Platform,ohine/Dnn.Platform,janjonas/Dnn.Platform,bdukes/Dnn.Platform,nvisionative/Dnn.Platform,EPTamminga/Dnn.Platform,valadas/Dnn.Platform,51Degrees/Dnn.Platform,AugustKarlstedt/Dnn.Platform,JoshuaBradley/Dnn.Platform,janjonas/Dnn.Platform,svdv71/Dnn.Platform,dnnsoftware/Dnn.Platform,ohine/Dnn.Platform,nvisionative/Dnn.Platform,valadas/Dnn.Platform,valadas/Dnn.Platform,AugustKarlstedt/Dnn.Platform,moshefi/Dnn.Platform,SCullman/Dnn.Platform,RichardHowells/Dnn.Platform,AugustKarlstedt/Dnn.Platform,mitchelsellers/Dnn.Platform,abukres/Dnn.Platform,wael101/Dnn.Platform,nvisionative/Dnn.Platform,janjonas/Dnn.Platform,abukres/Dnn.Platform,ohine/Dnn.Platform,mitchelsellers/Dnn.Platform,RichardHowells/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,raphael-m/Dnn.Platform,yiji/Dnn.Platform,robsiera/Dnn.Platform,svdv71/Dnn.Platform,wael101/Dnn.Platform,raphael-m/Dnn.Platform,raphael-m/Dnn.Platform,RichardHowells/Dnn.Platform,SCullman/Dnn.Platform,51Degrees/Dnn.Platform,moshefi/Dnn.Platform,wael101/Dnn.Platform,raphael-m/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,51Degrees/Dnn.Platform,SCullman/Dnn.Platform,JoshuaBradley/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,yiji/Dnn.Platform,bdukes/Dnn.Platform,mitchelsellers/Dnn.Platform,EPTamminga/Dnn.Platform,svdv71/Dnn.Platform,valadas/Dnn.Platform,JoshuaBradley/Dnn.Platform | SolutionInfo.cs | SolutionInfo.cs | #region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2014
// by DotNetNuke Corporation
//
// 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.
#endregion
#region Usings
using System.Reflection;
#endregion
// 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.
// Review the values of the assembly attributes
[assembly: AssemblyCompany("DNN Corporation")]
[assembly: AssemblyProduct("http://www.dnnsoftware.com")]
[assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2014 by DNN Corporation. All Rights Reserved.")]
[assembly: AssemblyTrademark("DNN")]
// 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("7.3.1.0")]
[assembly: AssemblyFileVersion("7.3.1.0")] | #region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2014
// by DotNetNuke Corporation
//
// 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.
#endregion
#region Usings
using System.Reflection;
#endregion
// 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.
// Review the values of the assembly attributes
[assembly: AssemblyCompany("DNN Corporation")]
[assembly: AssemblyProduct("http://www.dnnsoftware.com")]
[assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2014 by DNN Corporation. All Rights Reserved.")]
[assembly: AssemblyTrademark("DNN")]
// 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("7.3.0.0")]
[assembly: AssemblyFileVersion("7.3.0.0")] | mit | C# |
575070c5eeb41d00315b4f36e03e855567d410b7 | add binding flat to reduce list of getfunctions | haolly/slua_source_note,jiangzhhhh/slua,luzexi/slua-3rd-lib,luzexi/slua-3rd-lib,Roland0511/slua,yaukeywang/slua,luzexi/slua-3rd,luzexi/slua-3rd,haolly/slua_source_note,Roland0511/slua,jiangzhhhh/slua,Roland0511/slua,jiangzhhhh/slua,mr-kelly/slua,yaukeywang/slua,yaukeywang/slua,yaukeywang/slua,mr-kelly/slua,jiangzhhhh/slua,mr-kelly/slua,Roland0511/slua,yaukeywang/slua,luzexi/slua-3rd,soulgame/slua,soulgame/slua,haolly/slua_source_note,luzexi/slua-3rd-lib,mr-kelly/slua,haolly/slua_source_note,luzexi/slua-3rd-lib,soulgame/slua,jiangzhhhh/slua,luzexi/slua-3rd,shrimpz/slua,haolly/slua_source_note,yaukeywang/slua,haolly/slua_source_note,luzexi/slua-3rd-lib,pangweiwei/slua,mr-kelly/slua,luzexi/slua-3rd-lib,pangweiwei/slua,soulgame/slua,luzexi/slua-3rd,shrimpz/slua,soulgame/slua,pangweiwei/slua,jiangzhhhh/slua,pangweiwei/slua,luzexi/slua-3rd,pangweiwei/slua,Roland0511/slua,Roland0511/slua,soulgame/slua,mr-kelly/slua | Assets/Plugins/Slua_Managed/Lua3rdDLL.cs | Assets/Plugins/Slua_Managed/Lua3rdDLL.cs | using System.Collections.Generic;
using LuaInterface;
using System;
using System.Linq;
using System.Reflection;
using UnityEngine;
namespace SLua{
public static class Lua3rdDLL{
static Dictionary<string, LuaCSFunction> DLLRegFuncs = new Dictionary<string, LuaCSFunction>();
static Lua3rdDLL(){
// LuaSocketDLL.Reg(DLLRegFuncs);
}
public static void open(IntPtr L){
Assembly assembly = null;
foreach(var assem in AppDomain.CurrentDomain.GetAssemblies()){
if(assem.GetName().Name == "Assembly-CSharp"){
assembly = assem;
}
}
if(assembly != null){
var csfunctions = assembly.GetExportedTypes()
.SelectMany(x => x.GetMethods(BindingFlags.Public|BindingFlags.Static) )
.Where(y => y.IsDefined(typeof(LualibRegAttribute),false));
foreach(MethodInfo func in csfunctions){
var attr = System.Attribute.GetCustomAttribute(func,typeof(LualibRegAttribute)) as LualibRegAttribute;
var csfunc = Delegate.CreateDelegate(typeof(LuaCSFunction),func) as LuaCSFunction;
DLLRegFuncs.Add(attr.luaName,csfunc);
}
}
if(DLLRegFuncs.Count == 0){
return;
}
LuaDLL.lua_getglobal(L, "package");
LuaDLL.lua_getfield(L, -1, "preload");
foreach (KeyValuePair<string, LuaCSFunction> pair in DLLRegFuncs) {
LuaDLL.lua_pushcfunction (L, pair.Value);
LuaDLL.lua_setfield(L, -2, pair.Key);
}
LuaDLL.lua_settop(L, 0);
}
[AttributeUsage(AttributeTargets.Method)]
public class LualibRegAttribute:System.Attribute{
public string luaName;
public LualibRegAttribute(string luaName){
this.luaName = luaName;
}
}
}
} | using System.Collections.Generic;
using LuaInterface;
using System;
using System.Linq;
using System.Reflection;
namespace SLua{
public static class Lua3rdDLL{
static Dictionary<string, LuaCSFunction> DLLRegFuncs = new Dictionary<string, LuaCSFunction>();
static Lua3rdDLL(){
// LuaSocketDLL.Reg(DLLRegFuncs);
}
public static void open(IntPtr L){
// var now = System.DateTime.Now;
Assembly assembly = null;
foreach(var assem in AppDomain.CurrentDomain.GetAssemblies()){
if(assem.GetName().Name == "Assembly-CSharp"){
assembly = assem;
}
}
if(assembly != null){
var csfunctions = assembly.GetExportedTypes()
.SelectMany(x => x.GetMethods())
.Where(y => y.IsDefined(typeof(LualibRegAttribute),false));
foreach(MethodInfo func in csfunctions){
var attr = System.Attribute.GetCustomAttribute(func,typeof(LualibRegAttribute)) as LualibRegAttribute;
var csfunc = Delegate.CreateDelegate(typeof(LuaCSFunction),func) as LuaCSFunction;
DLLRegFuncs.Add(attr.luaName,csfunc);
// UnityEngine.Debug.Log(attr.luaName);
}
}
// UnityEngine.Debug.Log("find all methods marked by [Lua3rdRegAttribute] cost :"+(System.DateTime.Now - now).TotalSeconds);
if(DLLRegFuncs.Count == 0){
return;
}
LuaDLL.lua_getglobal(L, "package");
LuaDLL.lua_getfield(L, -1, "preload");
foreach (KeyValuePair<string, LuaCSFunction> pair in DLLRegFuncs) {
LuaDLL.lua_pushcfunction (L, pair.Value);
LuaDLL.lua_setfield(L, -2, pair.Key);
}
LuaDLL.lua_settop(L, 0);
}
[AttributeUsage(AttributeTargets.Method)]
public class LualibRegAttribute:System.Attribute{
public string luaName;
public LualibRegAttribute(string luaName){
this.luaName = luaName;
}
}
}
} | mit | C# |
57ae9797aab6e46d8dda3556af916700f107d598 | bump version | Fody/Fody,GeertvanHorrik/Fody | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("2.0.11")]
[assembly: AssemblyFileVersion("2.0.11")] | using System.Reflection;
[assembly: AssemblyTitle("Fody")]
[assembly: AssemblyProduct("Fody")]
[assembly: AssemblyVersion("2.0.10")]
[assembly: AssemblyFileVersion("2.0.10")] | mit | C# |
2719d59b6551dfbb291adb3e680e5c9d16af0b35 | rename PostParameters to BodyParameters | NebulousConcept/b2-csharp-client | b2-csharp-client/B2.Client/Rest/IRestRequest.cs | b2-csharp-client/B2.Client/Rest/IRestRequest.cs | using System.Collections.Generic;
using System.Net.Http;
namespace B2.Client.Rest
{
/// <summary>
/// Represents a REST client request.
/// </summary>
public interface IRestRequest
{
/// <summary>
/// The HTTP method to be used for this request.
/// </summary>
HttpMethod Method { get; }
/// <summary>
/// Request parameters that belong in the HTTP header.
/// </summary>
IList<Param> HeaderParameters { get; }
/// <summary>
/// Request parameters that belong in the HTTP query string.
/// </summary>
IList<Param> QueryParameters { get; }
/// <summary>
/// Request parameters that belong in the URL.
/// </summary>
IList<Param> UrlParameters { get; }
/// <summary>
/// Request parameters that belong in the HTTP body.
/// </summary>
IList<RequestData> BodyParameters { get; }
/// <summary>
/// Convert the Request for a given URL to an HttpClient HttpRequestMessage.
/// <param name="urlSegments">The URL segments for the request.</param>
/// </summary>
/// <returns>An HttpClient HttpRequestMessage.</returns>
HttpRequestMessage ToHttpRequestMessage(IList<UrlSegment> urlSegments);
/// <summary>
/// Form a complete URL for an API from components.
/// </summary>
/// <param name="urlSegments">The segments that make up the URL for the request.</param>
/// <returns>An URL (excluding endpoint) to the API.</returns>
string BuildUrl(IList<UrlSegment> urlSegments);
}
}
| using System.Collections.Generic;
using System.Net.Http;
namespace B2.Client.Rest
{
/// <summary>
/// Represents a REST client request.
/// </summary>
public interface IRestRequest
{
/// <summary>
/// The HTTP method to be used for this request.
/// </summary>
HttpMethod Method { get; }
/// <summary>
/// Request parameters that belong in the HTTP header.
/// </summary>
IList<Param> HeaderParameters { get; }
/// <summary>
/// Request parameters that belong in the HTTP query string.
/// </summary>
IList<Param> QueryParameters { get; }
/// <summary>
/// Request parameters that belong in the URL.
/// </summary>
IList<Param> UrlParameters { get; }
/// <summary>
/// Request parameters that belong in the HTTP POST body.
/// </summary>
IList<RequestData> PostParameters { get; }
/// <summary>
/// Convert the Request for a given URL to an HttpClient HttpRequestMessage.
/// <param name="urlSegments">The URL segments for the request.</param>
/// </summary>
/// <returns>An HttpClient HttpRequestMessage.</returns>
HttpRequestMessage ToHttpRequestMessage(IList<UrlSegment> urlSegments);
/// <summary>
/// Form a complete URL for an API from components.
/// </summary>
/// <param name="urlSegments">The segments that make up the URL for the request.</param>
/// <returns>An URL (excluding endpoint) to the API.</returns>
string BuildUrl(IList<UrlSegment> urlSegments);
}
}
| mit | C# |
380726b71cc3dd7746684e223bb2a793db625f6c | Fix exception message | cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium | Src/MaintainableSelenium/MaintainableSelenium.MvcPages/WebPages/WebForms/UnableToSetFieldValueException.cs | Src/MaintainableSelenium/MaintainableSelenium.MvcPages/WebPages/WebForms/UnableToSetFieldValueException.cs | using System;
namespace MaintainableSelenium.MvcPages.WebPages.WebForms
{
public class UnableToSetFieldValueException:ApplicationException
{
public UnableToSetFieldValueException(string fieldName, string value)
: base(string.Format("Cannot set value '{0}' for field '{1}'", value, fieldName))
{
}
}
} | using System;
namespace MaintainableSelenium.MvcPages.WebPages.WebForms
{
public class UnableToSetFieldValueException:ApplicationException
{
public UnableToSetFieldValueException(string fieldName, string value)
: base(string.Format("Cannot set value '{0}' for field '{1}'", fieldName, value))
{
}
}
} | mit | C# |
f334fd6b7eab616b3a188124a77ff1f791a14509 | Make bool type coercion work with arrays, and improve handling of non-null objects as expression arguments to unary ! and such | kayateia/scriptdotnet,kayateia/scriptdotnet | TypeCoercion.cs | TypeCoercion.cs | namespace ScriptNET {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal class TypeCoercion {
// Handle type coercion to bool for Javascript-style if(foo) statements.
static public object CoerceToBool(object obj) {
if (obj is bool) {
// Do nothing, we're fine.
} else if (obj is string) {
// A non-empty string is true.
obj = !string.IsNullOrEmpty(obj as string);
} else if (obj is Array) {
obj = ((Array)obj).Length > 0;
} else if (obj == null) {
obj = false;
} else {
// Give the binder a chance to splice in a bool coercion.
var equalityMethod = Runtime.RuntimeHost.Binder.BindToMethod(obj, "IsTrue", null, new object[0]);
if (equalityMethod != null) {
var result = equalityMethod.Invoke(null, new object[0]);
if (result is bool)
obj = (bool)result;
else
obj = obj != null;
}
}
// If all else fails...
if (!(obj is bool)) {
// A non-null object is true.
obj = obj != null;
}
return obj;
}
}
}
| namespace ScriptNET {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
internal class TypeCoercion {
// Handle type coercion to bool for Javascript-style if(foo) statements.
static public object CoerceToBool(object obj) {
if (obj is bool) {
// Do nothing, we're fine.
} else if (obj is string) {
// A non-empty string is true.
obj = !string.IsNullOrEmpty(obj as string);
} else {
// Give the binder a chance to splice in a bool coercion.
var equalityMethod = Runtime.RuntimeHost.Binder.BindToMethod(obj, "IsTrue", null, new object[0]);
if (equalityMethod != null) {
var result = equalityMethod.Invoke(null, new object[0]);
if (result is bool)
obj = (bool)result;
else
obj = obj != null;
} else {
// A non-null object is true.
obj = obj != null;
}
}
return obj;
}
}
}
| mit | C# |
5ad122bfec900566a9d3ec1ad5f910d5e77c3528 | Fix beatmaps importing with -1 as online set ID | ppy/osu,smoogipoo/osu,DrabWeb/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,ZLima12/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,2yangk23/osu,EVAST9919/osu,naoey/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu-new,naoey/osu,peppy/osu,naoey/osu,smoogipoo/osu | osu.Game/Beatmaps/BeatmapSetInfo.cs | osu.Game/Beatmaps/BeatmapSetInfo.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using osu.Game.Database;
namespace osu.Game.Beatmaps
{
public class BeatmapSetInfo : IHasPrimaryKey, IHasFiles<BeatmapSetFileInfo>, ISoftDelete
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
private int? onlineBeatmapSetID;
public int? OnlineBeatmapSetID
{
get { return onlineBeatmapSetID; }
set { onlineBeatmapSetID = value > 0 ? value : null; }
}
public BeatmapMetadata Metadata { get; set; }
public List<BeatmapInfo> Beatmaps { get; set; }
[NotMapped]
public BeatmapSetOnlineInfo OnlineInfo { get; set; }
public double MaxStarDifficulty => Beatmaps?.Max(b => b.StarDifficulty) ?? 0;
[NotMapped]
public bool DeletePending { get; set; }
public string Hash { get; set; }
public string StoryboardFile => Files?.FirstOrDefault(f => f.Filename.EndsWith(".osb"))?.Filename;
public List<BeatmapSetFileInfo> Files { get; set; }
public override string ToString() => Metadata?.ToString() ?? base.ToString();
public bool Protected { get; set; }
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using osu.Game.Database;
namespace osu.Game.Beatmaps
{
public class BeatmapSetInfo : IHasPrimaryKey, IHasFiles<BeatmapSetFileInfo>, ISoftDelete
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public int? OnlineBeatmapSetID { get; set; }
public BeatmapMetadata Metadata { get; set; }
public List<BeatmapInfo> Beatmaps { get; set; }
[NotMapped]
public BeatmapSetOnlineInfo OnlineInfo { get; set; }
public double MaxStarDifficulty => Beatmaps?.Max(b => b.StarDifficulty) ?? 0;
[NotMapped]
public bool DeletePending { get; set; }
public string Hash { get; set; }
public string StoryboardFile => Files?.FirstOrDefault(f => f.Filename.EndsWith(".osb"))?.Filename;
public List<BeatmapSetFileInfo> Files { get; set; }
public override string ToString() => Metadata?.ToString() ?? base.ToString();
public bool Protected { get; set; }
}
}
| mit | C# |
1f93a1d93841a8973252c84664d2ea1cb037c120 | Fix up first responder callback | jamesmontemagno/Office365-FiveMinuteMeeting,gxy001/Office365-FiveMinuteMeeting | FiveMinuteMeeting.iOS/ContactDetailViewController.cs | FiveMinuteMeeting.iOS/ContactDetailViewController.cs | using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.CodeDom.Compiler;
using MonoTouch.MessageUI;
using Microsoft.Office365.OutlookServices;
namespace FiveMinuteMeeting.iOS
{
partial class ContactDetailViewController : UIViewController
{
public ContactDetailViewController(IntPtr handle)
: base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;
var save = new UIBarButtonItem(
UIImage.FromBundle("save.png"),
UIBarButtonItemStyle.Plain,
(sender, args) =>
{
});
NavigationItem.RightBarButtonItem = save;
TextEmail.ShouldReturn += ShouldReturn;
TextFirst.ShouldReturn += ShouldReturn;
TextPhone.ShouldReturn += ShouldReturn;
TextLast.ShouldReturn += ShouldReturn;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if(Contact == null)
{
this.Title = "New Contact";
}
else
{
this.Title = Contact.GivenName;
}
}
private bool ShouldReturn(UITextField field)
{
field.ResignFirstResponder();
return true;
}
public IContact Contact { get; set; }
private void PlaceCall()
{
var alertPrompt = new UIAlertView("Dial Number?",
"Do you want to call " + string.Empty + "?",
null, "No", "Yes");
alertPrompt.Dismissed += (sender, e) =>
{
if (e.ButtonIndex >= alertPrompt.FirstOtherButtonIndex)
{
NSUrl url = new NSUrl("tel:" + string.Empty);
UIApplication.SharedApplication.OpenUrl(url);
}
};
alertPrompt.Show();
}
private async void SendEmail()
{
var mailController = new MFMailComposeViewController();
mailController.SetToRecipients(new string[] { "john@doe.com" });
mailController.SetSubject("mail test");
mailController.SetMessageBody("this is a test", false);
await PresentViewControllerAsync(mailController, true);
mailController.DismissViewControllerAsync(true);
}
}
}
| using System;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using System.CodeDom.Compiler;
using MonoTouch.MessageUI;
using Microsoft.Office365.OutlookServices;
namespace FiveMinuteMeeting.iOS
{
partial class ContactDetailViewController : UIViewController
{
public ContactDetailViewController(IntPtr handle)
: base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
NavigationController.NavigationBar.BarStyle = UIBarStyle.Black;
var save = new UIBarButtonItem(
UIImage.FromBundle("save.png"),
UIBarButtonItemStyle.Plain,
(sender, args) =>
{
});
NavigationItem.RightBarButtonItem = save;
TextEmail.ShouldReturn += ShouldReturn;
TextFirst.ShouldReturn += ShouldReturn;
TextPhone.ShouldReturn += ShouldReturn;
TextLast.ShouldReturn += ShouldReturn;
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
if(Contact == null)
{
this.Title = "New Contact";
}
else
{
this.Title = Contact.GivenName;
}
}
private void ShouldReturn(UITextField field)
{
field.ResignFirstResponder(); ;
}
public IContact Contact { get; set; }
private void PlaceCall()
{
var alertPrompt = new UIAlertView("Dial Number?",
"Do you want to call " + string.Empty + "?",
null, "No", "Yes");
alertPrompt.Dismissed += (sender, e) =>
{
if (e.ButtonIndex >= alertPrompt.FirstOtherButtonIndex)
{
NSUrl url = new NSUrl("tel:" + string.Empty);
UIApplication.SharedApplication.OpenUrl(url);
}
};
alertPrompt.Show();
}
private async void SendEmail()
{
var mailController = new MFMailComposeViewController();
mailController.SetToRecipients(new string[] { "john@doe.com" });
mailController.SetSubject("mail test");
mailController.SetMessageBody("this is a test", false);
await PresentViewControllerAsync(mailController, true);
mailController.DismissViewControllerAsync(true);
}
}
}
| mit | C# |
1c8f46fe5db68b7f74ecd53e30ce332dbd2be173 | Delete commented out code | xyon1/Expenditure-App | GeneralUseClasses/Services/IRecordExpenditureData.cs | GeneralUseClasses/Services/IRecordExpenditureData.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GeneralUseClasses.Contracts;
namespace GeneralUseClasses.Services
{
public interface IRecordExpenditureData
{
void RecordExpenditureData(IExpenditureEntry entry);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GeneralUseClasses.Contracts;
namespace GeneralUseClasses.Services
{
public interface IRecordExpenditureData
{
//IExpenditureEntry ExpenditureData { get; set; }
void RecordExpenditureData(IExpenditureEntry entry);
}
}
| apache-2.0 | C# |
df64d80570de8430cfa03e33fe1fc4024667b7e4 | Fix namespaces in ProjectCreateViewModel | leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net | Joinrpg/Models/ProjectCreateViewModel.cs | Joinrpg/Models/ProjectCreateViewModel.cs | namespace JoinRpg.Web.Models
{
public class ProjectCreateViewModel
{
public string ProjectName { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JoinRpg.Web.Models
{
public class ProjectCreateViewModel
{
public string ProjectName { get; set; }
}
}
| mit | C# |
a9fa229f8f7e5666fb88cd433e4bb8ec1c7db453 | Remove preprocess for texturemodel | tobyclh/UnityCNTK,tobyclh/UnityCNTK | Assets/UnityCNTK/Scripts/Models/TextureTransferModel.cs | Assets/UnityCNTK/Scripts/Models/TextureTransferModel.cs | using UnityEngine;
using CNTK;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using UnityCNTK;
using System.Net;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
[CreateAssetMenu(fileName = "TextureModel", menuName = "UnityCNTk/Model/TextureModel")]
public class TextureModel : Model
{
public new string relativeModelPath = "Assets/UnityCNTK/Model/VGG.dnn";
public double contentWeight = 5;
public double styleWeight = 1;
public double decay = 0.5f;
public int width = 50;
public int height = 50;
// Use this for initialization
//post processing output data
protected override void OnEvaluated(Dictionary<Variable, Value> outputDataMap)
{
List<Texture2D> textures = new List<Texture2D>();
// function.Evaluate(new Dictionary<Variable, Value>().Add(inputVar,))
Texture2D outputTexture = new Texture2D(width, height);
output = textures;
}
}
}
| using UnityEngine;
using CNTK;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using UnityCNTK;
using System.Net;
using System.Threading;
using UnityEngine.Assertions;
namespace UnityCNTK
{
[CreateAssetMenu(fileName = "TextureModel", menuName = "UnityCNTk/Model/TextureModel")]
public class TextureModel : Model
{
public new string relativeModelPath = "Assets/UnityCNTK/Model/VGG.dnn";
public double contentWeight = 5;
public double styleWeight = 1;
public double decay = 0.5f;
public int width = 50;
public int height = 50;
// Use this for initialization
//post processing output data
protected override void OnEvaluated(Dictionary<Variable, Value> outputDataMap)
{
List<Texture2D> textures = new List<Texture2D>();
// function.Evaluate(new Dictionary<Variable, Value>().Add(inputVar,))
Texture2D outputTexture = new Texture2D(width, height);
output = textures;
}
protected override List<Dictionary<Variable, Value>> OnPreprocess(UnityEngine.Object input)
{
var inputVar = function.Arguments.Single();
var resized = ((Texture2D)input).ResampleAndCrop(width, height);
var inputDataMap = new Dictionary<Variable, Value>() { { inputVar, resized.ToValue(CNTKManager.device) } };
var outputDataMap = new Dictionary<Variable, Value>() { { function.Output, null } };
return new List<Dictionary<Variable, Value>>() { inputDataMap, outputDataMap };
}
}
}
| mit | C# |
ad83ea70c62bf9bf71e7d55e4d3ce52850db1e0e | Initialize the OcclusionGeometryConcatenator to empty instead of null | virtuallynaked/virtually-naked,virtuallynaked/virtually-naked | Importer/src/occlusion/OcclusionGeometryConcatenator.cs | Importer/src/occlusion/OcclusionGeometryConcatenator.cs | using System.Linq;
public class OcclusionGeometryConcatenator {
private SubdivisionMesh combinedMesh = SubdivisionMesh.Empty;
private float[] combinedFaceTransparencies = new float[0];
public ArraySegment Add(SubdivisionMesh mesh, float[] faceTransparencies) {
int startingOffset = combinedMesh.Topology.VertexCount;
combinedMesh = SubdivisionMesh.Combine(this.combinedMesh, mesh);
combinedFaceTransparencies = this.combinedFaceTransparencies.Concat(faceTransparencies).ToArray();
int count = mesh.Topology.VertexCount;
return new ArraySegment(startingOffset, count);
}
public ArraySegment Add(HemisphereOcclusionSurrogate surrogate) {
int dummyVertexCount = surrogate.SampleCount;
var dummyMesh = new SubdivisionMesh(
0,
new QuadTopology(dummyVertexCount, new Quad[0]),
PackedLists<WeightedIndexWithDerivatives>.MakeEmptyLists(dummyVertexCount));
var dummyFaceTransparencies = new float[0];
return Add(dummyMesh, dummyFaceTransparencies);
}
public float[] FaceTransparencies => combinedFaceTransparencies;
public SubdivisionMesh Mesh => combinedMesh;
}
| using System.Linq;
public class OcclusionGeometryConcatenator {
private SubdivisionMesh combinedMesh;
private float[] combinedFaceTransparencies;
public ArraySegment Add(SubdivisionMesh mesh, float[] faceTransparencies) {
if (combinedMesh == null) {
combinedMesh = mesh;
combinedFaceTransparencies = faceTransparencies;
int count = mesh.Topology.VertexCount;
return new ArraySegment(0, count);
} else {
int startingOffset = combinedMesh.Topology.VertexCount;
combinedMesh = SubdivisionMesh.Combine(this.combinedMesh, mesh);
combinedFaceTransparencies = this.combinedFaceTransparencies.Concat(faceTransparencies).ToArray();
int count = mesh.Topology.VertexCount;
return new ArraySegment(startingOffset, count);
}
}
public ArraySegment Add(HemisphereOcclusionSurrogate surrogate) {
int dummyVertexCount = surrogate.SampleCount;
var dummyMesh = new SubdivisionMesh(
0,
new QuadTopology(dummyVertexCount, new Quad[0]),
PackedLists<WeightedIndexWithDerivatives>.MakeEmptyLists(dummyVertexCount));
var dummyFaceTransparencies = new float[0];
return Add(dummyMesh, dummyFaceTransparencies);
}
public float[] FaceTransparencies => combinedFaceTransparencies;
public SubdivisionMesh Mesh => combinedMesh;
}
| mit | C# |
ac9bbab618055e15d1ce98af7e998e019ad90595 | Allow getting a user env variable | sdl/groupsharekit.net | Sdl.Community.GroupShareKit.Tests.Integration/Helper.cs | Sdl.Community.GroupShareKit.Tests.Integration/Helper.cs | using System;
using System.Threading.Tasks;
using Sdl.Community.GroupShareKit.Clients;
using Sdl.Community.GroupShareKit.Http;
namespace Sdl.Community.GroupShareKit.Tests.Integration
{
public static class Helper
{
public static string GetVariable(string key)
{
// by default it gets a process variable. Allow getting user as well
return Environment.GetEnvironmentVariable(key) ??
Environment.GetEnvironmentVariable(key, EnvironmentVariableTarget.User);
}
public static async Task<GroupShareClient> GetGroupShareClient()
{
var groupShareUser = Helper.GetVariable("GROUPSHAREKIT_USERNAME");
var groupSharePassword = Helper.GetVariable("GROUPSHAREKIT_PASSWORD");
var token =
await
GroupShareClient.GetRequestToken(groupShareUser, groupSharePassword, BaseUri,
GroupShareClient.AllScopes);
var gsClient =
await
GroupShareClient.AuthenticateClient(token, groupShareUser, groupSharePassword,BaseUri,
GroupShareClient.AllScopes);
return gsClient;
}
public static Uri BaseUri => new Uri(Helper.GetVariable("GROUPSHAREKIT_BASEURI"));
public static string TestOrganization => Helper.GetVariable("GROUPSHAREKIT_TESTORGANIZATION");
}
}
| using System;
using System.Threading.Tasks;
using Sdl.Community.GroupShareKit.Clients;
using Sdl.Community.GroupShareKit.Http;
namespace Sdl.Community.GroupShareKit.Tests.Integration
{
public static class Helper
{
public static async Task<GroupShareClient> GetGroupShareClient()
{
var groupShareUser = Environment.GetEnvironmentVariable("GROUPSHAREKIT_USERNAME");
var groupSharePassword = Environment.GetEnvironmentVariable("GROUPSHAREKIT_PASSWORD");
var token =
await
GroupShareClient.GetRequestToken(groupShareUser, groupSharePassword, BaseUri,
GroupShareClient.AllScopes);
var gsClient =
await
GroupShareClient.AuthenticateClient(token, groupShareUser, groupSharePassword,BaseUri,
GroupShareClient.AllScopes);
return gsClient;
}
public static Uri BaseUri => new Uri(Environment.GetEnvironmentVariable("GROUPSHAREKIT_BASEURI"));
public static string TestOrganization => Environment.GetEnvironmentVariable("GROUPSHAREKIT_TESTORGANIZATION");
}
}
| mit | C# |
33eaeff9ac35820012b24cb3872c8095454a650f | Fix localization context issue in OrchardCore.Templates (#4042) | petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard | src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypeDefinitionDriver.cs | src/OrchardCore.Modules/OrchardCore.Templates/Settings/TemplateContentTypeDefinitionDriver.cs | using Microsoft.Extensions.Localization;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Templates.ViewModels;
namespace OrchardCore.Templates.Settings
{
public class TemplateContentTypeDefinitionDriver : ContentTypeDefinitionDisplayDriver
{
private readonly IStringLocalizer<TemplateContentTypeDefinitionDriver> S;
public TemplateContentTypeDefinitionDriver(IStringLocalizer<TemplateContentTypeDefinitionDriver> localizer)
{
S = localizer;
}
public override IDisplayResult Edit(ContentTypeDefinition contentTypeDefinition)
{
return Initialize<ContentSettingsViewModel>("TemplateSettings", model =>
{
var stereotype = contentTypeDefinition.Settings.ToObject<ContentTypeSettings>().Stereotype;
if (string.IsNullOrWhiteSpace(stereotype))
{
stereotype = "Content";
}
model.ContentSettingsEntries.Add(
new ContentSettingsEntry
{
Key = $"{stereotype}__{contentTypeDefinition.Name}",
Description = S["Template for a {0} content item in detail views", contentTypeDefinition.DisplayName]
});
model.ContentSettingsEntries.Add(
new ContentSettingsEntry
{
Key = $"{stereotype}_Summary__{contentTypeDefinition.Name}",
Description = S["Template for a {0} content item in summary views", contentTypeDefinition.DisplayName]
});
}).Location("Content");
}
}
} | using Microsoft.Extensions.Localization;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentTypes.Editors;
using OrchardCore.DisplayManagement.Views;
using OrchardCore.Templates.ViewModels;
namespace OrchardCore.Templates.Settings
{
public class TemplateContentTypeDefinitionDriver : ContentTypeDefinitionDisplayDriver
{
private readonly IStringLocalizer<TemplateContentPartDefinitionDriver> S;
public TemplateContentTypeDefinitionDriver(IStringLocalizer<TemplateContentPartDefinitionDriver> localizer)
{
S = localizer;
}
public override IDisplayResult Edit(ContentTypeDefinition contentTypeDefinition)
{
return Initialize<ContentSettingsViewModel>("TemplateSettings", model =>
{
var stereotype = contentTypeDefinition.Settings.ToObject<ContentTypeSettings>().Stereotype;
if (string.IsNullOrWhiteSpace(stereotype))
{
stereotype = "Content";
}
model.ContentSettingsEntries.Add(
new ContentSettingsEntry
{
Key = $"{stereotype}__{contentTypeDefinition.Name}",
Description = S["Template for a {0} content item in detail views", contentTypeDefinition.DisplayName]
});
model.ContentSettingsEntries.Add(
new ContentSettingsEntry
{
Key = $"{stereotype}_Summary__{contentTypeDefinition.Name}",
Description = S["Template for a {0} content item in summary views", contentTypeDefinition.DisplayName]
});
}).Location("Content");
}
}
} | bsd-3-clause | C# |
7b8d34243aa5e5af4fcdf6963765f7ed75f3126f | Update Error.cshtml.cs | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/ProjectTemplates/Web.Spa.ProjectTemplates/content/ReactRedux-CSharp/Pages/Error.cshtml.cs | src/ProjectTemplates/Web.Spa.ProjectTemplates/content/ReactRedux-CSharp/Pages/Error.cshtml.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace Company.WebApplication1.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
private readonly ILogger<ErrorModel> logger;
public ErrorModel(ILogger<ErrorModel> _logger)
{
logger = _logger;
}
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Company.WebApplication1.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
private readonly ILogger<ErrorModel> logger;
public ErrorModel(ILogger<ErrorModel> _logger)
{
logger = _logger;
}
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| apache-2.0 | C# |
47ec42e9d2d101d1ce5bff794cc3d9a22784348f | Fix bug with 1080p WP 8.1 devices (using a strange hack) | ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus,ValentinMinder/pocketcampus | Windows/Source/Common.WindowsPhone/Controls/BasePage.cs | Windows/Source/Common.WindowsPhone/Controls/BasePage.cs | // Copyright (c) PocketCampus.Org 2014
// See LICENSE file for more details
// File author: Solal Pirelli
using System.Windows;
using Microsoft.Phone.Controls;
namespace PocketCampus.Common.Controls
{
/// <summary>
/// Base class for all pages.
/// Contains animations and orientation visual states.
/// </summary>
[TemplateVisualState( GroupName = "OrientationStates", Name = "Portrait" )]
[TemplateVisualState( GroupName = "OrientationStates", Name = "Landscape" )]
public class BasePage : PhoneApplicationPage
{
/// <summary>
/// Creates a new BasePage.
/// </summary>
public BasePage()
{
TransitionService.SetNavigationInTransition( this, new NavigationInTransition
{
Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardIn },
Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardIn }
} );
TransitionService.SetNavigationOutTransition( this, new NavigationOutTransition
{
Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardOut },
Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardOut }
} );
Style = (Style) Application.Current.Resources["AppPageStyle"];
Loaded += ( s, e ) =>
{
if ( ApplicationBar != null )
{
ThemeManager.MatchOverriddenTheme( ApplicationBar );
// HACK to avoid strange problems with 1080p WP 8.1 devices
// see http://social.msdn.microsoft.com/Forums/wpapps/en-US/4a82edc5-273b-4655-95d6-aee6e953aaaa/1920x1080-black-border-at-the-bottom?forum=wpdevelop
ApplicationBar.Opacity = 0.99;
}
};
}
protected override void OnOrientationChanged( OrientationChangedEventArgs e )
{
base.OnOrientationChanged( e );
if ( e.Orientation.HasFlag( PageOrientation.Portrait ) )
{
VisualStateManager.GoToState( this, "Portrait", true );
}
else if ( e.Orientation.HasFlag( PageOrientation.Landscape ) )
{
VisualStateManager.GoToState( this, "Landscape", true );
}
}
}
} | // Copyright (c) PocketCampus.Org 2014
// See LICENSE file for more details
// File author: Solal Pirelli
using System.Windows;
using Microsoft.Phone.Controls;
namespace PocketCampus.Common.Controls
{
/// <summary>
/// Base class for all pages.
/// Contains animations and orientation visual states.
/// </summary>
[TemplateVisualState( GroupName = "OrientationStates", Name = "Portrait" )]
[TemplateVisualState( GroupName = "OrientationStates", Name = "Landscape" )]
public class BasePage : PhoneApplicationPage
{
/// <summary>
/// Creates a new BasePage.
/// </summary>
public BasePage()
{
TransitionService.SetNavigationInTransition( this, new NavigationInTransition
{
Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardIn },
Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardIn }
} );
TransitionService.SetNavigationOutTransition( this, new NavigationOutTransition
{
Backward = new TurnstileTransition { Mode = TurnstileTransitionMode.BackwardOut },
Forward = new TurnstileTransition { Mode = TurnstileTransitionMode.ForwardOut }
} );
Style = (Style) Application.Current.Resources["AppPageStyle"];
// TODO: If (when?) the PhoneThemeManager is updated to include an option to override the app bar only, remove this
Loaded += ( s, e ) => ThemeManager.MatchOverriddenTheme( this.ApplicationBar );
}
protected override void OnOrientationChanged( OrientationChangedEventArgs e )
{
base.OnOrientationChanged( e );
if ( e.Orientation.HasFlag( PageOrientation.Portrait ) )
{
VisualStateManager.GoToState( this, "Portrait", true );
}
else if ( e.Orientation.HasFlag( PageOrientation.Landscape ) )
{
VisualStateManager.GoToState( this, "Landscape", true );
}
}
}
} | bsd-3-clause | C# |
ceeb59518c1cf625f0c02a3b837f2e0fc131551f | Remove setter from List in test | Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet | Tests/WeaverTests/AssemblyToProcess/FaultyClasses.cs | Tests/WeaverTests/AssemblyToProcess/FaultyClasses.cs | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using Realms;
namespace AssemblyToProcess
{
public class RealmListWithSetter : RealmObject
{
public IList<Person> People { get; }
}
public class IndexedProperties : RealmObject
{
// These should be allowed:
[Indexed]
public int IntProperty { get; set; }
[Indexed]
public string StringProperty { get; set; }
[Indexed]
public bool BooleanProperty { get; set; }
[Indexed]
public DateTimeOffset DateTimeOffsetProperty { get; set; }
// This should cause an error:
[Indexed]
public float SingleProperty { get; set; }
}
public class ObjectIdProperties : RealmObject
{
// These should be allowed:
[ObjectId]
public int IntProperty { get; set; }
[ObjectId]
public string StringProperty { get; set; }
// These should cause errors:
[ObjectId]
public bool BooleanProperty { get; set; }
[ObjectId]
public DateTimeOffset DateTimeOffsetProperty { get; set; }
[ObjectId]
public float SingleProperty { get; set; }
}
// This class has no default constructor which is necessary for Realm.CreateObject<>()
public class DefaultConstructorMissing : RealmObject
{
public DefaultConstructorMissing(int parameter) { }
}
}
| ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using Realms;
namespace AssemblyToProcess
{
public class RealmListWithSetter : RealmObject
{
public IList<Person> People { get; set; }
}
public class IndexedProperties : RealmObject
{
// These should be allowed:
[Indexed]
public int IntProperty { get; set; }
[Indexed]
public string StringProperty { get; set; }
[Indexed]
public bool BooleanProperty { get; set; }
[Indexed]
public DateTimeOffset DateTimeOffsetProperty { get; set; }
// This should cause an error:
[Indexed]
public float SingleProperty { get; set; }
}
public class ObjectIdProperties : RealmObject
{
// These should be allowed:
[ObjectId]
public int IntProperty { get; set; }
[ObjectId]
public string StringProperty { get; set; }
// These should cause errors:
[ObjectId]
public bool BooleanProperty { get; set; }
[ObjectId]
public DateTimeOffset DateTimeOffsetProperty { get; set; }
[ObjectId]
public float SingleProperty { get; set; }
}
// This class has no default constructor which is necessary for Realm.CreateObject<>()
public class DefaultConstructorMissing : RealmObject
{
public DefaultConstructorMissing(int parameter) { }
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.