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 |
|---|---|---|---|---|---|---|---|---|
f1ea65145bd084f76414a2f93ca6e208853d2de6 | Add ExclamationMark token | transistor1/PoorMansTSqlFormatter,transistor1/PoorMansTSqlFormatter,transistor1/PoorMansTSqlFormatter,transistor1/PoorMansTSqlFormatter | PoorMansTSqlFormatterLib/Interfaces/SqlTokenType.cs | PoorMansTSqlFormatterLib/Interfaces/SqlTokenType.cs | /*
Poor Man's T-SQL Formatter - a small free Transact-SQL formatting
library for .Net 2.0, written in C#.
Copyright (C) 2011-2013 Tao Klerks
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace PoorMansTSqlFormatterLib.Interfaces
{
public enum SqlTokenType
{
OpenParens,
CloseParens,
WhiteSpace,
OtherNode,
SingleLineComment,
SingleLineCommentCStyle,
MultiLineComment,
String,
NationalString,
BracketQuotedName,
QuotedString,
Comma,
Period,
Semicolon,
Colon,
Asterisk,
EqualsSign,
MonetaryValue,
Number,
BinaryValue,
OtherOperator,
PseudoName,
ExclamationMark
}
} | /*
Poor Man's T-SQL Formatter - a small free Transact-SQL formatting
library for .Net 2.0, written in C#.
Copyright (C) 2011-2013 Tao Klerks
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
namespace PoorMansTSqlFormatterLib.Interfaces
{
public enum SqlTokenType
{
OpenParens,
CloseParens,
WhiteSpace,
OtherNode,
SingleLineComment,
SingleLineCommentCStyle,
MultiLineComment,
String,
NationalString,
BracketQuotedName,
QuotedString,
Comma,
Period,
Semicolon,
Colon,
Asterisk,
EqualsSign,
MonetaryValue,
Number,
BinaryValue,
OtherOperator,
PseudoName
}
} | agpl-3.0 | C# |
c80450666cb53c6ed001910bc75141e3aba57a8b | Use CancelKeyPress event to exist ServerNode app. | icsharp/Hangfire.Topshelf,icsharp/Hangfire.Topshelf,icsharp/Hangfire.Topshelf | cluster/HF.Samples.ServerNode/Program.cs | cluster/HF.Samples.ServerNode/Program.cs | using System;
using System.Reflection;
using System.Threading;
using Autofac;
using CommandLine;
using Serilog;
using Hangfire;
using Hangfire.Samples.Framework;
using Hangfire.Samples.Framework.Logging;
using HF.Samples.GoodsService;
using HF.Samples.OrderService;
using HF.Samples.StorageService;
namespace HF.Samples.ServerNode
{
public class Program
{
private static ILog _logger = LogProvider.For<Program>();
private static ManualResetEvent _signal = null;
private static BackgroundJobServer _backgroundJobServer = null;
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile("logs\\log-{Date}.txt")
.CreateLogger();
Parser.Default.ParseArguments<NodeOptions>(args)
.WithNotParsed(_ => _logger.Info("Arguments configuration is empty, you can view command line by type: --help"))
.WithParsed(opts =>
{
_logger.InfoFormat("Accepted args: {@opts}", opts);
_signal = new ManualResetEvent(false);
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
_signal.Set();
};
//start hangfire server here
UseHangfireServer(opts);
});
_logger.Info("Press Enter Ctrl+C to exit...");
_signal?.WaitOne();
_backgroundJobServer?.Dispose();
}
private static void UseHangfireServer(NodeOptions opts)
{
var options = new BackgroundJobServerOptions
{
ServerName = opts.Identifier,
WorkerCount = opts.WorkerCount,
Queues = opts.Queues.Split(',')
};
UseAutofac();
GlobalConfiguration.Configuration.UseRedisStorage();
_backgroundJobServer = new BackgroundJobServer(options);
}
private static void UseAutofac()
{
var builder = new ContainerBuilder();
builder.RegisterModule(new DelegateModule(() => new Assembly[]
{
typeof(IProductService).GetTypeInfo().Assembly,
typeof(IOrderService).GetTypeInfo().Assembly,
typeof(IInventoryService).GetTypeInfo().Assembly
}));
var container = builder.Build();
GlobalConfiguration.Configuration.UseAutofacActivator(container);
}
}
}
| using System;
using System.Reflection;
using Autofac;
using CommandLine;
using Serilog;
using Hangfire;
using Hangfire.Samples.Framework;
using Hangfire.Samples.Framework.Logging;
using HF.Samples.GoodsService;
using HF.Samples.OrderService;
using HF.Samples.StorageService;
namespace HF.Samples.ServerNode
{
public class Program
{
private static ILog _logger = LogProvider.For<Program>();
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile("logs\\log-{Date}.txt")
.CreateLogger();
Parser.Default.ParseArguments<NodeOptions>(args)
.WithNotParsed(_ => _logger.Info("Arguments configuration is empty, you can view command line by type: --help"))
.WithParsed(opts =>
{
_logger.InfoFormat("Accepted args: {@opts}", opts);
//start hangfire server here
UseHangfireServer(opts);
});
_logger.Info("Press Enter to exit...");
Console.ReadLine();
}
private static void UseHangfireServer(NodeOptions opts)
{
var options = new BackgroundJobServerOptions
{
ServerName = opts.Identifier,
WorkerCount = opts.WorkerCount,
Queues = opts.Queues.Split(',')
};
UseAutofac();
GlobalConfiguration.Configuration.UseRedisStorage();
using (new BackgroundJobServer(options))
{
while (true)
{
var command = Console.ReadLine();
if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase))
{
break;
}
}
}
}
private static void UseAutofac()
{
var builder = new ContainerBuilder();
builder.RegisterModule(new DelegateModule(() => new Assembly[]
{
typeof(IProductService).GetTypeInfo().Assembly,
typeof(IOrderService).GetTypeInfo().Assembly,
typeof(IInventoryService).GetTypeInfo().Assembly
}));
var container = builder.Build();
GlobalConfiguration.Configuration.UseAutofacActivator(container);
}
}
}
| mit | C# |
c8099872fdcff56c6c97624fec324ec939feb725 | Add clarifying comment. | PlanetLotus/TetrisClone2D | Assets/GridManager.cs | Assets/GridManager.cs | using UnityEngine;
public class GridManager : MonoBehaviour
{
public bool IsValidPosition(Transform transform)
{
// Check out of bounds
if (transform.position.x > MaxX || transform.position.x < MinX ||
transform.position.y < MinY)
{
return false;
}
// If spot is full (not null) and is occupied by another shape (different parent), it's invalid
// This may be naive, but we assume that the shape won't try to collide with itself
if (grid[(int)transform.position.x, (int)transform.position.y] != null &&
grid[(int)transform.position.x, (int)transform.position.y].parent != transform.parent)
{
return false;
}
return true;
}
public void UpdatePosition(Transform transform)
{
// Also naive. Trusts the caller that this position is valid.
// Should really be "UpdatePositionIfValid" and return whether it was updated.
// Also confusing that this is just one block and not the whole shape.
UnsetOldPosition(transform);
grid[(int)transform.position.x, (int)transform.position.y] = transform;
}
private void UnsetOldPosition(Transform transform)
{
// This would be much better if the old position were passed in,
// but we can't assume that that position hasn't already been taken up by
// another block if this isn't the first block in the shape. We'd need to unset
// them all first.
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
if (grid[x, y] == transform)
{
grid[x, y] = null;
return;
}
}
}
}
private void Start()
{
}
private void Update()
{
// Check for completed rows and clear them
}
private const int Width = 10;
private const int Height = 26;
private const int MinX = 0;
private const int MaxX = 10;
private const int MinY = 0;
// Each transform is a block, not the entire shape
// Instead of just setting a flag here, having the actual object helps
// us determine how it relates to the objects around it, like
// whether they're attached to the same shape.
private Transform[,] grid = new Transform[Width, Height];
}
| using UnityEngine;
public class GridManager : MonoBehaviour
{
public bool IsValidPosition(Transform transform)
{
// Check out of bounds
if (transform.position.x > MaxX || transform.position.x < MinX ||
transform.position.y < MinY)
{
return false;
}
// If spot is full (not null) and is occupied by another shape (different parent), it's invalid
// This may be naive, but we assume that the shape won't try to collide with itself
if (grid[(int)transform.position.x, (int)transform.position.y] != null &&
grid[(int)transform.position.x, (int)transform.position.y].parent != transform.parent)
{
return false;
}
return true;
}
public void UpdatePosition(Transform transform)
{
// Also naive. Trusts the caller that this position is valid.
// Should really be "UpdatePositionIfValid" and return whether it was updated.
// Also confusing that this is just one block and not the whole shape.
UnsetOldPosition(transform);
grid[(int)transform.position.x, (int)transform.position.y] = transform;
}
private void UnsetOldPosition(Transform transform)
{
for (int x = 0; x < Width; x++)
{
for (int y = 0; y < Height; y++)
{
if (grid[x, y] == transform)
{
grid[x, y] = null;
return;
}
}
}
}
private void Start()
{
}
private void Update()
{
// Check for completed rows and clear them
}
private const int Width = 10;
private const int Height = 26;
private const int MinX = 0;
private const int MaxX = 10;
private const int MinY = 0;
// Each transform is a block, not the entire shape
// Instead of just setting a flag here, having the actual object helps
// us determine how it relates to the objects around it, like
// whether they're attached to the same shape.
private Transform[,] grid = new Transform[Width, Height];
}
| mit | C# |
6ff52de55637424185397fbc1dbd7060c3871f93 | add command_setCombaud() / command_setMonitor() | yasokada/unity-151117-linemonitor-UI | Assets/SettingSend.cs | Assets/SettingSend.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text.RegularExpressions; // for Regex
// for UDP send
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class SettingSend : MonoBehaviour {
public const string kCommandIpAddressPrefix = "192.168.10.";
public const string kDefaultCommandPort = "7000";
public const string kDefaultComBaud = "9600";
public InputField IF_ipadr;
public InputField IF_port;
public InputField IF_combaud;
public bool s_udp_initialized = false;
UdpClient s_udp_client;
void Start () {
IF_ipadr.text = kCommandIpAddressPrefix;
IF_port.text = kDefaultCommandPort;
IF_combaud.text = kDefaultComBaud;
}
void UDP_init() {
s_udp_client = new UdpClient ();
s_udp_client.Client.ReceiveTimeout = 300; // msec
s_udp_client.Client.Blocking = false;
}
void UDP_send(string ipadr, string portStr, string text) {
int portInt = int.Parse(new Regex("[0-9]+").Match(portStr).Value); // from string to integer
byte[] data = System.Text.Encoding.ASCII.GetBytes(text); // from string to byte[]
s_udp_client.Send (data, data.Length, ipadr, portInt);
}
void command_setCombaud(string combaud) {
string cmdstr = "set,combaud," + combaud + "\r\n";
UDP_send (IF_ipadr.text, IF_port.text, cmdstr);
}
void command_setMonitor(string monip, string monport) {
string cmdstr = "set,mon," + monip + "," + monport;
UDP_send (IF_ipadr.text, IF_port.text, cmdstr);
}
public void SendButtonClick() {
if (s_udp_initialized == false) {
s_udp_initialized = true;
UDP_init ();
}
command_setMonitor (IF_ipadr.text, IF_port.text);
command_setCombaud (IF_combaud.text);
}
}
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Text.RegularExpressions; // for Regex
// for UDP send
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class SettingSend : MonoBehaviour {
public const string kCommandIpAddressPrefix = "192.168.10.";
public const string kDefaultCommandPort = "7000";
public const string kDefaultComBaud = "9600";
public InputField IF_ipadr;
public InputField IF_port;
public InputField IF_combaud;
public bool s_udp_initialized = false;
UdpClient s_udp_client;
void Start () {
IF_ipadr.text = kCommandIpAddressPrefix;
IF_port.text = kDefaultCommandPort;
IF_combaud.text = kDefaultComBaud;
}
void UDP_init() {
s_udp_client = new UdpClient ();
s_udp_client.Client.ReceiveTimeout = 300; // msec
s_udp_client.Client.Blocking = false;
}
void UDP_send(string ipadr, string portStr, string text) {
int portInt = int.Parse(new Regex("[0-9]+").Match(portStr).Value); // from string to integer
byte[] data = System.Text.Encoding.ASCII.GetBytes(text); // from string to byte[]
s_udp_client.Send (data, data.Length, ipadr, portInt);
}
public void SendButtonClick() {
if (s_udp_initialized == false) {
s_udp_initialized = true;
UDP_init ();
}
}
}
// client.Send (data, data.Length, ipadr, port);
| mit | C# |
34b9dc84a66597aa9ca3831fa1e7a5053f1376b8 | Remove many TODO items by switching to NotSupportedException | csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil | Agiil.Auth.Impl/FakeAuthenticationManager.cs | Agiil.Auth.Impl/FakeAuthenticationManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
namespace Agiil.Auth
{
public class FakeAuthenticationManager : IAuthenticationManager
{
public AuthenticationResponseChallenge AuthenticationResponseChallenge
{
get {
throw new NotSupportedException();
}
set {
throw new NotSupportedException();
}
}
public AuthenticationResponseGrant AuthenticationResponseGrant
{
get {
throw new NotSupportedException();
}
set {
throw new NotSupportedException();
}
}
public AuthenticationResponseRevoke AuthenticationResponseRevoke
{
get {
throw new NotSupportedException();
}
set {
throw new NotSupportedException();
}
}
public ClaimsPrincipal User
{
get {
throw new NotSupportedException();
}
set {
throw new NotSupportedException();
}
}
public Task<IEnumerable<AuthenticateResult>> AuthenticateAsync(string[] authenticationTypes)
{
throw new NotSupportedException();
}
public Task<AuthenticateResult> AuthenticateAsync(string authenticationType)
{
throw new NotSupportedException();
}
public void Challenge(params string[] authenticationTypes)
{
throw new NotSupportedException();
}
public void Challenge(AuthenticationProperties properties, params string[] authenticationTypes)
{
throw new NotSupportedException();
}
public IEnumerable<AuthenticationDescription> GetAuthenticationTypes()
{
throw new NotSupportedException();
}
public IEnumerable<AuthenticationDescription> GetAuthenticationTypes(Func<AuthenticationDescription, bool> predicate)
{
throw new NotSupportedException();
}
public void SignIn(params ClaimsIdentity[] identities)
{
SignIn(null, identities);
}
public void SignIn(AuthenticationProperties properties, params ClaimsIdentity[] identities)
{
System.Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(identities);
}
public void SignOut(params string[] authenticationTypes)
{
throw new NotSupportedException();
}
public void SignOut(AuthenticationProperties properties, params string[] authenticationTypes)
{
throw new NotSupportedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
namespace Agiil.Auth
{
public class FakeAuthenticationManager : IAuthenticationManager
{
public AuthenticationResponseChallenge AuthenticationResponseChallenge
{
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public AuthenticationResponseGrant AuthenticationResponseGrant
{
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public AuthenticationResponseRevoke AuthenticationResponseRevoke
{
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public ClaimsPrincipal User
{
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
public Task<IEnumerable<AuthenticateResult>> AuthenticateAsync(string[] authenticationTypes)
{
throw new NotImplementedException();
}
public Task<AuthenticateResult> AuthenticateAsync(string authenticationType)
{
throw new NotImplementedException();
}
public void Challenge(params string[] authenticationTypes)
{
throw new NotImplementedException();
}
public void Challenge(AuthenticationProperties properties, params string[] authenticationTypes)
{
throw new NotImplementedException();
}
public IEnumerable<AuthenticationDescription> GetAuthenticationTypes()
{
throw new NotImplementedException();
}
public IEnumerable<AuthenticationDescription> GetAuthenticationTypes(Func<AuthenticationDescription, bool> predicate)
{
throw new NotImplementedException();
}
public void SignIn(params ClaimsIdentity[] identities)
{
SignIn(null, identities);
}
public void SignIn(AuthenticationProperties properties, params ClaimsIdentity[] identities)
{
System.Threading.Thread.CurrentPrincipal = new ClaimsPrincipal(identities);
}
public void SignOut(params string[] authenticationTypes)
{
throw new NotImplementedException();
}
public void SignOut(AuthenticationProperties properties, params string[] authenticationTypes)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
80f3b8daf712460c4392f80756ca77ae29f0972e | Add sorting for APFT | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/APFT/List.cshtml | Battery-Commander.Web/Views/APFT/List.cshtml | @model IEnumerable<APFT>
<div class="page-header">
<h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped" id="dt">
<thead>
<tr>
<th>Soldier</th>
<th>Date</th>
<th>Score</th>
<th>Result</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var model in Model)
{
<tr>
<td>@Html.DisplayFor(_ => model.Soldier)</td>
<td>
<a href="@Url.Action("Index", new { date = model.Date })">
@Html.DisplayFor(_ => model.Date)
</a>
</td>
<td>@Html.DisplayFor(_ => model.TotalScore)</td>
<td>
@if (model.IsPassing)
{
<span class="label label-success">Passing</span>
}
else
{
<span class="label label-danger">Failure</span>
}
</td>
<td>@Html.ActionLink("Details", "Details", new { model.Id })</td>
</tr>
}
</tbody>
</table> | @model IEnumerable<APFT>
<div class="page-header">
<h1>APFT @Html.ActionLink("Add New", "New", "APFT", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<tbody>
@foreach (var model in Model)
{
<tr>
<td>@Html.DisplayFor(_ => model.Soldier)</td>
<td>
<a href="@Url.Action("Index", new { date = model.Date })">
@Html.DisplayFor(_ => model.Date)
</a>
</td>
<td>@Html.DisplayFor(_ => model.TotalScore)</td>
<td>
@if (model.IsPassing)
{
<span class="label label-success">Passing</span>
}
else
{
<span class="label label-danger">Failure</span>
}
</td>
<td>@Html.ActionLink("Details", "Details", new { model.Id })</td>
</tr>
}
</tbody>
</table> | mit | C# |
c68c729c9770e26396db3321ec587ac2c00fa01a | Add warning | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/SUTA/Edit.cshtml | Battery-Commander.Web/Views/SUTA/Edit.cshtml | @model BatteryCommander.Web.Commands.UpdateSUTARequest
<div class="alert alert-warning">
ATTENTION! Requests for HHB, 3-116 should be submitted at <a href="https://redleg.app/SUTA">https://redleg.app/SUTA</a>, NOT HERE. The form is being migrated there.
</div>
@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Supervisor)
@Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors, "-- Select the Supervisor --", new { @class = "select2 form-control" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.StartDate)
@Html.EditorFor(model => model.Body.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.EndDate)
@Html.EditorFor(model => model.Body.EndDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Reasoning)
@Html.TextAreaFor(model => model.Body.Reasoning, new { cols = "40", rows = "5" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.MitigationPlan)
@Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols = "40", rows = "5" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Archived)
@Html.EditorFor(model => model.Body.Archived, new { cols = "40", rows = "5" })
</div>
<button type="submit">Save</button>
} | @model BatteryCommander.Web.Commands.UpdateSUTARequest
@using (Html.BeginForm("Edit", "SUTA", new { Model.Id }, FormMethod.Post, true, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Supervisor)
@Html.DropDownListFor(model => model.Body.Supervisor, (IEnumerable<SelectListItem>)ViewBag.Supervisors, "-- Select the Supervisor --", new { @class = "select2 form-control" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.StartDate)
@Html.EditorFor(model => model.Body.StartDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.EndDate)
@Html.EditorFor(model => model.Body.EndDate)
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Reasoning)
@Html.TextAreaFor(model => model.Body.Reasoning, new { cols = "40", rows = "5" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.MitigationPlan)
@Html.TextAreaFor(model => model.Body.MitigationPlan, new { cols = "40", rows = "5" })
</div>
<div class="form-group form-group-lg">
@Html.DisplayNameFor(model => model.Body.Archived)
@Html.EditorFor(model => model.Body.Archived, new { cols = "40", rows = "5" })
</div>
<button type="submit">Save</button>
} | mit | C# |
920ff3a2ea067a37367af06267c9e97ab80920b8 | Apply the code fix to all valid diagnostics | Velir/Jabberwocky | Jabberwocky.Glass.CodeAnalysis/Jabberwocky.Glass.CodeAnalysis/CodeFixProvider.cs | Jabberwocky.Glass.CodeAnalysis/Jabberwocky.Glass.CodeAnalysis/CodeFixProvider.cs | using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Jabberwocky.Glass.CodeAnalysis
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(JabberwockyGlassCodeAnalysisCodeFixProvider)), Shared]
public class JabberwockyGlassCodeAnalysisCodeFixProvider : CodeFixProvider
{
private const string Title = "Make abstract";
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(GlassFactoryTypeIsAbstractAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
foreach (var diagnostic in context.Diagnostics)
{
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Find the type declaration identified by the diagnostic.
var declaration =
root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().FirstOrDefault();
// Only operate on class declarations explicitly
if (declaration == null) return;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Title,
createChangedSolution: c => MakeAbstractAsync(context.Document, declaration, c),
equivalenceKey: Title),
diagnostic);
}
}
private async Task<Solution> MakeAbstractAsync(Document document, ClassDeclarationSyntax typeDecl, CancellationToken cancellationToken)
{
var newModifiers = SyntaxFactory.TokenList(typeDecl.Modifiers.Concat(new[] { SyntaxFactory.Token(SyntaxKind.AbstractKeyword) }));
var newTypeDecl = typeDecl.WithModifiers(newModifiers);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNode(typeDecl, newTypeDecl);
var newDocument = document.WithSyntaxRoot(newRoot);
var newSolution = newDocument.Project.Solution;
// Return the new solution with the now-abstract type name.
return newSolution;
}
}
} | using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Jabberwocky.Glass.CodeAnalysis
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(JabberwockyGlassCodeAnalysisCodeFixProvider)), Shared]
public class JabberwockyGlassCodeAnalysisCodeFixProvider : CodeFixProvider
{
private const string Title = "Make abstract";
public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(GlassFactoryTypeIsAbstractAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Find the type declaration identified by the diagnostic.
var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<ClassDeclarationSyntax>().FirstOrDefault(); /* TypeDeclarationSyntax */
// Only operate on class declarations explicitly
if (declaration == null) return;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Title,
createChangedSolution: c => MakeAbstractAsync(context.Document, declaration, c),
equivalenceKey: Title),
diagnostic);
}
private async Task<Solution> MakeAbstractAsync(Document document, ClassDeclarationSyntax typeDecl, CancellationToken cancellationToken)
{
var newModifiers = SyntaxFactory.TokenList(typeDecl.Modifiers.Concat(new[] { SyntaxFactory.Token(SyntaxKind.AbstractKeyword) }));
var newTypeDecl = typeDecl.WithModifiers(newModifiers);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNode(typeDecl, newTypeDecl);
var newDocument = document.WithSyntaxRoot(newRoot);
var newSolution = newDocument.Project.Solution;
// Return the new solution with the now-uppercase type name.
return newSolution;
}
}
} | mit | C# |
9daa137c48985e2dc4ba088b0e5aa8d3bfcea8e8 | Fix to preserve SelectedValue. | cube-soft/Cube.Forms,cube-soft/Cube.Core,cube-soft/Cube.Forms,cube-soft/Cube.Core | Libraries/Extensions/ComboBoxExtension.cs | Libraries/Extensions/ComboBoxExtension.cs | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using System.Collections.Generic;
namespace Cube.Forms.Controls
{
/* --------------------------------------------------------------------- */
///
/// ComboBoxExtension
///
/// <summary>
/// System.Windows.Forms.ComboBox の拡張用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
public static class ComboBoxExtension
{
#region Methods
/* ----------------------------------------------------------------- */
///
/// Bind
///
/// <summary>
/// ComboBox オブジェクトに対してデータ・バインディングを
/// 実行します。
/// </summary>
///
/// <param name="src">ComboBox オブジェクト</param>
/// <param name="data">データ</param>
///
/* ----------------------------------------------------------------- */
public static void Bind<T>(this System.Windows.Forms.ComboBox src,
IEnumerable<KeyValuePair<string, T>> data)
{
var selected = src.SelectedValue;
src.DataSource = data;
src.DisplayMember = "Key";
src.ValueMember = "Value";
if (selected is T) src.SelectedValue = selected;
}
#endregion
}
}
| /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using System.Collections.Generic;
namespace Cube.Forms.Controls
{
/* --------------------------------------------------------------------- */
///
/// ComboBoxExtension
///
/// <summary>
/// System.Windows.Forms.ComboBox の拡張用クラスです。
/// </summary>
///
/* --------------------------------------------------------------------- */
public static class ComboBoxExtension
{
#region Methods
/* ----------------------------------------------------------------- */
///
/// Bind
///
/// <summary>
/// ComboBox オブジェクトに対してデータ・バインディングを
/// 実行します。
/// </summary>
///
/// <param name="src">ComboBox オブジェクト</param>
/// <param name="data">データ</param>
///
/* ----------------------------------------------------------------- */
public static void Bind<T>(this System.Windows.Forms.ComboBox src,
IEnumerable<KeyValuePair<string, T>> data)
{
src.DataSource = data;
src.DisplayMember = "Key";
src.ValueMember = "Value";
}
#endregion
}
}
| apache-2.0 | C# |
b6969f0c097f89c6348902f28d0613362f554059 | Remove stale remarks | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/Providers/OpenXR/Scripts/OpenXRCameraSettingsProfile.cs | Assets/MRTK/Providers/OpenXR/Scripts/OpenXRCameraSettingsProfile.cs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.CameraSystem;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.XRSDK.OpenXR
{
[CreateAssetMenu(menuName = "Mixed Reality/Toolkit/Providers/OpenXR/OpenXR Camera Settings Profile", fileName = "OpenXRCameraSettingsProfile", order = 100)]
[MixedRealityServiceProfile(typeof(OpenXRCameraSettings))]
public class OpenXRCameraSettingsProfile : BaseCameraSettingsProfile
{
[SerializeField]
[Tooltip("Specifies the default reprojection method for HoloLens 2.")]
private HolographicReprojectionMethod reprojectionMethod = HolographicReprojectionMethod.Depth;
/// <summary>
/// Specifies the default reprojection method for HoloLens 2.
/// </summary>
public HolographicReprojectionMethod ReprojectionMethod => reprojectionMethod;
}
}
| // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.MixedReality.Toolkit.CameraSystem;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.XRSDK.OpenXR
{
[CreateAssetMenu(menuName = "Mixed Reality/Toolkit/Providers/OpenXR/OpenXR Camera Settings Profile", fileName = "OpenXRCameraSettingsProfile", order = 100)]
[MixedRealityServiceProfile(typeof(OpenXRCameraSettings))]
public class OpenXRCameraSettingsProfile : BaseCameraSettingsProfile
{
[SerializeField]
[Tooltip("Specifies the default reprojection method for HoloLens 2. Note: AutoPlanar requires the DotNetWinRT adapter. DepthReprojection is the default if the adapter isn't present.")]
private HolographicReprojectionMethod reprojectionMethod = HolographicReprojectionMethod.Depth;
/// <summary>
/// Specifies the default reprojection method for HoloLens 2.
/// </summary>
/// <remarks>AutoPlanar requires the DotNetWinRT adapter. DepthReprojection is the default if the adapter isn't present.</remarks>
public HolographicReprojectionMethod ReprojectionMethod => reprojectionMethod;
}
}
| mit | C# |
4a377c23a87d13b1cd967be0f0f67519185e4f1c | make leg goal position immutable | dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo | DynamixelServo.Quadruped/LegGoalPositions.cs | DynamixelServo.Quadruped/LegGoalPositions.cs | namespace DynamixelServo.Quadruped
{
struct LegGoalPositions
{
public readonly float Coxa;
public readonly float Femur;
public readonly float Tibia;
public LegGoalPositions(float coxa, float femur, float tibia)
{
Coxa = coxa;
Femur = femur;
Tibia = tibia;
}
public override string ToString()
{
return $"Coxa: {Coxa} Femur: {Femur} Tibia: {Tibia}";
}
}
}
| namespace DynamixelServo.Quadruped
{
struct LegGoalPositions
{
public float Coxa;
public float Femur;
public float Tibia;
public LegGoalPositions(float coxa, float femur, float tibia)
{
Coxa = coxa;
Femur = femur;
Tibia = tibia;
}
public override string ToString()
{
return $"Coxa: {Coxa} Femur: {Femur} Tibia: {Tibia}";
}
}
}
| apache-2.0 | C# |
8e9a309d1f2d6c874dc50611fdbdcbae79b9bf29 | Fix BaseApiController | DimitarDKirov/Forum-Paulo-Coelho,DimitarDKirov/Forum-Paulo-Coelho,DimitarDKirov/Forum-Paulo-Coelho | Forum-Paulo-Coelho/ForumSystem.Api/Controllers/BaseApiController.cs | Forum-Paulo-Coelho/ForumSystem.Api/Controllers/BaseApiController.cs | namespace ForumSystem.Api.Controllers
{
using ForumSystem.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
public class BaseApiController : ApiController
{
protected IForumDbContext data;
public BaseApiController(IForumDbContext data)
{
this.data = data;
}
protected T PerformOperationAndHandleExceptions<T>(Func<T> operation)
{
try
{
return operation();
}
catch (Exception ex)
{
var errResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
throw new HttpResponseException(errResponse);
}
}
}
} | namespace ForumSystem.Api.Controllers
{
using ForumSystem.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
public class BaseApiController : ApiController
{
protected IForumDbContext data;
public BaseApiController(IForumDbContext data)
{
this.data = data;
}
}
} | mit | C# |
b9e7c875966352355af0beb6147b338a5c9352cc | Update assembly version | CalebChalmers/NetworkMonitor | NetworkMonitor/Properties/AssemblyInfo.cs | NetworkMonitor/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Network Monitor")]
[assembly: AssemblyDescription("A simple application designed to show you basic network data.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Caleb Chalmers")]
[assembly: AssemblyProduct("NetworkMonitor")]
[assembly: AssemblyCopyright("Copyright © Caleb Chamers 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Network Monitor")]
[assembly: AssemblyDescription("A simple application designed to show you basic network data.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Caleb Chalmers")]
[assembly: AssemblyProduct("NetworkMonitor")]
[assembly: AssemblyCopyright("Copyright © Caleb Chamers 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
fb4376b228a8bd0a50672d19b6314586e8fb8b13 | Use lowered transform value in hash computing | Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize,Romanets/RestImageResize | RestImageResize/Security/HashGenerator.cs | RestImageResize/Security/HashGenerator.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace RestImageResize.Security
{
public class HashGenerator
{
public string ComputeHash(string privateKey, int width, int height, ImageTransform transform)
{
var values = new[] { privateKey, width.ToString(), height.ToString(), transform.ToString().ToLower() };
var bytes = Encoding.ASCII.GetBytes(string.Join(":", values));
var sha1 = SHA1.Create();
sha1.ComputeHash(bytes);
return BitConverter.ToString(sha1.Hash).Replace("-", "").ToLower();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace RestImageResize.Security
{
public class HashGenerator
{
public string ComputeHash(string privateKey, int width, int height, ImageTransform transform)
{
var values = new[] { privateKey, width.ToString(), height.ToString(), transform.ToString() };
var bytes = Encoding.ASCII.GetBytes(string.Join(":", values));
var sha1 = SHA1.Create();
sha1.ComputeHash(bytes);
return BitConverter.ToString(sha1.Hash).Replace("-", "").ToLower();
}
}
} | mit | C# |
b18e735abcbe4866dbbe0ce99370c0c63005337b | Update AssemblyInfo version number to 0.1.5 | blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon,blakeohare/crayon | csharp/Crayon/Properties/AssemblyInfo.cs | csharp/Crayon/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crayon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Crayon")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c822f9b-cce6-49aa-acc5-a1a03788c983")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.5")]
[assembly: AssemblyFileVersion("0.1.5")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Crayon")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Crayon")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6c822f9b-cce6-49aa-acc5-a1a03788c983")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
37aba6ed699b4a62b7b2ec784a579a4188bb1e15 | Change panel icon to the cog | SAEnergy/Infrastructure,SAEnergy/Superstructure,SAEnergy/Infrastructure | Src/Client/Client.Admin.Plugins/Views/ComponentManagerPanel.xaml.cs | Src/Client/Client.Admin.Plugins/Views/ComponentManagerPanel.xaml.cs | using Client.Base;
using Core.Comm;
using Core.Interfaces.ServiceContracts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace Client.Admin.Plugins
{
/// <summary>
/// Interaction logic for ComponentManagerPanel.xaml
/// </summary>
[PanelMetadata(DisplayName = "Component Manager", IconPath = "images/cog.png")]
public partial class ComponentManagerPanel : PanelBase
{
public ComponentManagerPanel()
{
ViewModel = new ComponentManagerViewModel(this);
InitializeComponent();
}
}
}
| using Client.Base;
using Core.Comm;
using Core.Interfaces.ServiceContracts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace Client.Admin.Plugins
{
/// <summary>
/// Interaction logic for ComponentManagerPanel.xaml
/// </summary>
[PanelMetadata(DisplayName = "Component Manager", IconPath = "images/puzzle-piece.png")]
public partial class ComponentManagerPanel : PanelBase
{
public ComponentManagerPanel()
{
ViewModel = new ComponentManagerViewModel(this);
InitializeComponent();
}
}
}
| mit | C# |
9a7c7a0d253eb4c77b13484fb72ca8b4f1fd405e | Improve form safe name regex | kjac/FormEditor,kjac/FormEditor,kjac/FormEditor | Source/Solution/FormEditor/FieldHelper.cs | Source/Solution/FormEditor/FieldHelper.cs | using System.Text.RegularExpressions;
namespace FormEditor
{
public static class FieldHelper
{
private static readonly Regex FormSafeNameRegex = new Regex("[^a-zA-Z0-9_]", RegexOptions.Compiled);
public static string FormSafeName(string name)
{
return FormSafeNameRegex.Replace(name ?? string.Empty, "_");
}
}
} | using System.Text.RegularExpressions;
namespace FormEditor
{
public static class FieldHelper
{
private static readonly Regex FormSafeNameRegex = new Regex("[ -]", RegexOptions.Compiled);
public static string FormSafeName(string name)
{
return FormSafeNameRegex.Replace(name ?? string.Empty, "_");
}
}
} | mit | C# |
ba6d90d1cb04a4a6313a4a274976ab9d15484af9 | Fix in unit test | Fody/LoadAssembliesOnStartup | src/LoadAssembliesOnStartup.Test/AssemblyWeaver.cs | src/LoadAssembliesOnStartup.Test/AssemblyWeaver.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyWeaver.cs" company="Catel development team">
// Copyright (c) 2008 - 2013 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace LoadAssembliesOnStartup.Test
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Catel.Reflection;
using Mono.Cecil;
public static class AssemblyWeaver
{
#region Constants
public static Assembly Assembly;
public static string BeforeAssemblyPath;
public static string AfterAssemblyPath;
public static List<string> Errors = new List<string>();
#endregion
#region Constructors
static AssemblyWeaver()
{
var directory = Path.GetDirectoryName(typeof(AssemblyWeaver).GetAssemblyEx().Location);
BeforeAssemblyPath = Path.Combine(directory, "LoadAssembliesOnStartup.TestAssembly.dll");
AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
Console.WriteLine("Weaving assembly on-demand from '{0}' to '{1}'", BeforeAssemblyPath, AfterAssemblyPath);
File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);
var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath);
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AssemblyResolver = new MockAssemblyResolver(),
LogError = LogError,
};
weavingTask.Execute();
moduleDefinition.Write(AfterAssemblyPath);
Assembly = Assembly.LoadFile(AfterAssemblyPath);
}
#endregion
#region Methods
public static void Initialize()
{
}
private static void LogError(string error)
{
Errors.Add(error);
}
#endregion
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyWeaver.cs" company="Catel development team">
// Copyright (c) 2008 - 2013 Catel development team. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace LoadAssembliesOnStartup.Test
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Catel.Reflection;
using Mono.Cecil;
public static class AssemblyWeaver
{
#region Constants
public static Assembly Assembly;
public static string BeforeAssemblyPath;
public static string AfterAssemblyPath;
public static List<string> Errors = new List<string>();
#endregion
#region Constructors
static AssemblyWeaver()
{
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
BeforeAssemblyPath = Path.Combine(directory, "LoadAssembliesOnStartup.TestAssembly.dll");
AfterAssemblyPath = BeforeAssemblyPath.Replace(".dll", "2.dll");
Console.WriteLine("Weaving assembly on-demand from '{0}' to '{1}'", BeforeAssemblyPath, AfterAssemblyPath);
File.Copy(BeforeAssemblyPath, AfterAssemblyPath, true);
var moduleDefinition = ModuleDefinition.ReadModule(AfterAssemblyPath);
var weavingTask = new ModuleWeaver
{
ModuleDefinition = moduleDefinition,
AssemblyResolver = new MockAssemblyResolver(),
LogError = LogError,
};
weavingTask.Execute();
moduleDefinition.Write(AfterAssemblyPath);
Assembly = Assembly.LoadFile(AfterAssemblyPath);
}
#endregion
#region Methods
public static void Initialize()
{
}
private static void LogError(string error)
{
Errors.Add(error);
}
#endregion
}
} | mit | C# |
61da12e73b4ce0c57dc86384189cc0a9b25e390d | test teardown fix | yetanotherchris/Remy | src/Remy.Tests/Unit/Core/Tasks/TypeManagerTests.cs | src/Remy.Tests/Unit/Core/Tasks/TypeManagerTests.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Remy.Core.Tasks;
using Remy.Tests.StubsAndMocks;
using Serilog;
namespace Remy.Tests.Unit.Core.Tasks
{
[TestFixture]
public class TypeManagerTests
{
private ILogger _logger;
private string _currentDir;
private string _pluginsDirectory;
[SetUp]
public void Setup()
{
_logger = new LoggerConfiguration()
.WriteTo
.LiterateConsole()
.CreateLogger();
_currentDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
_pluginsDirectory = Path.Combine(_currentDir, "plugins");
if (Directory.Exists(_pluginsDirectory))
Directory.Delete(_pluginsDirectory, true);
Directory.CreateDirectory(_pluginsDirectory);
}
[TearDown]
public void TearDown()
{
try
{
Directory.Delete(_pluginsDirectory, true);
}
catch
{
}
}
[Test]
public void should_return_all_itasks_and_register_yamlname_for_keys()
{
// given + when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(4));
KeyValuePair<string, ITask> task = tasks.First();
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
}
[Test]
public void should_add_tasks_from_plugins_directory()
{
// given - copy MockTask (Remy.tests.dll) into plugins/
string nugetFolder = Path.Combine(_pluginsDirectory, "Remy.tests", "lib", "net461");
Directory.CreateDirectory(nugetFolder);
File.Copy(Path.Combine(_currentDir, "Remy.tests.dll"), Path.Combine(nugetFolder, "Remy.tests.dll"));
// when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(5));
KeyValuePair<string, ITask> task = tasks.FirstOrDefault(x => x.Key == "mock-task");
Assert.That(task, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Value.GetType().Name, Is.EqualTo(typeof(MockTask).Name));
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Remy.Core.Tasks;
using Remy.Tests.StubsAndMocks;
using Serilog;
namespace Remy.Tests.Unit.Core.Tasks
{
[TestFixture]
public class TypeManagerTests
{
private ILogger _logger;
private string _currentDir;
private string _pluginsDirectory;
[SetUp]
public void Setup()
{
_logger = new LoggerConfiguration()
.WriteTo
.LiterateConsole()
.CreateLogger();
_currentDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
_pluginsDirectory = Path.Combine(_currentDir, "plugins");
if (Directory.Exists(_pluginsDirectory))
Directory.Delete(_pluginsDirectory, true);
Directory.CreateDirectory(_pluginsDirectory);
}
[TearDown]
public void TearDown()
{
Directory.Delete(_pluginsDirectory, true);
}
[Test]
public void should_return_all_itasks_and_register_yamlname_for_keys()
{
// given + when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(4));
KeyValuePair<string, ITask> task = tasks.First();
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
}
[Test]
public void should_add_tasks_from_plugins_directory()
{
// given - copy MockTask (Remy.tests.dll) into plugins/
string nugetFolder = Path.Combine(_pluginsDirectory, "Remy.tests", "lib", "net461");
Directory.CreateDirectory(nugetFolder);
File.Copy(Path.Combine(_currentDir, "Remy.tests.dll"), Path.Combine(nugetFolder, "Remy.tests.dll"));
// when
Dictionary<string, ITask> tasks = TypeManager.GetRegisteredTaskInstances(_logger);
// then
Assert.That(tasks.Count, Is.EqualTo(5));
KeyValuePair<string, ITask> task = tasks.FirstOrDefault(x => x.Key == "mock-task");
Assert.That(task, Is.Not.Null);
Assert.That(task.Key, Is.EqualTo(task.Value.YamlName));
Assert.That(task.Value, Is.Not.Null);
Assert.That(task.Value.GetType().Name, Is.EqualTo(typeof(MockTask).Name));
}
}
} | mit | C# |
8fb505afa10ce1bd58faa75940f06506951ceda0 | Mark IsNullable usage with a TODO | actionshrimp/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,knocte/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Schema/TrackEndpoint/Track.cs | src/SevenDigital.Api.Schema/TrackEndpoint/Track.cs | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
using SevenDigital.Api.Schema.Pricing;
using SevenDigital.Api.Schema.ReleaseEndpoint;
namespace SevenDigital.Api.Schema.TrackEndpoint
{
[XmlRoot("track")]
[ApiEndpoint("track/details")]
[Serializable]
public class Track : HasTrackIdParameter
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("artist")]
public Artist Artist { get; set; }
[XmlElement("trackNumber")]
public int TrackNumber { get; set; }
[XmlElement("duration")]
public int Duration { get; set; }
[XmlElement("explicitContent")]
public bool ExplicitContent { get; set; }
[XmlElement("isrc")]
public string Isrc { get; set; }
[XmlElement("release")]
public Release Release { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("price")]
public Price Price { get; set; }
[XmlElement("type")]
public TrackType Type { get; set; }
[XmlElement(ElementName = "streamingReleaseDate",
//workaround for https://bugzilla.xamarin.com/show_bug.cgi?id=7613 (TODO: remove when Mono 2.12 is out)
IsNullable = true)]
public DateTime? StreamingReleaseDate { get; set; }
}
} | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.ArtistEndpoint;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
using SevenDigital.Api.Schema.Pricing;
using SevenDigital.Api.Schema.ReleaseEndpoint;
namespace SevenDigital.Api.Schema.TrackEndpoint
{
[XmlRoot("track")]
[ApiEndpoint("track/details")]
[Serializable]
public class Track : HasTrackIdParameter
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("artist")]
public Artist Artist { get; set; }
[XmlElement("trackNumber")]
public int TrackNumber { get; set; }
[XmlElement("duration")]
public int Duration { get; set; }
[XmlElement("explicitContent")]
public bool ExplicitContent { get; set; }
[XmlElement("isrc")]
public string Isrc { get; set; }
[XmlElement("release")]
public Release Release { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("price")]
public Price Price { get; set; }
[XmlElement("type")]
public TrackType Type { get; set; }
[XmlElement(ElementName = "streamingReleaseDate", IsNullable = true)]
public DateTime? StreamingReleaseDate { get; set; }
}
} | mit | C# |
0a9239cabfe7fb9a3a9c1f14d5193bb94a22602a | rename test after client no longer implements IDispose | RossLieberman/NEST,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,cstlaurent/elasticsearch-net,CSGOpenSource/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,elastic/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net | src/Tests/ClientConcepts/LowLevel/Lifetimes.doc.cs | src/Tests/ClientConcepts/LowLevel/Lifetimes.doc.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Threading.Tasks;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Newtonsoft.Json;
using Tests.Framework;
namespace Tests.ClientConcepts.LowLevel
{
public class Lifetimes
{
/**
* ## Lifetimes
*
* If you are using an IOC container its always useful to know the best practices around the lifetime of your objects
* In general we advise folks to register their ElasticClient instances as singleton. The client is thread safe
* so sharing this instance over threads is ok.
* Zooming in however the actual moving part that benefits the most of being static for most of the duration of your
* application is ConnectionSettings. Caches are per ConnectionSettings.
* In some applications it could make perfect sense to have multiple singleton IElasticClient's registered with different
* connectionsettings. e.g if you have 2 functionally isolated Elasticsearch clusters.
*/
[U] public void InitialDisposeState()
{
var connection = new AConnection();
var connectionPool = new AConnectionPool(new Uri("http://localhost:9200"));
var settings = new AConnectionSettings(connectionPool, connection);
settings.IsDisposed.Should().BeFalse();
connectionPool.IsDisposed.Should().BeFalse();
connection.IsDisposed.Should().BeFalse();
}
/**
* Disposing the ConnectionSettings will dispose the IConnectionPool and IConnection it has a hold of
*/
[U] public void DisposingSettingsDisposesMovingParts()
{
var connection = new AConnection();
var connectionPool = new AConnectionPool(new Uri("http://localhost:9200"));
var settings = new AConnectionSettings(connectionPool, connection);
using (settings) { }
settings.IsDisposed.Should().BeTrue();
connectionPool.IsDisposed.Should().BeTrue();
connection.IsDisposed.Should().BeTrue();
}
class AConnectionPool : SingleNodeConnectionPool
{
public AConnectionPool(Uri uri, IDateTimeProvider dateTimeProvider = null) : base(uri, dateTimeProvider) { }
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
class AConnectionSettings : ConnectionSettings
{
public AConnectionSettings(IConnectionPool pool, IConnection connection)
: base(pool, connection) { }
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
class AConnection : InMemoryConnection
{
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Threading.Tasks;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Newtonsoft.Json;
using Tests.Framework;
namespace Tests.ClientConcepts.LowLevel
{
public class Lifetimes
{
/**
* ## Lifetimes
*
* If you are using an IOC container its always useful to know the best practices around the lifetime of your objects
* In general we advise folks to register their ElasticClient instances as singleton. The client is thread safe
* so sharing this instance over threads is ok.
* Zooming in however the actual moving part that benefits the most of being static for most of the duration of your
* application is ConnectionSettings. Caches are per ConnectionSettings.
* In some applications it could make perfect sense to have multiple singleton IElasticClient's registered with different
* connectionsettings. e.g if you have 2 functionally isolated Elasticsearch clusters.
*/
[U] public void DisposingClientDoesNotDisposeMovingParts()
{
var connection = new AConnection();
var connectionPool = new AConnectionPool(new Uri("http://localhost:9200"));
var settings = new AConnectionSettings(connectionPool, connection);
settings.IsDisposed.Should().BeFalse();
connectionPool.IsDisposed.Should().BeFalse();
connection.IsDisposed.Should().BeFalse();
}
/**
* Disposing the ConnectionSettings will dispose the IConnectionPool and IConnection it has a hold of
*/
[U] public void DisposingSettingsDisposesMovingParts()
{
var connection = new AConnection();
var connectionPool = new AConnectionPool(new Uri("http://localhost:9200"));
var settings = new AConnectionSettings(connectionPool, connection);
using (settings) { }
settings.IsDisposed.Should().BeTrue();
connectionPool.IsDisposed.Should().BeTrue();
connection.IsDisposed.Should().BeTrue();
}
class AConnectionPool : SingleNodeConnectionPool
{
public AConnectionPool(Uri uri, IDateTimeProvider dateTimeProvider = null) : base(uri, dateTimeProvider) { }
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
class AConnectionSettings : ConnectionSettings
{
public AConnectionSettings(IConnectionPool pool, IConnection connection)
: base(pool, connection) { }
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
class AConnection : InMemoryConnection
{
public bool IsDisposed { get; private set; }
protected override void DisposeManagedResources()
{
this.IsDisposed = true;
base.DisposeManagedResources();
}
}
}
}
| apache-2.0 | C# |
89a4f255da916630f1fe4a6497acfadae0ce4023 | remove GetState | acple/ParsecSharp | ParsecSharp/Parser/Internal/Builder.cs | ParsecSharp/Parser/Internal/Builder.cs | using System;
using System.Runtime.CompilerServices;
namespace ParsecSharp.Internal
{
public static class Builder
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Create<TToken, T>(Func<IParsecStateStream<TToken>, Result<TToken, T>> function)
=> new Single<TToken, T>(function);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> ModifyResult<TToken, T, TResult>(this Parser<TToken, T> parser, Func<IParsecStateStream<TToken>, Fail<TToken, T>, Result<TToken, TResult>> fail, Func<IParsecStateStream<TToken>, Success<TToken, T>, Result<TToken, TResult>> success)
=> new ModifyResult<TToken, T, TResult>(parser, fail, success);
}
}
| using System;
using System.Runtime.CompilerServices;
namespace ParsecSharp.Internal
{
public static class Builder
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, T> Create<TToken, T>(Func<IParsecStateStream<TToken>, Result<TToken, T>> function)
=> new Single<TToken, T>(function);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, TResult> ModifyResult<TToken, T, TResult>(this Parser<TToken, T> parser, Func<IParsecStateStream<TToken>, Fail<TToken, T>, Result<TToken, TResult>> fail, Func<IParsecStateStream<TToken>, Success<TToken, T>, Result<TToken, TResult>> success)
=> new ModifyResult<TToken, T, TResult>(parser, fail, success);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Parser<TToken, IParsecStateStream<TToken>> GetState<TToken>()
=> Create<TToken, IParsecStateStream<TToken>>(state => Result.Success(state, state));
}
}
| mit | C# |
739e87c5ab1afec58d012c797a97553ac281c99c | Add one decimal place to MB/GB/TB in the table in the Attachments tab | chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker | app/Desktop/Common/BytesValueConverter.cs | app/Desktop/Common/BytesValueConverter.cs | using System;
using System.Globalization;
using Avalonia.Data.Converters;
namespace DHT.Desktop.Common {
sealed class BytesValueConverter : IValueConverter {
private sealed class Unit {
private readonly string label;
private readonly string numberFormat;
public Unit(string label, int decimalPlaces) {
this.label = label;
this.numberFormat = "{0:n" + decimalPlaces + "}";
}
public string Format(double size) {
return string.Format(Program.Culture, numberFormat, size) + " " + label;
}
}
private static readonly Unit[] Units = {
new ("B", decimalPlaces: 0),
new ("kB", decimalPlaces: 0),
new ("MB", decimalPlaces: 1),
new ("GB", decimalPlaces: 1),
new ("TB", decimalPlaces: 1)
};
private const int Scale = 1000;
private static string Convert(ulong size) {
int power = size == 0L ? 0 : (int) Math.Log(size, Scale);
int unit = power >= Units.Length ? Units.Length - 1 : power;
return Units[unit].Format(unit == 0 ? size : size / Math.Pow(Scale, unit));
}
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is long size and >= 0L) {
return Convert((ulong) size);
}
else if (value is ulong usize) {
return Convert(usize);
}
else {
return "-";
}
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
throw new NotSupportedException();
}
}
}
| using System;
using System.Globalization;
using Avalonia.Data.Converters;
namespace DHT.Desktop.Common {
sealed class BytesValueConverter : IValueConverter {
private static readonly string[] Units = {
"B",
"kB",
"MB",
"GB",
"TB"
};
private const int Scale = 1000;
private static string Convert(ulong size) {
int power = size == 0L ? 0 : (int) Math.Log(size, Scale);
int unit = power >= Units.Length ? Units.Length - 1 : power;
if (unit == 0) {
return string.Format(Program.Culture, "{0:n0}", size) + " " + Units[unit];
}
else {
double humanReadableSize = size / Math.Pow(Scale, unit);
return string.Format(Program.Culture, "{0:n0}", humanReadableSize) + " " + Units[unit];
}
}
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) {
if (value is long size and >= 0L) {
return Convert((ulong) size);
}
else if (value is ulong usize) {
return Convert(usize);
}
else {
return "-";
}
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) {
throw new NotSupportedException();
}
}
}
| mit | C# |
e8c768638c3cb0c348606ea39ef381df2e8d52ed | Fix XML comments | henkmollema/Jwt.NET,henkmollema/Jwt.NET | src/JsonWebTokens/JwtHashAlgorithm.cs | src/JsonWebTokens/JwtHashAlgorithm.cs | namespace Jwt
{
/// <summary>
/// Specifies the hashing algorithm being used used.
/// </summary>
public enum JwtHashAlgorithm
{
/// <summary>
/// Hash-based Message Authentication Code (HMAC) using SHA256.
/// </summary>
HS256,
/// <summary>
/// Hash-based Message Authentication Code (HMAC) using SHA384.
/// </summary>
HS384,
/// <summary>
/// Hash-based Message Authentication Code (HMAC) using SHA512.
/// </summary>
HS512
}
}
| namespace Jwt
{
/// <summary>
/// Represents the hashing algorithm being used used.
/// </summary>
public enum JwtHashAlgorithm
{
/// <summary>
/// Hash-based Message Authentication Code (HMAC) using SHA256.
/// </summary>
HS256,
/// <summary>
/// Hash-based Message Authentication Code (HMAC) using SHA256.
/// </summary>
HS384,
/// <summary>
/// Hash-based Message Authentication Code (HMAC) using SHA256.
/// </summary>
HS512
}
} | mit | C# |
0e12ae4cb2452e81e6a25868554168540a06ff55 | Improve performance of puzzle 10 | martincostello/project-euler | src/ProjectEuler/Puzzles/Puzzle010.cs | src/ProjectEuler/Puzzles/Puzzle010.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
long sum = ParallelEnumerable.Range(3, max - 3)
.Where((p) => p % 2 != 0)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
Answer = sum + 2;
return 0;
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System;
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=10</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle010 : Puzzle
{
/// <inheritdoc />
public override string Question => "Find the sum of all the primes below the specified value.";
/// <inheritdoc />
protected override int MinimumArguments => 1;
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
int max;
if (!TryParseInt32(args[0], out max) || max < 2)
{
Console.Error.WriteLine("The specified number is invalid.");
return -1;
}
Answer = ParallelEnumerable.Range(2, max - 2)
.Where((p) => Maths.IsPrime(p))
.Select((p) => (long)p)
.Sum();
return 0;
}
}
}
| apache-2.0 | C# |
f3df4c5ba8b4d7610a047f49628265c6190056b7 | add pet skill to passivities | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Data/Databases/PassivityDatabase.cs | TCC.Core/Data/Databases/PassivityDatabase.cs | using System.Collections.Generic;
using TCC.Data.Skills;
using TeraDataLite;
namespace TCC.Data.Databases
{
public static class PassivityDatabase
{
//TODO: maybe move this to a TeraData tsv file (or merge in hotdot.tsv)
public static Dictionary<uint, uint> Passivities { get; } = new Dictionary<uint, uint>
{
{6001,60}, {6002,60}, {6003,60}, {6004,60}, // dragon
{6012,60}, {6013,60}, // phoenix
{6017,60}, {6018,60}, // drake
{60029,120}, {60030,120}, { 60031,120}, { 60032,120}, //concentration
{15162,60}, // insigna of the punisher
// bracing force
{13000, 180},{13001, 180},{13002, 180},
{13003, 180},{13004, 180},{13005, 180},
{13006, 180},{13007, 180},{13008, 180},
{13009, 180},{13010, 180},{13011, 180},
{13012, 180},{13013, 180},{13014, 180},
{13015, 180},{13016, 180},{13017, 180},
{13018, 180},{13019, 180},{13020, 180},
{13021, 180},{13022, 180},{13023, 180},
{13024, 180},{13025, 180},{13026, 180},
{13027, 180},{13028, 180},{13029, 180},
{13030, 180},{13031, 180},{13032, 180},
{13033, 180},{13034, 180},{13035, 180},
{13036, 180},{13037, 180},
};
public static bool TryGetPassivitySkill(uint id, out Skill sk)
{
var result = false;
sk = new Skill(0, Class.None, string.Empty, string.Empty);
if (!Game.DB.AbnormalityDatabase.Abnormalities.TryGetValue(id, out var ab)) return result;
result = true;
sk = new Skill(id, Class.Common, ab.Name, "") { IconName = ab.IconName };
return result;
}
}
}
| using System.Collections.Generic;
using TCC.Data.Skills;
using TeraDataLite;
namespace TCC.Data.Databases
{
public static class PassivityDatabase
{
//TODO: maybe move this to a TeraData tsv file (or merge in hotdot.tsv)
public static Dictionary<uint, uint> Passivities { get; } = new Dictionary<uint, uint>
{
{6001,60}, {6002,60}, {6003,60}, {6004,60}, // dragon
{6012,60}, {6013,60}, // phoenix
{6017,60}, {6018,60}, // drake
{60029,120}, {60030,120}, { 60031,120}, { 60032,120}, //concentration
{15162,60} // insigna of the punisher
};
public static bool TryGetPassivitySkill(uint id, out Skill sk)
{
var result = false;
sk = new Skill(0, Class.None, string.Empty, string.Empty);
if (Game.DB.AbnormalityDatabase.Abnormalities.TryGetValue(id, out var ab))
{
result = true;
sk = new Skill(id, Class.Common, ab.Name, "") { IconName = ab.IconName };
}
return result;
}
}
}
| mit | C# |
d506831d8406a3bff20810399f1b4b0115abe106 | Update to hello support example. | awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples | dotnetv3/Support/Actions/HelloSupport.cs | dotnetv3/Support/Actions/HelloSupport.cs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.AWSSupport;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace SupportActions;
/// <summary>
/// Hello AWS Support example.
/// </summary>
public static class HelloSupport
{
static async Task Main(string[] args)
{
// snippet-start:[Support.dotnetv3.HelloSupport]
// Use the AWS .NET Core Setup package to set up dependency injection for the AWS Support service.
// Use your AWS profile name, or leave it blank to use the default profile.
// You must have a Business, Enterprise On-Ramp, or Enterprise Support subscription, or an exception will be thrown.
using var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
services.AddAWSService<IAmazonAWSSupport>()
).Build();
// For this example, get the client from the host after setup.
var supportClient = host.Services.GetRequiredService<IAmazonAWSSupport>();
var response = await supportClient.DescribeServicesAsync();
Console.WriteLine($"\tHello AWS Support! There are {response.Services.Count} services available.");
// snippet-end:[Support.dotnetv3.HelloSupport]
}
}
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.AWSSupport;
using Amazon.Extensions.NETCore.Setup;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
namespace SupportActions;
// snippet-start:[Support.dotnetv3.HelloSupport]
/// <summary>
/// Hello AWS Support example.
/// </summary>
public static class HelloSupport
{
static async Task Main(string[] args)
{
// Set up dependency injection for the AWS Support service.
// Use your AWS profile name, or leave it blank to use the default profile.
using var host = Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
logging.AddFilter("System", LogLevel.Debug)
.AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
.AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
.ConfigureServices((_, services) =>
services.AddAWSService<IAmazonAWSSupport>()
.AddTransient<SupportWrapper>()
)
.Build();
var logger = LoggerFactory.Create(builder =>
{
builder.AddConsole();
}).CreateLogger(typeof(HelloSupport));
var supportWrapper = host.Services.GetRequiredService<SupportWrapper>();
Console.WriteLine(new string('-', 80));
Console.WriteLine("Welcome to the AWS Support Hello Support example.");
Console.WriteLine(new string('-', 80));
try
{
var apiSupported = await supportWrapper.VerifySubscription();
if (!apiSupported)
{
logger.LogError("You must have a Business, Enterprise On-Ramp, or Enterprise Support " +
"plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these examples.");
return;
}
var services = await supportWrapper.DescribeServices();
Console.WriteLine($"AWS Support client returned {services.Count} services.");
Console.WriteLine(new string('-', 80));
Console.WriteLine("Hello Support example is complete.");
Console.WriteLine(new string('-', 80));
}
catch (Exception ex)
{
logger.LogError(ex, "There was a problem executing the scenario.");
}
}
}
// snippet-end:[Support.dotnetv3.HelloSupport] | apache-2.0 | C# |
542f598d9b4772e6f3f330bda5ccbc1255f69bd4 | Write the DOCTYPE and use two-space indentation | openmedicus/dbus-sharp,Tragetaschen/dbus-sharp,openmedicus/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,arfbtwn/dbus-sharp,arfbtwn/dbus-sharp | src/Introspection.cs | src/Introspection.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Text;
namespace NDesk.DBus
{
//TODO: complete this class
public class Introspector
{
const string NAMESPACE = "http://www.freedesktop.org/standards/dbus";
const string PUBLIC_IDENTIFIER = "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN";
const string SYSTEM_IDENTIFIER = "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd";
public string xml;
public Type target_type;
public void HandleIntrospect ()
{
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
settings.IndentChars = (" ");
settings.OmitXmlDeclaration = true;
StringBuilder sb = new StringBuilder ();
XmlWriter writer;
writer = XmlWriter.Create (sb, settings);
writer.WriteDocType ("node", PUBLIC_IDENTIFIER, SYSTEM_IDENTIFIER, null);
writer.WriteStartElement ("node");
writer.WriteStartElement ("interface");
writer.WriteAttributeString ("name", "org.freedesktop.DBus.Introspectable");
writer.WriteStartElement ("method");
writer.WriteAttributeString ("name", "Introspect");
writer.WriteStartElement ("arg");
writer.WriteAttributeString ("name", "data");
writer.WriteAttributeString ("direction", "out");
writer.WriteAttributeString ("type", "s");
writer.WriteEndElement ();
writer.WriteEndElement ();
writer.WriteEndElement ();
writer.WriteEndElement ();
writer.Flush ();
xml = sb.ToString ();
}
}
}
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Text;
namespace NDesk.DBus
{
//TODO: complete this class
public class Introspector
{
public string xml;
public Type target_type;
public void HandleIntrospect ()
{
XmlWriterSettings settings = new XmlWriterSettings ();
settings.Indent = true;
settings.IndentChars = ("\t");
settings.OmitXmlDeclaration = true;
StringBuilder sb = new StringBuilder ();
XmlWriter writer;
//TODO: doctype
writer = XmlWriter.Create (sb, settings);
writer.WriteStartElement ("node");
writer.WriteStartElement ("interface");
writer.WriteAttributeString ("name", "org.freedesktop.DBus.Introspectable");
writer.WriteStartElement ("method");
writer.WriteAttributeString ("name", "Introspect");
writer.WriteStartElement ("arg");
writer.WriteAttributeString ("name", "data");
writer.WriteAttributeString ("direction", "out");
writer.WriteAttributeString ("type", "s");
writer.WriteEndElement ();
writer.WriteEndElement ();
writer.WriteEndElement ();
writer.WriteEndElement ();
writer.Flush ();
xml = sb.ToString ();
}
}
}
| mit | C# |
6d94953fc13a95f121448651aba901ac52483eca | remove unused method | kcummings/kgrep,kcummings/kgrep | src/ReplaceTokens.cs | src/ReplaceTokens.cs | using System.Collections.Generic;
using System.Text.RegularExpressions;
using NLog;
namespace kgrep {
public class ReplaceTokens : IFileAction {
protected static Logger logger = LogManager.GetCurrentClassLogger();
public IHandleOutput sw = new WriteStdout();
protected int _countOfMatchesInFile = 0;
protected int _lineNumber = 0;
private Command _command;
private readonly Pickup _pickup;
public ReplaceTokens() {
_pickup = new Pickup();
}
public virtual string ApplyCommands(ParseCommandFile rf, List<string> inputFilenames) {
return "";
}
protected string ApplySingleCommand(string line, Command command) {
_command = command;
_pickup.CollectAllPickupsInLine(line, command);
line = ReplaceIt(command.SubjectString, line, _pickup.ReplacePickupsWithStoredValue(command.ReplacementString));
return line;
}
private string ReplaceIt(Regex re, string source, string target) {
int count = re.Matches(source).Count;
if (count>0) {
logger.Debug(" At line {0} found {1} occurances of '{2}' in '{3}'", _lineNumber, count, re.ToString(), source);
_countOfMatchesInFile += count;
return re.Replace(source, target);
}
return source;
}
protected bool isCandidateForReplacement(string line, Command command) {
// Has a matching AnchorString?
if (command.AnchorString.Length > 0) {
if (Regex.IsMatch(line, command.AnchorString))
return true;
logger.Trace(" is not a Command candidate");
return false;
}
return true;
}
}
}
| using System.Collections.Generic;
using System.Text.RegularExpressions;
using NLog;
namespace kgrep {
public class ReplaceTokens : IFileAction {
protected static Logger logger = LogManager.GetCurrentClassLogger();
public IHandleOutput sw = new WriteStdout();
protected int _countOfMatchesInFile = 0;
protected int _lineNumber = 0;
private Command _command;
private readonly Pickup _pickup;
public ReplaceTokens() {
_pickup = new Pickup();
}
public virtual string ApplyCommands(ParseCommandFile rf, List<string> inputFilenames) {
return "";
}
protected string ApplySingleCommand(string line, Command command) {
_command = command;
_pickup.CollectAllPickupsInLine(line, command);
line = ReplaceIt(command.SubjectString, line, _pickup.ReplacePickupsWithStoredValue(command.ReplacementString));
return line;
}
private string ReplacePickupsInReplacementString(string repString) {
if (_command.IsPickupInReplacementString) {
return _pickup.ReplacePickupsWithStoredValue(repString);
}
return repString;
}
private string ReplaceIt(Regex re, string source, string target) {
int count = re.Matches(source).Count;
if (count>0) {
logger.Debug(" At line {0} found {1} occurances of '{2}' in '{3}'", _lineNumber, count, re.ToString(), source);
_countOfMatchesInFile += count;
return re.Replace(source, target);
}
return source;
}
protected bool isCandidateForReplacement(string line, Command command) {
// Has a matching AnchorString?
if (command.AnchorString.Length > 0) {
if (Regex.IsMatch(line, command.AnchorString))
return true;
logger.Trace(" is not a Command candidate");
return false;
}
return true;
}
}
}
| mit | C# |
f92436b9c2f6bd9d1f067e95c1539dc795523dc0 | Remove fullanme tooltip | leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net | Joinrpg/Views/Shared/DisplayTemplates/User.cshtml | Joinrpg/Views/Shared/DisplayTemplates/User.cshtml | @model JoinRpg.DataModel.User
@if (Model == null)
{
<span>нет</span>
return;
}
<span style="font-weight: bold">
<nobr><a href="@Url.Action("Details", "User", new {Model.UserId})"><span class="glyphicon glyphicon-user"></span>@Model.DisplayName.Trim()</a></nobr>
</span> | @model JoinRpg.DataModel.User
@if (Model == null)
{
<span>нет</span>
return;
}
<span style="font-weight: bold">
<nobr><a href="@Url.Action("Details", "User", new {Model.UserId})" title="@Model.FullName"><span class="glyphicon glyphicon-user"></span>@Model.DisplayName.Trim()</a></nobr>
</span> | mit | C# |
3bf5df5c7e6e4ad710e73949145e3477c98f637d | Update copyright version | SonarSource-VisualStudio/sonarlint-visualstudio | src/AssemblyInfo.Shared.cs | src/AssemblyInfo.Shared.cs | /*
* SonarLint for Visual Studio
* Copyright (C) 2016-2017 SonarSource SA and Microsoft Corporation
* mailto: contact AT sonarsource DOT com
*
* Licensed under the MIT License.
* See LICENSE file in the project root for full license information.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// Note: keep the version numbers in sync with the VSIX (source.extension.manifest)
[assembly: AssemblyVersion("2.9.0")]
[assembly: AssemblyFileVersion("2.9.0.0")] // This should exactly match the VSIX version
[assembly: AssemblyInformationalVersion("Version:2.9.0.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: ComVisible(false)]
[assembly: AssemblyProduct("SonarLint for Visual Studio")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource SA and Microsoft Corporation 2016-2017")]
[assembly: AssemblyTrademark("")]
| /*
* SonarLint for Visual Studio
* Copyright (C) 2016-2017 SonarSource SA and Microsoft Corporation
* mailto: contact AT sonarsource DOT com
*
* Licensed under the MIT License.
* See LICENSE file in the project root for full license information.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System.Reflection;
using System.Runtime.InteropServices;
// Note: keep the version numbers in sync with the VSIX (source.extension.manifest)
[assembly: AssemblyVersion("2.9.0")]
[assembly: AssemblyFileVersion("2.9.0.0")] // This should exactly match the VSIX version
[assembly: AssemblyInformationalVersion("Version:2.9.0.0 Branch:not-set Sha1:not-set")]
[assembly: AssemblyConfiguration("")]
[assembly: ComVisible(false)]
[assembly: AssemblyProduct("SonarLint for Visual Studio")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCompany("SonarSource and Microsoft")]
[assembly: AssemblyCopyright("Copyright © SonarSource SA and Microsoft Corporation 2016")]
[assembly: AssemblyTrademark("")] | mit | C# |
4ca01f491aea6bd621fc80cad41e50854b142a90 | fix test | khipu/lib-dotnet | unittest/Khipu/HtmlHelperTest.cs | unittest/Khipu/HtmlHelperTest.cs | using System;
using NUnit.Framework;
using Khipu.Api;
using Rhino.Mocks;
using System.IO;
namespace unittest
{
[TestFixture ()]
public class HtmlHelperTest
{
HtmlHelper endPoint;
[TestFixtureSetUp]
public void PreTestInitialize ()
{
endPoint = MockRepository.GeneratePartialMock<HtmlHelper> ("1234", "123456");
}
[Test()]
public void CreatePaymentForm(){
string form = endPoint.CreatePaymentForm (new System.Collections.Generic.Dictionary<string, object> {
{"subject","Un cobro desde .Net"},
{"body", "El cuerpo del cobro"},
{"amount","1000"},
{"email", "john.doe@gmail.com"}
});
Console.Out.WriteLine (form);
Assert.IsNotNull (form);
}
}
}
| using System;
using NUnit.Framework;
using Khipu.Api;
using Rhino.Mocks;
using System.IO;
namespace unittest
{
[TestFixture ()]
public class HtmlHelperTest
{
HtmlHelper endPoint;
[TestFixtureSetUp]
public void PreTestInitialize ()
{
endPoint = MockRepository.GeneratePartialMock<HtmlHelper> ("1234", "123456");
}
[Test()]
public void CreatePaymentForm(){
string form = endPoint.CreatePaymentForm (new System.Collections.Generic.Dictionary<string, object> {
{"subject","Un cobro desde .Net"},
{"body", "El cuerpo del cobro"},
{"amount","1000"},
{"email", "john.doe@gmail.com"}
});
Console.Out.WriteLine (form);
Assert.IsNotNull (form);
using (StreamWriter file = new StreamWriter ("/home/alvaro/form.html")) {
file.Write (form);
}
}
}
}
| bsd-3-clause | C# |
a386548439d2ff054f23bf3ef8c5f5359509a031 | Add alt tags to image, add download links. | dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch,dsteinweg/TeacherPouch | TeacherPouch.Web/Views/Photos/PhotoDetails.cshtml | TeacherPouch.Web/Views/Photos/PhotoDetails.cshtml | @model PhotoDetailsViewModel
@{
ViewBag.Title = "Photo Details";
}
<div id="photoDetails">
<header>
<h1>@Model.Photo.Name</h1>
</header>
<table class="photo-details-tbl">
<tr>
<td class="prev-arrow-cell">
@if (Model.PreviousPhoto != null)
{
<a href="@Url.PhotoDetails(Model.PreviousPhoto, Model.SearchResultTag)"><</a>
}
</td>
<td class="photo-cell">
@Html.LargePhoto(Model.Photo, Model.PhotoTags)
<div>
@{ Html.RenderPartial(MVC.Tags.Views._TagButtons, Model.PhotoTags); }
</div>
</td>
<td class="next-arrow-cell">
@if (Model.NextPhoto != null)
{
<a href="@Url.PhotoDetails(Model.NextPhoto, Model.SearchResultTag)">></a>
}
</td>
</tr>
</table>
<div id="download">
Download this photo:
<span class="download-link"><a href="@Url.PhotoDownloadUrl(Model.Photo, PhotoSizes.Small)"><i class="icon-download-alt"></i>Small</a> <span class="file-size">(@Model.SmallFileSize)</span></span> |
<span class="download-link"><a href="@Url.PhotoDownloadUrl(Model.Photo, PhotoSizes.Large)"><i class="icon-download-alt"></i>Large</a> <span class="file-size">(@Model.LargeFileSize)</span></span>
</div>
@if (SecurityHelper.UserCanSeePrivateRecords(base.User))
{
<div>
@if (Model.Photo.IsPrivate)
{
<span>Is Private: <strong>Yes</strong></span>
}
else
{
<span>Is Private: No</span>
}
</div>
}
@if (SecurityHelper.UserIsAdmin(base.User))
{
<div>
<a href="@Url.PhotoEdit(Model.Photo)">Edit</a> |
<a href="@Url.PhotoDelete(Model.Photo)">Delete</a> |
<a href="@Url.PhotoIndex()">Photo index</a>
</div>
}
</div>
| @model PhotoDetailsViewModel
@{
ViewBag.Title = "Photo Details";
}
<div id="photoDetails">
<header>
<h1>@Model.Photo.Name</h1>
</header>
<table class="photo-details-tbl">
<tr>
<td class="prev-arrow-cell">
@if (Model.PreviousPhoto != null)
{
<a href="@Url.PhotoDetails(Model.PreviousPhoto, Model.SearchResultTag)"><</a>
}
</td>
<td class="photo-cell">
@Html.LargePhoto(Model.Photo)
<div>
@{ Html.RenderPartial(MVC.Tags.Views._TagButtons, Model.PhotoTags); }
</div>
</td>
<td class="next-arrow-cell">
@if (Model.NextPhoto != null)
{
<a href="@Url.PhotoDetails(Model.NextPhoto, Model.SearchResultTag)">></a>
}
</td>
</tr>
</table>
@if (SecurityHelper.UserCanSeePrivateRecords(base.User))
{
<div>
@if (Model.Photo.IsPrivate)
{
<span>Is Private: <strong>Yes</strong></span>
}
else
{
<span>Is Private: No</span>
}
</div>
}
@if (SecurityHelper.UserIsAdmin(base.User))
{
<div>
<a href="@Url.PhotoEdit(Model.Photo)">Edit</a> |
<a href="@Url.PhotoDelete(Model.Photo)">Delete</a> |
<a href="@Url.PhotoIndex()">Photo index</a>
</div>
}
</div>
| mit | C# |
87a626f495707429e07fb2b3ef942c2b17fd8556 | Update ReferenceCacheManager.cs | PowerMogli/Rabbit.Db | src/Micro+/Caching/ReferenceCacheManager.cs | src/Micro+/Caching/ReferenceCacheManager.cs | using System;
using MicroORM.Entity;
namespace MicroORM.Caching
{
internal static class ReferenceCacheManager
{
private static readonly object _lock = new object();
private static EntityInfoReferenceCache<object> _referenceCache = new EntityInfoReferenceCache<object>();
internal static EntityInfo GetEntityInfo<TEntity>(TEntity entity)
{
EntityInfo entityInfo;
lock (_lock)
{
if (_referenceCache == null)
return null;
entityInfo = _referenceCache.Get(entity);
}
if (entityInfo == null)
entityInfo = SetEntityInfo<TEntity>(entity, new EntityInfo());
return entityInfo;
}
internal static EntityInfo SetEntityInfo<TEntity>(TEntity entity, EntityInfo entityInfo)
{
lock (_lock)
{
if (_referenceCache == null)
return null;
if (_referenceCache.Get(entity) == null)
_referenceCache.Add(entity, entityInfo);
else
_referenceCache.Update(entity, entityInfo);
}
return entityInfo;
}
internal static void Dispose()
{
lock (_lock) { _referenceCache.Dispose(); }
}
}
}
| using System;
using MicroORM.Entity;
namespace MicroORM.Caching
{
internal static class ReferenceCacheManager
{
private static readonly object _lock = new object();
private static EntityInfoReferenceCache<object> _referenceCache = new EntityInfoReferenceCache<object>();
internal static EntityInfo GetEntityInfo<TEntity>(TEntity entity)
{
EntityInfo entityInfo;
lock (_lock)
{
if (_referenceCache == null)
return null;
entityInfo = _referenceCache.Get(entity);
}
if (entityInfo == null)
entityInfo = SetEntityInfo<TEntity>(entity, new EntityInfo());
return entityInfo;
}
internal static EntityInfo SetEntityInfo<TEntity>(TEntity entity, EntityInfo entityInfo)
{
lock (_lock)
{
if (_referenceCache == null)
return null;
if (_referenceCache.Get(entity) == null)
_referenceCache.Add(entity, entityInfo);
else
_referenceCache.Update(entity, entityInfo);
}
return entityInfo;
}
internal static void Dispose()
{
lock (_lock) { _referenceCache.Dispose(); }
}
}
}
| apache-2.0 | C# |
dc1556e8b3153d4dd6b4d4bf9b7992097218b3b5 | Tidy up BindingPaths a bit | jamesqo/Sirloin | src/Sirloin.DesignerSupport/BindingPaths.cs | src/Sirloin.DesignerSupport/BindingPaths.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Typed.Xaml;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Sirloin.Internal
{
public sealed class BindingPaths
{
private BindingPaths()
{
throw new InvalidOperationException("This class shouldn't be instantiated.");
}
// Content
public static readonly DependencyProperty ContentProperty =
Dependency.RegisterAttached<string, ContentControl, BindingPaths>("Content", ContentChanged);
public static string GetContent(DependencyObject obj) => obj.Get<string>(ContentProperty);
public static void SetContent(DependencyObject obj, string value) => obj.Set(ContentProperty, value);
private static void ContentChanged(ContentControl control, IPropertyChangedArgs<string> args)
{
control.SetBinding(ContentControl.ContentProperty, args.NewValue);
}
// Height
public static readonly DependencyProperty HeightProperty =
Dependency.RegisterAttached<string, FrameworkElement, BindingPaths>("Height", HeightChanged);
public static string GetHeight(DependencyObject obj) => obj.Get<string>(HeightProperty);
public static void SetHeight(DependencyObject obj, string value) => obj.Set(HeightProperty, value);
private static void HeightChanged(FrameworkElement element, IPropertyChangedArgs<string> args)
{
element.SetBinding(FrameworkElement.HeightProperty, args.NewValue);
}
// Width
public static readonly DependencyProperty WidthProperty =
Dependency.RegisterAttached<string, FrameworkElement, BindingPaths>("Width", WidthChanged);
public static string GetWidth(DependencyObject obj) => obj.Get<string>(WidthProperty);
public static void SetWidth(DependencyObject obj, string value) => obj.Set(WidthProperty, value);
private static void WidthChanged(FrameworkElement element, IPropertyChangedArgs<string> args)
{
element.SetBinding(FrameworkElement.WidthProperty, args.NewValue);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Typed.Xaml;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace Sirloin.Internal
{
public sealed class BindingPaths
{
private BindingPaths()
{
throw new InvalidOperationException("This class shouldn't be instantiated.");
}
// Content
public static readonly DependencyProperty ContentProperty =
Dependency.RegisterAttached<string, ContentControl, BindingPaths>("Content", ContentChanged);
public static string GetContent(DependencyObject o) =>
o.Get<string>(ContentProperty);
public static void SetContent(DependencyObject o, string value) =>
o.Set(ContentProperty, value);
private static void ContentChanged(ContentControl o, IPropertyChangedArgs<string> args) =>
o.SetBinding(ContentControl.ContentProperty, args.NewValue);
// Height
public static readonly DependencyProperty HeightProperty =
Dependency.RegisterAttached<string, FrameworkElement, BindingPaths>("Height", HeightChanged);
public static string GetHeight(DependencyObject o) =>
o.Get<string>(HeightProperty);
public static void SetHeight(DependencyObject o, string value) =>
o.Set(HeightProperty, value);
private static void HeightChanged(FrameworkElement o, IPropertyChangedArgs<string> args) =>
o.SetBinding(FrameworkElement.HeightProperty, args.NewValue);
// Width
public static readonly DependencyProperty WidthProperty =
Dependency.RegisterAttached<string, FrameworkElement, BindingPaths>("Width", WidthChanged);
public static string GetWidth(DependencyObject o) =>
o.Get<string>(WidthProperty);
public static void SetWidth(DependencyObject o, string value) =>
o.Set(WidthProperty, value);
private static void WidthChanged(FrameworkElement o, IPropertyChangedArgs<string> args) =>
o.SetBinding(FrameworkElement.WidthProperty, args.NewValue);
}
}
| bsd-2-clause | C# |
3613751426b06c361931aebdce9ae27a277eaa67 | add conversation window private var | octoblu/meshblu-connector-skype,octoblu/meshblu-connector-skype | src/csharp/join-meeting.cs | src/csharp/join-meeting.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.Sharing;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
private ConversationWindow conversationWindow = null;
public async Task<object> Invoke(string JoinUrl)
{
Automation automation = LyncClient.GetAutomation();
var Client = LyncClient.GetClient();
JoinUrl = JoinUrl + '?';
var state = new Object();
IAsyncResult ar = automation.BeginStartConversation(JoinUrl, 0, (result) => { }, state);
conversationWindow = automation.EndStartConversation(ar);
conversationId = conversationWindow.Conversation.Properties[ConversationProperty.Id].ToString();
return conversationId;
}
public void HandleStateChange(object Sender, ConversationStateChangedEventArgs e)
{
if(e.NewState.ToString() == "Active"){
Thread.Sleep(3000);
conversationWindow.ShowContent();
conversationWindow.ShowFullScreen(0);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.Sharing;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
public async Task<object> Invoke(string JoinUrl)
{
Automation automation = LyncClient.GetAutomation();
var Client = LyncClient.GetClient();
JoinUrl = JoinUrl + '?';
var state = new Object();
IAsyncResult ar = automation.BeginStartConversation(JoinUrl, 0, (result) => { }, state);
conversationWindow = automation.EndStartConversation(ar);
conversation = conversationWindow.Conversation;
conversationId = conversationWindow.Conversation.Properties[ConversationProperty.Id].ToString();
return conversationId;
}
public void HandleStateChange(object Sender, ConversationStateChangedEventArgs e)
{
if(e.NewState.ToString() == "Active"){
Thread.Sleep(3000);
conversationWindow.ShowContent();
conversationWindow.ShowFullScreen(0);
}
}
}
| mit | C# |
10f9b522f2cfd724750fcaa1b7e91ebbf8ec8b74 | Consolidate ButtonFactory - AboutWindow | larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,larsbrubaker/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl | AboutPage/AboutWindow.cs | AboutPage/AboutWindow.cs | /*
Copyright (c) 2017, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
namespace MatterHackers.MatterControl
{
public class AboutWindow : SystemWindow
{
private static AboutWindow aboutWindow = null;
public AboutWindow(TextImageButtonFactory textImageButtonFactory)
: base(500, 640)
{
GuiWidget aboutPage = new AboutWidget();
aboutPage.AnchorAll();
this.AddChild(aboutPage);
Button cancelButton = textImageButtonFactory.Generate("Close".Localize());
cancelButton.Click += (s, e) =>
{
UiThread.RunOnIdle(aboutWindow.Close);
};
cancelButton.HAnchor = HAnchor.ParentRight;
this.AddChild(cancelButton);
this.Title = "About MatterControl".Localize();
this.AlwaysOnTopOfMain = true;
this.ShowAsSystemWindow();
}
public static void Show()
{
if (aboutWindow == null)
{
aboutWindow = new AboutWindow(ApplicationController.Instance.Theme.textImageButtonFactory);
aboutWindow.Closed += (parentSender, e) =>
{
aboutWindow = null;
};
}
else
{
aboutWindow.BringToFront();
}
}
}
} | /*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using MatterHackers.Agg;
using MatterHackers.Agg.Font;
using MatterHackers.Agg.Image;
using MatterHackers.Agg.PlatformAbstract;
using MatterHackers.Agg.UI;
using MatterHackers.Localizations;
using MatterHackers.MatterControl.ContactForm;
using MatterHackers.MatterControl.CustomWidgets;
using MatterHackers.MatterControl.HtmlParsing;
using MatterHackers.MatterControl.PrintLibrary;
using MatterHackers.MatterControl.PrintQueue;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
namespace MatterHackers.MatterControl
{
public class AboutWindow : SystemWindow
{
private static AboutWindow aboutWindow = null;
private TextImageButtonFactory textImageButtonFactory = new TextImageButtonFactory();
public AboutWindow()
: base(500, 640)
{
GuiWidget aboutPage = new AboutWidget();
aboutPage.AnchorAll();
this.AddChild(aboutPage);
Button cancelButton = textImageButtonFactory.Generate("Close".Localize());
cancelButton.Click += (s, e) => CancelButton_Click();
cancelButton.HAnchor = HAnchor.ParentRight;
this.AddChild(cancelButton);
this.Title = "About MatterControl".Localize();
this.AlwaysOnTopOfMain = true;
this.ShowAsSystemWindow();
}
public static void Show()
{
if (aboutWindow == null)
{
aboutWindow = new AboutWindow();
aboutWindow.Closed += (parentSender, e) =>
{
aboutWindow = null;
};
}
else
{
aboutWindow.BringToFront();
}
}
private void CancelButton_Click()
{
UiThread.RunOnIdle(aboutWindow.Close);
}
}
} | bsd-2-clause | C# |
bef565592df5a8bd0b7368e188a125af2e5a7bf2 | Remove unused code | cloudfoundry-incubator/garden-windows,stefanschneider/garden-windows,cloudfoundry-incubator/garden-windows,stefanschneider/garden-windows,cloudfoundry/garden-windows,stefanschneider/garden-windows,cloudfoundry-incubator/garden-windows,cloudfoundry/garden-windows,cloudfoundry/garden-windows | Containerizer/Program.cs | Containerizer/Program.cs | using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Owin.WebSocket;
using Owin.WebSocket.Extensions;
using System.Threading.Tasks;
namespace Containerizer
{
public class Program
{
static void Main(string[] args)
{
// Start OWIN host
try
{
using (WebApp.Start<Startup>("http://*:" + args[0] + "/"))
{
Console.WriteLine("SUCCESS: started");
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync("http://localhost:" + args[0] + "/api/ping").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine("Hit a key");
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine("ERRROR: " + ex.Message);
}
}
}
} | using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using Owin.WebSocket;
using Owin.WebSocket.Extensions;
using System.Threading.Tasks;
namespace Containerizer
{
public class Program
{
public class WS : WebSocketConnection
{
public override Task OnMessageReceived(ArraySegment<byte> message, WebSocketMessageType type)
{
Console.WriteLine(message);
return SendText(message, true);
}
}
static void Main2(string[] args)
{
WebApp.Start(new StartOptions("http://localhost:8989"), startup =>
{
startup.MapWebSocketPattern<WS>("/captures/(?<capture1>.+)/(?<capture2>.+)");
});
var client = new ClientWebSocket();
client.ConnectAsync(new Uri("ws://localhost:8989/captures/fred/james"), CancellationToken.None).Wait();
client.SendAsync(new ArraySegment<byte>(new UTF8Encoding(true).GetBytes("foo")), WebSocketMessageType.Text, true, CancellationToken.None).Wait();
Console.ReadLine();
}
static void Main(string[] args)
{
// Start OWIN host
try
{
using (WebApp.Start<Startup>("http://*:" + args[0] + "/"))
{
Console.WriteLine("SUCCESS: started");
// Create HttpCient and make a request to api/values
HttpClient client = new HttpClient();
var response = client.GetAsync("http://localhost:" + args[0] + "/api/ping").Result;
Console.WriteLine(response);
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
Console.WriteLine("Hit a key");
Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine("ERRROR: " + ex.Message);
}
}
}
} | apache-2.0 | C# |
fad86b09e5734f1c384a0ee075acf3a79be23aaa | change default view service templates folder to 'templates' | kouweizhong/IdentityServer3,wondertrap/IdentityServer3,wondertrap/IdentityServer3,chicoribas/IdentityServer3,jackswei/IdentityServer3,mvalipour/IdentityServer3,mvalipour/IdentityServer3,roflkins/IdentityServer3,delRyan/IdentityServer3,EternalXw/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,delRyan/IdentityServer3,tbitowner/IdentityServer3,tonyeung/IdentityServer3,tuyndv/IdentityServer3,chicoribas/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,EternalXw/IdentityServer3,bestwpw/IdentityServer3,charoco/IdentityServer3,mvalipour/IdentityServer3,delloncba/IdentityServer3,SonOfSam/IdentityServer3,ryanvgates/IdentityServer3,openbizgit/IdentityServer3,charoco/IdentityServer3,18098924759/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,Agrando/IdentityServer3,IdentityServer/IdentityServer3,olohmann/IdentityServer3,jackswei/IdentityServer3,uoko-J-Go/IdentityServer,SonOfSam/IdentityServer3,roflkins/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,uoko-J-Go/IdentityServer,IdentityServer/IdentityServer3,delloncba/IdentityServer3,IdentityServer/IdentityServer3,olohmann/IdentityServer3,faithword/IdentityServer3,ryanvgates/IdentityServer3,bestwpw/IdentityServer3,kouweizhong/IdentityServer3,olohmann/IdentityServer3,bodell/IdentityServer3,bestwpw/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,ryanvgates/IdentityServer3,18098924759/IdentityServer3,tbitowner/IdentityServer3,18098924759/IdentityServer3,openbizgit/IdentityServer3,Agrando/IdentityServer3,bodell/IdentityServer3,faithword/IdentityServer3,Agrando/IdentityServer3,codeice/IdentityServer3,tuyndv/IdentityServer3,tuyndv/IdentityServer3,tbitowner/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,faithword/IdentityServer3,codeice/IdentityServer3,jackswei/IdentityServer3,delloncba/IdentityServer3,EternalXw/IdentityServer3,roflkins/IdentityServer3,tonyeung/IdentityServer3,wondertrap/IdentityServer3,delRyan/IdentityServer3,uoko-J-Go/IdentityServer,bodell/IdentityServer3,SonOfSam/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,feanz/Thinktecture.IdentityServer.v3,kouweizhong/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,openbizgit/IdentityServer3,charoco/IdentityServer3,tonyeung/IdentityServer3,codeice/IdentityServer3 | source/Core/Services/DefaultViewService/FileSystemWithEmbeddedFallbackViewLoader.cs | source/Core/Services/DefaultViewService/FileSystemWithEmbeddedFallbackViewLoader.cs | /*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* 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.IO;
using System.Threading.Tasks;
namespace IdentityServer3.Core.Services.Default
{
/// <summary>
/// View loader implementation that uses a combination of the file system view loader
/// and the embedded assets view loader. This allows for some templates to be defined
/// via the file system, while using the embedded assets templates for all others.
/// </summary>
public class FileSystemWithEmbeddedFallbackViewLoader : IViewLoader
{
readonly FileSystemViewLoader file;
readonly EmbeddedAssetsViewLoader embedded;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
public FileSystemWithEmbeddedFallbackViewLoader()
: this(GetDefaultDirectory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
/// <param name="directory">The directory.</param>
public FileSystemWithEmbeddedFallbackViewLoader(string directory)
{
this.file = new FileSystemViewLoader(directory);
this.embedded = new EmbeddedAssetsViewLoader();
}
static string GetDefaultDirectory()
{
var path = AppDomain.CurrentDomain.BaseDirectory;
path = Path.Combine(path, "templates");
return path;
}
/// <summary>
/// Loads the HTML for the named view.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public async Task<string> LoadAsync(string name)
{
var value = await file.LoadAsync(name);
if (value == null)
{
value = await embedded.LoadAsync(name);
}
return value;
}
}
}
| /*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* 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.IO;
using System.Threading.Tasks;
namespace IdentityServer3.Core.Services.Default
{
/// <summary>
/// View loader implementation that uses a combination of the file system view loader
/// and the embedded assets view loader. This allows for some templates to be defined
/// via the file system, while using the embedded assets templates for all others.
/// </summary>
public class FileSystemWithEmbeddedFallbackViewLoader : IViewLoader
{
readonly FileSystemViewLoader file;
readonly EmbeddedAssetsViewLoader embedded;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
public FileSystemWithEmbeddedFallbackViewLoader()
: this(GetDefaultDirectory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
/// <param name="directory">The directory.</param>
public FileSystemWithEmbeddedFallbackViewLoader(string directory)
{
this.file = new FileSystemViewLoader(directory);
this.embedded = new EmbeddedAssetsViewLoader();
}
static string GetDefaultDirectory()
{
var path = AppDomain.CurrentDomain.BaseDirectory;
path = Path.Combine(path, "views");
return path;
}
/// <summary>
/// Loads the HTML for the named view.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public async Task<string> LoadAsync(string name)
{
var value = await file.LoadAsync(name);
if (value == null)
{
value = await embedded.LoadAsync(name);
}
return value;
}
}
}
| apache-2.0 | C# |
527b52f5cec6a3cb5f4f4e0185ec8881cd46916b | Fix unit tests. | Eusth/IPA | IPA.Tests/ProgramTest.cs | IPA.Tests/ProgramTest.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace IPA.Tests
{
public class ProgramTest
{
[Theory]
// Unrelated path
[InlineData("test/from.dll", "test/to.dll", "native", false, new string[] { "test/to.dll" })]
// Flat -> Not-Flat
[InlineData("native/from.dll", "native/to.dll", "native", false, new string[] { "native/x86/to.dll", "native/x86_64/to.dll" })]
// Flat -> Flat
[InlineData("native/from.dll", "native/to.dll", "native", true, new string[] { "native/to.dll" })]
// Not-Flat -> Flat
[InlineData("native/x86/from.dll", "native/x86/to.dll", "native", true, new string[] { })]
[InlineData("native/x86_64/from.dll", "native/x86_64/to.dll", "native", true, new string[] { "native/to.dll" })]
// Not-flat -> Not-Flat
[InlineData("native/x86/from.dll", "native/x86/to.dll", "native", false, new string[] { "native/x86/to.dll" })]
[InlineData("native/x86_64/from.dll", "native/x86_64/to.dll", "native", false, new string[] { "native/x86_64/to.dll" })]
public void CopiesCorrectly(string from, string to, string nativeFolder, bool isFlat, string[] expected)
{
var outcome = Program.NativePluginInterceptor(new FileInfo(from), new FileInfo(to), new DirectoryInfo(nativeFolder), isFlat, Program.Architecture.Unknown).Select(f => f.FullName).ToList();
var expectedPaths = expected.Select(e => new FileInfo(e)).Select(f => f.FullName).ToList();
Assert.Equal(expectedPaths, outcome);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace IPA.Tests
{
public class ProgramTest
{
[Theory]
// Unrelated path
[InlineData("test/from.dll", "test/to.dll", "native", false, new string[] { "test/to.dll" })]
// Flat -> Not-Flat
[InlineData("native/from.dll", "native/to.dll", "native", false, new string[] { "native/x86/to.dll", "native/x86_64/to.dll" })]
// Flat -> Flat
[InlineData("native/from.dll", "native/to.dll", "native", true, new string[] { "native/to.dll" })]
// Not-Flat -> Flat
[InlineData("native/x86/from.dll", "native/x86/to.dll", "native", true, new string[] { })]
[InlineData("native/x86_64/from.dll", "native/x86_64/to.dll", "native", true, new string[] { "native/to.dll" })]
// Not-flat -> Not-Flat
[InlineData("native/x86/from.dll", "native/x86/to.dll", "native", false, new string[] { "native/x86/to.dll" })]
[InlineData("native/x86_64/from.dll", "native/x86_64/to.dll", "native", false, new string[] { "native/x86_64/to.dll" })]
public void CopiesCorrectly(string from, string to, string nativeFolder, bool isFlat, string[] expected)
{
var outcome = Program.NativePluginInterceptor(new FileInfo(from), new FileInfo(to), new DirectoryInfo(nativeFolder), isFlat).Select(f => f.FullName).ToList();
var expectedPaths = expected.Select(e => new FileInfo(e)).Select(f => f.FullName).ToList();
Assert.Equal(expectedPaths, outcome);
}
}
}
| mit | C# |
4c8fe9b05a30a8eeacdba923920f23d6a582c59e | add Env modified: Dragon/Source/Symbols.cs | Mooophy/cs143,Mooophy/cs143,Mooophy/cs143,Mooophy/cs143,Mooophy/cs143 | Dragon/Source/Symbols.cs | Dragon/Source/Symbols.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dragon
{
public class Env
{
private Dictionary<Token, Id> _table;
protected Env _prev;
public Env(Env prev)
{
_table = new Dictionary<Token, Id>();
_prev = prev;
}
public void Add(Token tok, Id id)
{
_table.Add(tok, id);
}
public Id Get(Token tok)
{
for(var env = this; env != null; env = env._prev)
if (_table.Keys.Contains(tok)) return _table[tok];
return null;
}
}
public class Type : Word
{
public int Width;
public Type(string typeName, char tag, int width)
: base(typeName, tag)
{
this.Width = width;
}
public readonly static Type
Int = new Type("int", Tag.BASIC, 4),
Float = new Type("float", Tag.BASIC, 8),
Char = new Type("char", Tag.BASIC, 1),
Bool = new Type("bool", Tag.BASIC, 1);
public static bool Numeric(Type type)
{
return type == Type.Char || type == Type.Int || type == Type.Float;
}
public static Type Max(Type lhs, Type rhs)
{
if (!Type.Numeric(lhs) || !Type.Numeric(rhs))
return null;
else if (lhs == Type.Float || rhs == Type.Float)
return Type.Float;
else if (lhs == Type.Int || rhs == Type.Int)
return Type.Int;
else
return Type.Char;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dragon
{
public class Type : Word
{
public int Width;
public Type(string typeName, char tag, int width)
: base(typeName, tag)
{
this.Width = width;
}
public readonly static Type
Int = new Type("int", Tag.BASIC, 4),
Float = new Type("float", Tag.BASIC, 8),
Char = new Type("char", Tag.BASIC, 1),
Bool = new Type("bool", Tag.BASIC, 1);
public static bool Numeric(Type type)
{
return type == Type.Char || type == Type.Int || type == Type.Float;
}
public static Type Max(Type lhs, Type rhs)
{
if (!Type.Numeric(lhs) || !Type.Numeric(rhs))
return null;
else if (lhs == Type.Float || rhs == Type.Float)
return Type.Float;
else if (lhs == Type.Int || rhs == Type.Int)
return Type.Int;
else
return Type.Char;
}
}
}
| mit | C# |
4ada2a912e159fc3b165d4f41201633b1593bee5 | bump verison | mstyura/Anotar,distantcam/Anotar,modulexcite/Anotar,Fody/Anotar | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Anotar")]
[assembly: AssemblyProduct("Anotar")]
[assembly: AssemblyVersion("0.13.0.0")]
[assembly: AssemblyFileVersion("0.13.0.0")]
| mit | C# |
1cabcca0ff03818e972cf9f70dc65a3c09cb8c15 | Add comments to PersonalInfoDto. | harrison314/MapperPerformace | MapperPerformace/Testing/PersonInfoDto.cs | MapperPerformace/Testing/PersonInfoDto.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapperPerformace.Testing
{
/// <summary>
/// Dto represents <see cref="MapperPerformace.Ef.Person"/>.
/// </summary>
public class PersonInfoDto
{
public int BusinessEntityID
{
get;
set;
}
public string PersonType
{
get;
set;
}
public string Title
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public DateTime? EmployeeBrithDate
{
get;
set;
}
public string EmployeeGender
{
get;
set;
}
/// <summary>
/// Initializes a new instance of the <see cref="PersonInfoDto"/> class.
/// </summary>
public PersonInfoDto()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MapperPerformace.Testing
{
/// <summary>
/// POCO class for short personal informations.
/// </summary>
public class PersonInfoDto
{
public int BusinessEntityID
{
get;
set;
}
public string PersonType
{
get;
set;
}
public string Title
{
get;
set;
}
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public DateTime? EmployeeBrithDate
{
get;
set;
}
public string EmployeeGender
{
get;
set;
}
public PersonInfoDto()
{
}
}
}
| mit | C# |
9893da92ac50226235547f2c3823e9a60d9520da | Make consistent and add a comment for clarification | ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing | Purchasing.Mvc/Views/Order/_Submit.cshtml | Purchasing.Mvc/Views/Order/_Submit.cshtml | @model OrderModifyModel
@{
var submitMap = new Dictionary<string, string> {{"Request", "Create"}, {"Edit", "Save"}, {"Copy", "Save"}};
var submitText = submitMap[ViewBag.Title];
var submitTitle = ViewBag.Title == "Copy" ? "Save this order which was duplicated from an existing order" : string.Empty;
}
<section id="order-submit-section">
<div class="section-contents">
@if (!string.IsNullOrWhiteSpace(Model.Workgroup.Disclaimer))
{
<div class="section-text">
<p><strong>Disclaimer: </strong>@Model.Workgroup.Disclaimer</p>
</div>
}
<ul>
<li><div class="editor-label"> </div>
<div class="editor-field">
<input type="submit" class="button order-submit" value="@submitText" title="@submitTitle"/>
|
@if (submitText == "Create")
{
<input type="button" class="button" value="Save For Later" id="save-btn"/> <text>|</text>
}
@Html.ActionLink("Cancel", "Landing", "Home", new {}, new {id="order-cancel"}) @*This id is an element so the local storage gets cleared out. It is not a route value.*@
</div>
</li>
</ul>
</div>
| @model OrderModifyModel
@{
var submitMap = new Dictionary<string, string> {{"Request", "Create"}, {"Edit", "Save"}, {"Copy", "Save"}};
var submitText = submitMap[ViewBag.Title];
var submitTitle = ViewBag.Title == "Copy" ? "Save this order which was duplicated from an existing order" : string.Empty;
}
<section id="order-submit-section">
<div class="section-contents">
@if (!string.IsNullOrWhiteSpace(Model.Workgroup.Disclaimer))
{
<div class="section-text">
<p><strong>Disclaimer: </strong>@Model.Workgroup.Disclaimer</p>
</div>
}
<ul>
<li><div class="editor-label"> </div>
<div class="editor-field">
<input type="submit" class="button order-submit" value="@submitText" title="@submitTitle"/>
|
@if (submitText == "Create")
{
<input type="button" class="button" value="Save For Later" id="save-btn"/> <text>|</text>
}
@Html.ActionLink("Cancel", "Landing", "Home", null, new {id="order-cancel"})
</div>
</li>
</ul>
</div>
| mit | C# |
c85c6d1199607fbc73534e151460aa668a1f9ffd | Update new-blog.cshtml | mishrsud/sudhanshutheone.com,mishrsud/sudhanshutheone.com,mishrsud/sudhanshutheone.com,daveaglick/daveaglick,daveaglick/daveaglick | Somedave/Views/Blog/Posts/new-blog.cshtml | Somedave/Views/Blog/Posts/new-blog.cshtml | @{
Title = "New Blog";
Lead = "Look, Ma, no database!";
Published = new DateTime(2014, 9, 2);
Tags = new[] { "blog", "meta" };
}
<p>It's been a little while coming, but I'm finally launching my new blog. It's built from scratch in ASP.NET MVC. Why go to all the trouble to build a blog engine from scratch when there are a gazillion great engines already out there? That's a very good question, let's break it down.</p>
<h1>Own Your Content</h1>
<p>I'll thank Scott Hanselman for really driving this point home.</p>
<p>So that's <em>why</em> I created this new blog, but what about <em>how</em>? This blog engine uses no database, makes it easy to mix content pages with blog articles, is hosted on GitHub, and uses continuous deployment to automatically publish to an Azure Website.</p>
| @{
Title = "New Blog";
Lead = "Look, Ma, no database!";
//Published = new DateTime(2014, 9, 4);
Tags = new[] { "blog", "meta" };
}
<p>It's been a little while coming, but I'm finally launching my new blog. It's built from scratch in ASP.NET MVC. Why go to all the trouble to build a blog engine from scratch when there are a gazillion great engines already out there? That's a very good question, let's break it down.</p>
<h1>Own Your Content</h1>
<p>I'll thank Scott Hanselman for really driving this point home.</p>
<p>So that's <em>why</em> I created this new blog, but what about <em>how</em>? This blog engine uses no database, makes it easy to mix content pages with blog articles, is hosted on GitHub, and uses continuous deployment to automatically publish to an Azure Website.</p>
| mit | C# |
eefa1e41c4bcff5924abb6420f2c9d4a656f2251 | Stop testing Message property in UnchangedParametersInError(). | PenguinF/sandra-three | SysExtensions/Tests/JsonErrorInfoTests.cs | SysExtensions/Tests/JsonErrorInfoTests.cs | #region License
/*********************************************************************************
* JsonErrorInfoTests.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
#endregion
using SysExtensions.Text.Json;
using System;
using Xunit;
namespace SysExtensions.Tests
{
public class JsonErrorInfoTests
{
[Theory]
[InlineData(-1, 0, "start")]
[InlineData(-1, -1, "start")]
[InlineData(0, -1, "length")]
public void OutOfRangeArgumentsInError(int start, int length, string parameterName)
{
Assert.Throws<ArgumentOutOfRangeException>(parameterName, () => new JsonErrorInfo(JsonErrorCode.Unspecified, start, length));
}
[Theory]
[InlineData(JsonErrorCode.Unspecified, 0, 0)]
[InlineData(JsonErrorCode.Custom, 0, 1)]
[InlineData(JsonErrorCode.ExpectedEof, 1, 0)]
[InlineData(JsonErrorCode.Custom + 999, 0, 2)]
public void UnchangedParametersInError(JsonErrorCode errorCode, int start, int length)
{
var errorInfo = new JsonErrorInfo(errorCode, start, length);
Assert.Equal(errorCode, errorInfo.ErrorCode);
Assert.Equal(start, errorInfo.Start);
Assert.Equal(length, errorInfo.Length);
}
}
}
| #region License
/*********************************************************************************
* JsonErrorInfoTests.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
#endregion
using SysExtensions.Text.Json;
using System;
using Xunit;
namespace SysExtensions.Tests
{
public class JsonErrorInfoTests
{
[Theory]
[InlineData(-1, 0, "start")]
[InlineData(-1, -1, "start")]
[InlineData(0, -1, "length")]
public void OutOfRangeArgumentsInError(int start, int length, string parameterName)
{
Assert.Throws<ArgumentOutOfRangeException>(parameterName, () => new JsonErrorInfo(JsonErrorCode.Unspecified, start, length));
}
[Theory]
[InlineData(JsonErrorCode.Unspecified, "", 0, 0)]
[InlineData(JsonErrorCode.Custom, "Error!", 0, 1)]
// No newline conversions.
[InlineData(JsonErrorCode.ExpectedEof, "\n", 1, 0)]
[InlineData(JsonErrorCode.Custom + 999, "Error!\r\n", 0, 2)]
public void UnchangedParametersInError(JsonErrorCode errorCode, string message, int start, int length)
{
var errorInfo = new JsonErrorInfo(errorCode, message, start, length);
Assert.Equal(errorCode, errorInfo.ErrorCode);
Assert.Equal(message, errorInfo.Message);
Assert.Equal(start, errorInfo.Start);
Assert.Equal(length, errorInfo.Length);
}
}
}
| apache-2.0 | C# |
afdf9eabe605ac314c54fc7855da2461dacbd252 | fix non-passing unit test. | ParagonTruss/UnitClassLibrary | UnitClassLibrary/Force/ForceConversion.cs | UnitClassLibrary/Force/ForceConversion.cs | using System;
namespace UnitClassLibrary
{
public partial class Force
{
/// <summary>Converts one unit of Force to another</summary>
/// <param name="typeConvertingTo">input unit type</param>
/// <param name="passedValue"></param>
/// <param name="typeConvertingFrom">desired output unit type</param>
/// <returns>passedValue in desired units</returns>
public static double ConvertForce(ForceType typeConvertingFrom, double passedValue, ForceType typeConvertingTo)
{
double returnDouble = 0.0;
switch (typeConvertingFrom)
{
case ForceType.Newton:
switch (typeConvertingTo)
{
case ForceType.Newton:
returnDouble = passedValue; // Return passed in Newton
break;
case ForceType.Pound:
returnDouble = passedValue * (1/4.44822162); // Convert Newton to Pound
break;
case ForceType.Kip:
returnDouble = passedValue * (1/4448.2216); // Convert Newton to Kip
break;
}
break;
case ForceType.Pound:
switch (typeConvertingTo)
{
case ForceType.Newton:
returnDouble = passedValue * 4.44822162; // Convert Pound to Newton
break;
case ForceType.Pound:
returnDouble = passedValue; // Return passed in Pound
break;
case ForceType.Kip:
returnDouble = passedValue * (1.0/1000.0); // Convert Pound to Kip
break;
}
break;
case ForceType.Kip:
switch (typeConvertingTo)
{
case ForceType.Newton:
returnDouble = passedValue * 4448.2216; // Convert Kip to Newton
break;
case ForceType.Pound:
returnDouble = passedValue * 1000; // Convert Kip to Pound
break;
case ForceType.Kip:
returnDouble = passedValue; // Return passed in Kip
break;
}
break;
}
return returnDouble;
}
}
} | using System;
namespace UnitClassLibrary
{
public partial class Force
{
/// <summary>Converts one unit of Force to another</summary>
/// <param name="typeConvertingTo">input unit type</param>
/// <param name="passedValue"></param>
/// <param name="typeConvertingFrom">desired output unit type</param>
/// <returns>passedValue in desired units</returns>
public static double ConvertForce(ForceType typeConvertingFrom, double passedValue, ForceType typeConvertingTo)
{
double returnDouble = 0.0;
switch (typeConvertingFrom)
{
case ForceType.Newton:
switch (typeConvertingTo)
{
case ForceType.Newton:
returnDouble = passedValue; // Return passed in Newton
break;
case ForceType.Pound:
returnDouble = passedValue * (1/4.44822162); // Convert Newton to Pound
break;
case ForceType.Kip:
returnDouble = passedValue * (1/4448.2216); // Convert Newton to Kip
break;
}
break;
case ForceType.Pound:
switch (typeConvertingTo)
{
case ForceType.Newton:
returnDouble = passedValue * 4.44822162; // Convert Pound to Newton
break;
case ForceType.Pound:
returnDouble = passedValue; // Return passed in Pound
break;
case ForceType.Kip:
returnDouble = passedValue * (1/1000); // Convert Pound to Kip
break;
}
break;
case ForceType.Kip:
switch (typeConvertingTo)
{
case ForceType.Newton:
returnDouble = passedValue * 4448.2216; // Convert Kip to Newton
break;
case ForceType.Pound:
returnDouble = passedValue * 1000; // Convert Kip to Pound
break;
case ForceType.Kip:
returnDouble = passedValue; // Return passed in Kip
break;
}
break;
}
return returnDouble;
}
}
} | lgpl-2.1 | C# |
ae3662c392b6670dcfbdd63b9bf850e2f024d6ff | Remove nameof operator because it caused a build error in AppHarbor | nelsonwellswku/Yahtzee,nelsonwellswku/Yahtzee,nelsonwellswku/Yahtzee | Website/Security/EnforceHttpsAttribute.cs | Website/Security/EnforceHttpsAttribute.cs | using System;
using System.Web.Mvc;
namespace Website.Security
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EnforceHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if(filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
if(string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if(filterContext.HttpContext.Request.IsLocal)
{
return;
}
HandleNonHttpsRequest(filterContext);
}
}
} | using System;
using System.Web.Mvc;
namespace Website.Security
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EnforceHttpsAttribute : RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
}
if(filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
if(string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
"https",
StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if(filterContext.HttpContext.Request.IsLocal)
{
return;
}
HandleNonHttpsRequest(filterContext);
}
}
} | mit | C# |
a3136065406748f4e34a048783f5ccf061ef8100 | Change test settings default Redis Db | jdehlin/CacheSleeve,MonoSoftware/CacheSleeve | CacheSleeve.Tests/TestSettings.cs | CacheSleeve.Tests/TestSettings.cs | using System.Collections.Generic;
using CacheSleeve.Tests.TestObjects;
namespace CacheSleeve.Tests
{
public static class TestSettings
{
public static string RedisHost = "localhost";
public static int RedisPort = 6379;
public static string RedisPassword = null;
public static int RedisDb = 5;
public static string KeyPrefix = "cs.";
// don't mess with George.. you'll break a lot of tests
public static Monkey George = new Monkey("George") { Bananas = new List<Banana> { new Banana(4, "yellow") }};
}
} | using System.Collections.Generic;
using CacheSleeve.Tests.TestObjects;
namespace CacheSleeve.Tests
{
public static class TestSettings
{
public static string RedisHost = "localhost";
public static int RedisPort = 6379;
public static string RedisPassword = null;
public static int RedisDb = 0;
public static string KeyPrefix = "cs.";
// don't mess with George.. you'll break a lot of tests
public static Monkey George = new Monkey("George") { Bananas = new List<Banana> { new Banana(4, "yellow") }};
}
} | apache-2.0 | C# |
b0e2806be46e5ea88800d48fd5bb505586d0bb21 | use file name as the parameter for controller | Mooophy/158212 | as4/TextAnalysis/TextAnalysis/MainForm.cs | as4/TextAnalysis/TextAnalysis/MainForm.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows;
using System.IO;
namespace TextAnalysis
{
public partial class MainForm : Form
{
List<string> Data = new List<string>();
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// this experiment suggests that string should be the interface between UI and Controller
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var sr = new StreamReader(openFileDialog.FileName))
{
string[] content = sr.ReadLine().Split(' ');
Data.AddRange(content);
foreach (var str in Data) MessageBox.Show(str);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows;
using System.IO;
namespace TextAnalysis
{
public partial class MainForm : Form
{
List<string> Data;
public MainForm()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
//Stream fs = null;
try
{
using (var sr = new StreamReader(openFileDialog.FileName))
{
string[] content = sr.ReadToEnd().Split('\n');
MessageBox.Show(content[0]);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
}
| mit | C# |
d99b2b64d3452ad40b585a9816ac29f19b41d31f | Fix too close neighbors | creepylava/RotMG-Dungeon-Generator | DungeonGenerator/RoomCollision.cs | DungeonGenerator/RoomCollision.cs | /*
Copyright (C) 2015 creepylava
This file is part of RotMG Dungeon Generator.
RotMG Dungeon Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using DungeonGenerator.Dungeon;
using RotMG.Common;
using RotMG.Common.Rasterizer;
namespace DungeonGenerator {
public class RoomCollision {
const int GridScale = 3;
const int GridSize = 1 << GridScale;
struct RoomKey {
public readonly int XKey;
public readonly int YKey;
public RoomKey(int x, int y) {
XKey = x >> GridScale;
YKey = y >> GridScale;
}
public override int GetHashCode() {
return XKey * 7 + YKey;
}
}
readonly Dictionary<RoomKey, HashSet<Room>> rooms = new Dictionary<RoomKey, HashSet<Room>>();
void Add(int x, int y, Room rm) {
var key = new RoomKey(x, y);
var roomList = rooms.GetValueOrCreate(key, k => new HashSet<Room>());
roomList.Add(rm);
}
public void Add(Room rm) {
var bounds = rm.Bounds;
int x = bounds.X, y = bounds.Y;
for (; y <= bounds.MaxY + GridSize; y += GridSize) {
for (x = bounds.X; x <= bounds.MaxX + 20; x += GridSize)
Add(x, y, rm);
}
}
bool HitTest(int x, int y, Rect bounds) {
var key = new RoomKey(x, y);
var roomList = rooms.GetValueOrDefault(key, (HashSet<Room>)null);
if (roomList != null) {
foreach (var room in roomList)
if (!room.Bounds.Intersection(bounds).IsEmpty)
return true;
}
return false;
}
public bool HitTest(Room rm) {
var bounds = new Rect(rm.Bounds.X - 1, rm.Bounds.Y - 1, rm.Bounds.MaxX + 1, rm.Bounds.MaxY + 1);
int x = bounds.X, y = bounds.Y;
for (; y <= bounds.MaxY + GridSize; y += GridSize) {
for (x = bounds.X; x <= bounds.MaxX + GridSize; x += GridSize) {
if (HitTest(x, y, bounds))
return true;
}
}
return false;
}
}
} | /*
Copyright (C) 2015 creepylava
This file is part of RotMG Dungeon Generator.
RotMG Dungeon Generator is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using DungeonGenerator.Dungeon;
using RotMG.Common;
using RotMG.Common.Rasterizer;
namespace DungeonGenerator {
public class RoomCollision {
const int GridScale = 3;
const int GridSize = 1 << GridScale;
struct RoomKey {
public readonly int XKey;
public readonly int YKey;
public RoomKey(int x, int y) {
XKey = x >> GridScale;
YKey = y >> GridScale;
}
public override int GetHashCode() {
return XKey * 7 + YKey;
}
}
readonly Dictionary<RoomKey, HashSet<Room>> rooms = new Dictionary<RoomKey, HashSet<Room>>();
void Add(int x, int y, Room rm) {
var key = new RoomKey(x, y);
var roomList = rooms.GetValueOrCreate(key, k => new HashSet<Room>());
roomList.Add(rm);
}
public void Add(Room rm) {
var bounds = rm.Bounds;
int x = bounds.X, y = bounds.Y;
for (; y <= bounds.MaxY + GridSize; y += GridSize) {
for (x = bounds.X; x <= bounds.MaxX + 20; x += GridSize)
Add(x, y, rm);
}
}
bool HitTest(int x, int y, Rect bounds) {
var key = new RoomKey(x, y);
var roomList = rooms.GetValueOrDefault(key, (HashSet<Room>)null);
if (roomList != null) {
foreach (var room in roomList)
if (!room.Bounds.Intersection(bounds).IsEmpty)
return true;
}
return false;
}
public bool HitTest(Room rm) {
var bounds = rm.Bounds;
int x = bounds.X, y = bounds.Y;
for (; y <= bounds.MaxY + GridSize; y += GridSize) {
for (x = bounds.X; x <= bounds.MaxX + GridSize; x += GridSize) {
if (HitTest(x, y, bounds))
return true;
}
}
return false;
}
}
} | agpl-3.0 | C# |
145c714580de659e23389047a48c54e10b147772 | Enable nullable reference type | neuecc/MagicOnion | src/MagicOnion.Server.HttpGateway/MagicOnionMiddlewareExtensions.cs | src/MagicOnion.Server.HttpGateway/MagicOnionMiddlewareExtensions.cs | #nullable enable
using Grpc.Core;
using MagicOnion.Server.HttpGateway;
using MagicOnion.Server.HttpGateway.Swagger;
using MagicOnion.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grpc.Net.Client;
using Microsoft.AspNetCore.Routing;
namespace Microsoft.AspNetCore.Builder
{
public static class MagicOnionMiddlewareExtensions
{
public static IEndpointConventionBuilder MapMagicOnionSwagger(this IEndpointRouteBuilder endpoints, string pattern, IReadOnlyList<MagicOnion.Server.MethodHandler> handlers, string apiBasePath, SwaggerOptions? swaggerOptions = default)
{
var d = endpoints.CreateApplicationBuilder()
.UseMiddleware<MagicOnionSwaggerMiddleware>(handlers, swaggerOptions ?? new SwaggerOptions("MagicOnion", "", apiBasePath))
.Build();
return endpoints.Map(pattern + "/{path?}", d);
}
public static IEndpointConventionBuilder MapMagicOnionHttpGateway(this IEndpointRouteBuilder endpoints, string pattern, IReadOnlyList<MagicOnion.Server.MethodHandler> handlers, GrpcChannel channel)
{
var d = endpoints.CreateApplicationBuilder()
.UseMiddleware<MagicOnionHttpGatewayMiddleware>(handlers, channel)
.Build();
return endpoints.Map(pattern + "/{service}/{method}", d);
}
}
} | using Grpc.Core;
using MagicOnion.Server.HttpGateway;
using MagicOnion.Server.HttpGateway.Swagger;
using MagicOnion.Server;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grpc.Net.Client;
using Microsoft.AspNetCore.Routing;
namespace Microsoft.AspNetCore.Builder
{
public static class MagicOnionMiddlewareExtensions
{
public static IEndpointConventionBuilder MapMagicOnionSwagger(this IEndpointRouteBuilder endpoints, string pattern, IReadOnlyList<MagicOnion.Server.MethodHandler> handlers, string apiBasePath, SwaggerOptions? swaggerOptions = default)
{
var d = endpoints.CreateApplicationBuilder()
.UseMiddleware<MagicOnionSwaggerMiddleware>(handlers, swaggerOptions ?? new SwaggerOptions("MagicOnion", "", apiBasePath))
.Build();
return endpoints.Map(pattern + "/{path?}", d);
}
public static IEndpointConventionBuilder MapMagicOnionHttpGateway(this IEndpointRouteBuilder endpoints, string pattern, IReadOnlyList<MagicOnion.Server.MethodHandler> handlers, GrpcChannel channel)
{
var d = endpoints.CreateApplicationBuilder()
.UseMiddleware<MagicOnionHttpGatewayMiddleware>(handlers, channel)
.Build();
return endpoints.Map(pattern + "/{service}/{method}", d);
}
}
} | mit | C# |
5f2001fa599673d067f10404e2a38ac82842175a | Enable offline exception catching | File-New-Project/EarTrumpet | EarTrumpet/Services/ErrorReportingService.cs | EarTrumpet/Services/ErrorReportingService.cs | using Bugsnag;
using Bugsnag.Clients;
using EarTrumpet.Extensions;
using EarTrumpet.Misc;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Windows.ApplicationModel;
namespace EarTrumpet.Services
{
class ErrorReportingService
{
internal static void Initialize()
{
try
{
#if DEBUG
WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif
WPFClient.Config.StoreOfflineErrors = true;
WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal";
WPFClient.Start();
WPFClient.Config.BeforeNotify(OnBeforeNotify);
Task.Factory.StartNew(WPFClient.SendStoredReports);
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
private static bool OnBeforeNotify(Event error)
{
// Remove default metadata we don't need nor want.
error.Metadata.AddToTab("Device", "machineName", "<redacted>");
error.Metadata.AddToTab("Device", "hostname", "<redacted>");
error.Metadata.AddToTab("AppSettings", "IsLightTheme", GetNoError(() => SystemSettings.IsLightTheme));
error.Metadata.AddToTab("AppSettings", "IsRTL", GetNoError(() => SystemSettings.IsRTL));
error.Metadata.AddToTab("AppSettings", "IsTransparencyEnabled", GetNoError(() => SystemSettings.IsTransparencyEnabled));
error.Metadata.AddToTab("AppSettings", "UseAccentColor", GetNoError(() => SystemSettings.UseAccentColor));
return true;
}
private static string GetNoError(Func<object> get)
{
try
{
var ret = get();
return ret == null ? "null" : ret.ToString();
}
catch (Exception ex)
{
return $"{ex}";
}
}
}
}
| using Bugsnag;
using Bugsnag.Clients;
using EarTrumpet.Extensions;
using EarTrumpet.Misc;
using System;
using System.Diagnostics;
using System.IO;
using Windows.ApplicationModel;
namespace EarTrumpet.Services
{
class ErrorReportingService
{
internal static void Initialize()
{
try
{
#if DEBUG
WPFClient.Config.ApiKey = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @"\eartrumpet.bugsnag.apikey");
#endif
WPFClient.Config.AppVersion = App.Current.HasIdentity() ? Package.Current.Id.Version.ToVersionString() : "DevInternal";
WPFClient.Start();
WPFClient.Config.BeforeNotify(OnBeforeNotify);
}
catch (Exception ex)
{
Trace.WriteLine(ex);
}
}
private static bool OnBeforeNotify(Event error)
{
// Remove default metadata we don't need nor want.
error.Metadata.AddToTab("Device", "machineName", "<redacted>");
error.Metadata.AddToTab("Device", "hostname", "<redacted>");
error.Metadata.AddToTab("AppSettings", "IsLightTheme", GetNoError(() => SystemSettings.IsLightTheme));
error.Metadata.AddToTab("AppSettings", "IsRTL", GetNoError(() => SystemSettings.IsRTL));
error.Metadata.AddToTab("AppSettings", "IsTransparencyEnabled", GetNoError(() => SystemSettings.IsTransparencyEnabled));
error.Metadata.AddToTab("AppSettings", "UseAccentColor", GetNoError(() => SystemSettings.UseAccentColor));
return true;
}
private static string GetNoError(Func<object> get)
{
try
{
var ret = get();
return ret == null ? "null" : ret.ToString();
}
catch (Exception ex)
{
return $"{ex}";
}
}
}
}
| mit | C# |
7c810f259f88a45a1b601f74ba1504121ee0f0e9 | Update YourFoodDbContext.cs | Telerik-Hackathon-2014/YourFood-WebAPI,Telerik-Hackathon-2014/YourFood-WebAPI | YourFood.Data/DbContext/YourFoodDbContext.cs | YourFood.Data/DbContext/YourFoodDbContext.cs | namespace YourFood.Data.DbContext
{
using System;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using YourFood.Common;
using YourFood.Data.Migrations;
using YourFood.Models;
public class YourFoodDbContext : IdentityDbContext<User>, IYourFoodDbContext
{
public YourFoodDbContext()
: base(ConnectionStrings.CloudDatabaseConnection, throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourFoodDbContext, Configuration>());
}
public IDbSet<AvailabilityProduct> AvailabilityProducts { get; set; }
public IDbSet<CatalogProduct> CatalogProducts { get; set; }
public IDbSet<Product> Products { get; set; }
public IDbSet<ProductCategory> ProductCategories { get; set; }
public IDbSet<Recipe> Recipes { get; set; }
public IDbSet<RecipeCategory> RecipeCategoriess { get; set; }
public IDbSet<RecipeProduct> RecipeProducts { get; set; }
public IDbSet<RecipeUsageRecord> RecipeUsageRecords { get; set; }
public IDbSet<ShoppingList> ShoppingLists { get; set; }
public static YourFoodDbContext Create()
{
return new YourFoodDbContext();
}
public IDbSet<T> Set<T>() where T : class
{
return base.Set<T>();
}
public void SaveChanges()
{
base.SaveChanges();
}
}
}
| namespace YourFood.Data.DbContext
{
using System;
using System.Data.Entity;
using Microsoft.AspNet.Identity.EntityFramework;
using YourFood.Common;
using YourFood.Data.Migrations;
using YourFood.Models;
public class YourFoodDbContext : IdentityDbContext<User>, IYourFoodDbContext
{
public YourFoodDbContext()
: base(ConnectionStrings.DefaultConnection, throwIfV1Schema: false)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<YourFoodDbContext, Configuration>());
}
public IDbSet<AvailabilityProduct> AvailabilityProducts { get; set; }
public IDbSet<CatalogProduct> CatalogProducts { get; set; }
public IDbSet<Product> Products { get; set; }
public IDbSet<ProductCategory> ProductCategories { get; set; }
public IDbSet<Recipe> Recipes { get; set; }
public IDbSet<RecipeCategory> RecipeCategoriess { get; set; }
public IDbSet<RecipeProduct> RecipeProducts { get; set; }
public IDbSet<RecipeUsageRecord> RecipeUsageRecords { get; set; }
public IDbSet<ShoppingList> ShoppingLists { get; set; }
public static YourFoodDbContext Create()
{
return new YourFoodDbContext();
}
public IDbSet<T> Set<T>() where T : class
{
return base.Set<T>();
}
public void SaveChanges()
{
base.SaveChanges();
}
}
} | mit | C# |
3ca3062118d5498dae38fe953bb447f0261c9e33 | Fix crash when viewing some maps with features close to the edge | MHeasell/Mappy,MHeasell/Mappy | Mappy/Data/Feature.cs | Mappy/Data/Feature.cs | namespace Mappy.Data
{
using System;
using System.Drawing;
using Grids;
public class Feature
{
public Feature(string name, Bitmap image)
: this(name, image, new Point(0, 0), new Size(1, 1))
{
}
public Feature(string name, Bitmap image, Point offset, Size footprint)
{
this.Name = name;
this.Image = image;
this.Offset = offset;
this.Footprint = footprint;
}
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public Size Footprint { get; set; }
public Point Offset { get; set; }
public Bitmap Image { get; set; }
public void Draw(Graphics g, Rectangle clipRectangle)
{
g.DrawImageUnscaled(this.Image, this.Offset);
}
public Rectangle GetDrawBounds(IGrid<int> heightmap, int xPos, int yPos)
{
int accum = 0;
for (int y = 0; y <= this.Footprint.Width; y++)
{
for (int x = 0; x <= this.Footprint.Height; x++)
{
int accX = xPos + x;
int accY = yPos + y;
// avoid crashing if we try to draw a feature too close to the map edge
if (accX < 0 || accY < 0 || accX >= heightmap.Width || accY >= heightmap.Height)
{
continue;
}
accum += heightmap.Get(xPos + x, yPos + y);
}
}
int avg = accum / ((this.Footprint.Width + 1) * (this.Footprint.Height + 1));
float posX = ((float)xPos + (this.Footprint.Width / 2.0f)) * 16;
float posY = (((float)yPos + (this.Footprint.Height / 2.0f)) * 16) - (avg / 2);
Point pos = new Point((int)Math.Round(posX) - this.Offset.X, (int)Math.Round(posY) - this.Offset.Y);
return new Rectangle(pos, this.Image.Size);
}
}
}
| namespace Mappy.Data
{
using System;
using System.Drawing;
using Grids;
public class Feature
{
public Feature(string name, Bitmap image)
: this(name, image, new Point(0, 0), new Size(1, 1))
{
}
public Feature(string name, Bitmap image, Point offset, Size footprint)
{
this.Name = name;
this.Image = image;
this.Offset = offset;
this.Footprint = footprint;
}
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public Size Footprint { get; set; }
public Point Offset { get; set; }
public Bitmap Image { get; set; }
public void Draw(Graphics g, Rectangle clipRectangle)
{
g.DrawImageUnscaled(this.Image, this.Offset);
}
public Rectangle GetDrawBounds(IGrid<int> heightmap, int xPos, int yPos)
{
int accum = 0;
for (int y = 0; y <= this.Footprint.Width; y++)
{
for (int x = 0; x <= this.Footprint.Height; x++)
{
accum += heightmap.Get(xPos + x, yPos + y);
}
}
int avg = accum / ((this.Footprint.Width + 1) * (this.Footprint.Height + 1));
float posX = ((float)xPos + (this.Footprint.Width / 2.0f)) * 16;
float posY = (((float)yPos + (this.Footprint.Height / 2.0f)) * 16) - (avg / 2);
Point pos = new Point((int)Math.Round(posX) - this.Offset.X, (int)Math.Round(posY) - this.Offset.Y);
return new Rectangle(pos, this.Image.Size);
}
}
}
| mit | C# |
d1a06381161223bd024ee6c80ea483834ee0b477 | Add configuration options for HMRC to use MI Feed | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Domain/Configuration/HmrcConfiguration.cs | src/SFA.DAS.EmployerApprenticeshipsService.Domain/Configuration/HmrcConfiguration.cs | namespace SFA.DAS.EAS.Domain.Configuration
{
public class HmrcConfiguration
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string Scope { get; set; }
public string ClientSecret { get; set; }
public string ServerToken { get; set; }
public string OgdSecret { get; set; }
public string OgdClientId { get; set; }
public string AzureClientId { get; set; }
public string AzureAppKey { get; set; }
public string AzureResourceId { get; set; }
public string AzureTenant { get; set; }
public bool UseHiDataFeed { get; set; }
}
} | namespace SFA.DAS.EAS.Domain.Configuration
{
public class HmrcConfiguration
{
public string BaseUrl { get; set; }
public string ClientId { get; set; }
public string Scope { get; set; }
public string ClientSecret { get; set; }
public string ServerToken { get; set; }
public string OgdSecret { get; set; }
public string OgdClientId { get; set; }
}
} | mit | C# |
c4ab17da68ff73ddf5aa10e895fd52394b6fa007 | Remove static that is unused. | mgoertz-msft/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,tmeschter/roslyn,reaction1989/roslyn,genlu/roslyn,OmarTawfik/roslyn,eriawan/roslyn,agocke/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,jcouv/roslyn,cston/roslyn,AmadeusW/roslyn,jmarolf/roslyn,reaction1989/roslyn,DustinCampbell/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,weltkante/roslyn,eriawan/roslyn,bartdesmet/roslyn,dotnet/roslyn,tmeschter/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,swaroop-sridhar/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,paulvanbrenk/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,heejaechang/roslyn,jamesqo/roslyn,DustinCampbell/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,heejaechang/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,xasx/roslyn,tmeschter/roslyn,agocke/roslyn,DustinCampbell/roslyn,davkean/roslyn,xasx/roslyn,aelij/roslyn,abock/roslyn,cston/roslyn,nguerrera/roslyn,paulvanbrenk/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,mavasani/roslyn,diryboy/roslyn,jcouv/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,dpoeschl/roslyn,AmadeusW/roslyn,stephentoub/roslyn,genlu/roslyn,bkoelman/roslyn,jcouv/roslyn,jamesqo/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,bkoelman/roslyn,paulvanbrenk/roslyn,AmadeusW/roslyn,brettfo/roslyn,wvdd007/roslyn,sharwell/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,OmarTawfik/roslyn,KirillOsenkov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,wvdd007/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,diryboy/roslyn,physhi/roslyn,jasonmalinowski/roslyn,tmat/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,jamesqo/roslyn,MichalStrehovsky/roslyn,mavasani/roslyn,stephentoub/roslyn,aelij/roslyn,wvdd007/roslyn,abock/roslyn,weltkante/roslyn,davkean/roslyn,OmarTawfik/roslyn,nguerrera/roslyn,VSadov/roslyn,aelij/roslyn,nguerrera/roslyn,AlekseyTs/roslyn,tmat/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,bkoelman/roslyn,agocke/roslyn,gafter/roslyn,dotnet/roslyn,xasx/roslyn,davkean/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,panopticoncentral/roslyn,tmat/roslyn,dotnet/roslyn,gafter/roslyn,KirillOsenkov/roslyn,dpoeschl/roslyn,brettfo/roslyn,bartdesmet/roslyn,genlu/roslyn,diryboy/roslyn,eriawan/roslyn,mavasani/roslyn,cston/roslyn | src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/WellKnownFixAllProviders.cs | src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/WellKnownFixAllProviders.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 Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Contains well known implementations of <see cref="FixAllProvider"/>.
/// </summary>
public static class WellKnownFixAllProviders
{
/// <summary>
/// Default batch fix all provider.
/// This provider batches all the individual diagnostic fixes across the scope of fix all action,
/// computes fixes in parallel and then merges all the non-conflicting fixes into a single fix all code action.
/// This fixer supports fixes for the following fix all scopes:
/// <see cref="FixAllScope.Document"/>, <see cref="FixAllScope.Project"/> and <see cref="FixAllScope.Solution"/>.
/// </summary>
/// <remarks>
/// The batch fix all provider only batches operations (i.e. <see cref="CodeActionOperation"/>) of type
/// <see cref="ApplyChangesOperation"/> present within the individual diagnostic fixes. Other types of
/// operations present within these fixes are ignored.
/// </remarks>
public static FixAllProvider BatchFixer => BatchFixAllProvider.Instance;
}
}
| // 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 Microsoft.CodeAnalysis.CodeActions;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Contains well known implementations of <see cref="FixAllProvider"/>.
/// </summary>
public static class WellKnownFixAllProviders
{
/// <summary>
/// Default batch fix all provider.
/// This provider batches all the individual diagnostic fixes across the scope of fix all action,
/// computes fixes in parallel and then merges all the non-conflicting fixes into a single fix all code action.
/// This fixer supports fixes for the following fix all scopes:
/// <see cref="FixAllScope.Document"/>, <see cref="FixAllScope.Project"/> and <see cref="FixAllScope.Solution"/>.
/// </summary>
/// <remarks>
/// The batch fix all provider only batches operations (i.e. <see cref="CodeActionOperation"/>) of type
/// <see cref="ApplyChangesOperation"/> present within the individual diagnostic fixes. Other types of
/// operations present within these fixes are ignored.
/// </remarks>
public static FixAllProvider BatchFixer => BatchFixAllProvider.Instance;
/// <summary>
/// Default batch fix all provider for simplification fixers which only add Simplifier annotations to documents.
/// This provider batches all the simplifier annotation actions within a document into a single code action,
/// instead of creating separate code actions for each added annotation.
/// This fixer supports fixes for the following fix all scopes:
/// <see cref="FixAllScope.Document"/>, <see cref="FixAllScope.Project"/> and <see cref="FixAllScope.Solution"/>.
/// </summary>
internal static FixAllProvider BatchSimplificationFixer => BatchSimplificationFixAllProvider.Instance;
}
}
| mit | C# |
2d37d0a7ac922b282b0c0f5b9816d65d934a4757 | Update Singleton.cs | efruchter/UnityUtilities | Patterns/Singleton.cs | Patterns/Singleton.cs | using System;
using UnityEngine.Assertions;
namespace Patterns
{
/// <summary>
/// Singleton manager. Provides a warning when trying to double-add or get null singletons.
/// </summary>
public static class Singleton<T> where T : class
{
private static T _singleton;
private static Action<T> _onAdd;
/// <summary>
/// O(1) Fetch or add of singleton.
/// </summary>
public static T Instance
{
set { AddSingleton(value); }
get { return GetSingleton(); }
}
public static bool Exists
{
get
{
return _singleton != null;
}
}
/// <summary>
/// Get a singleton. Warning if not available.
/// </summary>
/// <returns>The singleton if available.</returns>
public static T GetSingleton()
{
Assert.IsTrue(Exists, "Singleton does not exist at this moment. Advice: Fetch Singletons with GetSingletonDeferred, or later in the frame.");
return _singleton;
}
/// <summary>
/// Perform an action as soon as the singleton is available.
/// </summary>
public static Action<T> InstanceReady
{
set
{
GetSingletonDeferred(value);
}
}
/// <summary>
/// Get a singleton whenever it is available.
/// </summary>
/// <param name="onAdd">The callback to run when singleton Exists</param>
public static void GetSingletonDeferred(Action<T> onAdd)
{
Assert.IsNotNull(onAdd, "Callback can not be null.");
if (Exists)
{
onAdd(GetSingleton());
}
else if (_onAdd == null)
{
_onAdd = onAdd;
}
else
{
_onAdd += onAdd;
}
}
/// <summary>
/// Register a singleton. Replacement is illegal.
/// </summary>
/// <param name="singleton">The instance.</param>
public static void AddSingleton(T singleton)
{
AddSingleton(singleton, false);
}
/// <summary>
/// Release the singleton so others can use it.
/// </summary>
public static void Release()
{
_singleton = null;
_onAdd = null;
}
/// <summary>
/// Register a singleton.
/// </summary>
/// <param name="singleton">The instance.</param>
/// <param name="allowReplace">If true, allow replacement without warning.</param>
public static void AddSingleton(T singleton, bool allowReplace)
{
if (singleton == null)
{
Release();
return;
}
Assert.IsFalse(!allowReplace && Exists, "Attempting to replace a singleton that already exists.");
_singleton = singleton;
if (_onAdd != null)
{
_onAdd(singleton);
_onAdd = null;
}
}
}
}
| using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
/// <summary>
/// Singleton manager. Provides a warning when trying to double-add or get null singletons.
/// </summary>
public static class Singleton<T> where T : class
{
private static T _singleton;
private static Action<T> _onAdd;
public static T Instance
{
set
{
AddSingleton (value);
}
get
{
return GetSingleton();
}
}
public static T GetSingleton()
{
Assert.IsNotNull (_singleton, "SingletonManager: Warning, attempting to get a singleton that does not exist." +
" Be sure you are not calling get before Awake()");
return _singleton;
}
public static void GetSingletonDeferred(Action<T> onAdd)
{
Assert.IsNotNull(onAdd, "Callback can not be null.");
T singleton = GetSingleton();
if (singleton == null)
{
if (_onAdd == null)
{
_onAdd = onAdd;
}
else
{
_onAdd += onAdd;
}
}
else
{
onAdd(singleton);
}
}
public static void AddSingleton(T singleton)
{
AddSingleton(singleton, false);
}
public static void AddSingleton(T singleton, bool allowReplace)
{
Assert.IsNotNull (singleton, "Singleton can not be null.");
Assert.IsFalse ((!allowReplace) && (_singleton != null), "Attempting to replace a singleton that already exists.");
_singleton = singleton;
if (_onAdd != null)
{
_onAdd (singleton);
_onAdd = null;
}
}
}
| mit | C# |
3ca2a7767a04d2911d8244bb1d2755747e099a45 | Exclude misses and empty window hits from UR calculation | ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu | osu.Game/Screens/Ranking/Statistics/UnstableRate.cs | osu.Game/Screens/Ranking/Statistics/UnstableRate.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.Generic;
using System.Linq;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Ranking.Statistics
{
/// <summary>
/// Displays the unstable rate statistic for a given play.
/// </summary>
public class UnstableRate : SimpleStatisticItem<double>
{
/// <summary>
/// Creates and computes an <see cref="UnstableRate"/> statistic.
/// </summary>
/// <param name="hitEvents">Sequence of <see cref="HitEvent"/>s to calculate the unstable rate based on.</param>
public UnstableRate(IEnumerable<HitEvent> hitEvents)
: base("Unstable Rate")
{
var timeOffsets = hitEvents.Where(e => !(e.HitObject.HitWindows is HitWindows.EmptyHitWindows) && e.Result != HitResult.Miss)
.Select(ev => ev.TimeOffset).ToArray();
Value = 10 * standardDeviation(timeOffsets);
}
private static double standardDeviation(double[] timeOffsets)
{
if (timeOffsets.Length == 0)
return double.NaN;
var mean = timeOffsets.Average();
var squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum();
return Math.Sqrt(squares / timeOffsets.Length);
}
protected override string DisplayValue(double value) => double.IsNaN(value) ? "(not available)" : value.ToString("N2");
}
}
| // 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.Generic;
using System.Linq;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Screens.Ranking.Statistics
{
/// <summary>
/// Displays the unstable rate statistic for a given play.
/// </summary>
public class UnstableRate : SimpleStatisticItem<double>
{
/// <summary>
/// Creates and computes an <see cref="UnstableRate"/> statistic.
/// </summary>
/// <param name="hitEvents">Sequence of <see cref="HitEvent"/>s to calculate the unstable rate based on.</param>
public UnstableRate(IEnumerable<HitEvent> hitEvents)
: base("Unstable Rate")
{
var timeOffsets = hitEvents.Select(ev => ev.TimeOffset).ToArray();
Value = 10 * standardDeviation(timeOffsets);
}
private static double standardDeviation(double[] timeOffsets)
{
if (timeOffsets.Length == 0)
return double.NaN;
var mean = timeOffsets.Average();
var squares = timeOffsets.Select(offset => Math.Pow(offset - mean, 2)).Sum();
return Math.Sqrt(squares / timeOffsets.Length);
}
protected override string DisplayValue(double value) => double.IsNaN(value) ? "(not available)" : value.ToString("N2");
}
}
| mit | C# |
a31be8f846c890c95a2ffdc2571686ce5f9f9130 | Fix name violation | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/ManagedDialogs/ManagedFileChooserFilterViewModel.cs | WalletWasabi.Gui/ManagedDialogs/ManagedFileChooserFilterViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.ManagedDialogs
{
internal class ManagedFileChooserFilterViewModel : ViewModelBase
{
private readonly string[] Extensions;
public string Name { get; }
public ManagedFileChooserFilterViewModel(FileDialogFilter filter)
{
Name = filter.Name;
if (filter.Extensions.Contains("*"))
{
return;
}
Extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()).ToArray();
}
public ManagedFileChooserFilterViewModel()
{
Name = "All files";
}
public bool Match(string filename)
{
if (Extensions == null)
{
return true;
}
foreach (var ext in Extensions)
{
if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
public override string ToString() => Name;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.ManagedDialogs
{
internal class ManagedFileChooserFilterViewModel : ViewModelBase
{
private readonly string[] _extensions;
public string Name { get; }
public ManagedFileChooserFilterViewModel(FileDialogFilter filter)
{
Name = filter.Name;
if (filter.Extensions.Contains("*"))
{
return;
}
_extensions = filter.Extensions?.Select(e => "." + e.ToLowerInvariant()).ToArray();
}
public ManagedFileChooserFilterViewModel()
{
Name = "All files";
}
public bool Match(string filename)
{
if (_extensions == null)
{
return true;
}
foreach (var ext in _extensions)
{
if (filename.EndsWith(ext, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
public override string ToString() => Name;
}
}
| mit | C# |
038099a58a1cb4dde9afa510e343993345fc5b69 | Update to skype production openId configuration | xiangyan99/BotBuilder,dr-em/BotBuilder,msft-shahins/BotBuilder,msft-shahins/BotBuilder,stevengum97/BotBuilder,dr-em/BotBuilder,yakumo/BotBuilder,dr-em/BotBuilder,xiangyan99/BotBuilder,stevengum97/BotBuilder,stevengum97/BotBuilder,Clairety/ConnectMe,mmatkow/BotBuilder,mmatkow/BotBuilder,Clairety/ConnectMe,msft-shahins/BotBuilder,yakumo/BotBuilder,mmatkow/BotBuilder,Clairety/ConnectMe,yakumo/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,dr-em/BotBuilder,stevengum97/BotBuilder,Clairety/ConnectMe,xiangyan99/BotBuilder,mmatkow/BotBuilder,xiangyan99/BotBuilder | CSharp/Library/Microsoft.Bot.Connector/JwtConfig.cs | CSharp/Library/Microsoft.Bot.Connector/JwtConfig.cs | using System;
using System.IdentityModel.Tokens;
using System.Linq;
namespace Microsoft.Bot.Connector
{
/// <summary>
/// Configuration for JWT tokens
/// </summary>
public static class JwtConfig
{
/// <summary>
/// TO BOT FROM CHANNEL: OpenID metadata document for tokens coming from MSA
/// </summary>
public const string ToBotFromChannelOpenIdMetadataUrl = "https://api.aps.skype.com/v1/.well-known/openidconfiguration";
/// <summary>
/// TO BOT FROM CHANNEL: Token validation parameters when connecting to a bot
/// </summary>
public static TokenValidationParameters GetToBotFromChannelTokenValidationParameters(string msaAppId)
{
return new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuers = new[] { "https://api.botframework.com" },
ValidateAudience = true,
ValidAudiences = new[] { msaAppId },
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5),
RequireSignedTokens = true
};
}
/// <summary>
/// TO BOT FROM MSA: OpenID metadata document for tokens coming from MSA
/// </summary>
/// <remarks>
/// These settings are used to allow access from the Bot Framework Emulator
/// </remarks>
public const string ToBotFromMSAOpenIdMetadataUrl = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
/// <summary>
/// TO BOT FROM MSA: Token validation parameters when connecting to a channel
/// </summary>
/// <remarks>
/// These settings are used to allow access from the Bot Framework Emulator
/// </remarks>
public static readonly TokenValidationParameters ToBotFromMSATokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuers = new[] { "https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/" },
ValidateAudience = true,
ValidAudiences = new[] { "https://graph.microsoft.com" },
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5),
RequireSignedTokens = true
};
}
}
| using System;
using System.IdentityModel.Tokens;
using System.Linq;
namespace Microsoft.Bot.Connector
{
/// <summary>
/// Configuration for JWT tokens
/// </summary>
public static class JwtConfig
{
/// <summary>
/// TO BOT FROM CHANNEL: OpenID metadata document for tokens coming from MSA
/// </summary>
public const string ToBotFromChannelOpenIdMetadataUrl = "https://intercom-api-scratch.azurewebsites.net/api/.well-known/OpenIdConfiguration";
/// <summary>
/// TO BOT FROM CHANNEL: Token validation parameters when connecting to a bot
/// </summary>
public static TokenValidationParameters GetToBotFromChannelTokenValidationParameters(string msaAppId)
{
return new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuers = new[] { "https://api.botframework.com" },
ValidateAudience = true,
ValidAudiences = new[] { msaAppId },
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5),
RequireSignedTokens = true
};
}
/// <summary>
/// TO BOT FROM MSA: OpenID metadata document for tokens coming from MSA
/// </summary>
/// <remarks>
/// These settings are used to allow access from the Bot Framework Emulator
/// </remarks>
public const string ToBotFromMSAOpenIdMetadataUrl = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
/// <summary>
/// TO BOT FROM MSA: Token validation parameters when connecting to a channel
/// </summary>
/// <remarks>
/// These settings are used to allow access from the Bot Framework Emulator
/// </remarks>
public static readonly TokenValidationParameters ToBotFromMSATokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuers = new[] { "https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/" },
ValidateAudience = true,
ValidAudiences = new[] { "https://graph.microsoft.com" },
ValidateLifetime = true,
ClockSkew = TimeSpan.FromMinutes(5),
RequireSignedTokens = true
};
}
}
| mit | C# |
d73a3da61da863a5b5e76b3f7ce868b3719eea1f | tweak enemy spawn delay | paidgeek/Withstand | Assets/Scripts/Enemies/EnemySpawner.cs | Assets/Scripts/Enemies/EnemySpawner.cs | using System.Collections;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private Transform[] m_EnemyPrefabs;
private float m_Rate;
private void Start()
{
m_Rate = 8.0f;
StartCoroutine(SpawnerCoroutine());
}
public void OnGameOver()
{
StopAllCoroutines();
}
private IEnumerator SpawnerCoroutine()
{
yield return new WaitForSeconds(2.0f);
while (true) {
m_Rate = Mathf.Clamp(m_Rate - 0.06f, 3.0f, 8.0f);
Spawn();
yield return new WaitForSeconds(m_Rate);
}
}
private void Spawn()
{
var pos = Random.onUnitSphere * 13.0f;
Instantiate(m_EnemyPrefabs[Random.Range(0, m_EnemyPrefabs.Length)], pos, Quaternion.identity);
}
} | using System.Collections;
using UnityEngine;
public class EnemySpawner : MonoBehaviour
{
[SerializeField] private Transform[] m_EnemyPrefabs;
private float m_Rate;
private void Start()
{
m_Rate = 8.0f;
StartCoroutine(SpawnerCoroutine());
}
public void OnGameOver()
{
StopAllCoroutines();
}
private IEnumerator SpawnerCoroutine()
{
yield return new WaitForSeconds(2.0f);
while (true) {
m_Rate = Mathf.Clamp(m_Rate - 0.1f, 5.0f, 8.0f);
Spawn();
yield return new WaitForSeconds(m_Rate);
}
}
private void Spawn()
{
var pos = Random.onUnitSphere * 13.0f;
Instantiate(m_EnemyPrefabs[Random.Range(0, m_EnemyPrefabs.Length)], pos, Quaternion.identity);
}
} | apache-2.0 | C# |
595fb247d6626fb78741d145c57f02d5dc8b9f30 | add ModelState.Clear() | hatelove/MyMvcHomework,hatelove/MyMvcHomework,hatelove/MyMvcHomework | MyMoney/MyMoney/Controllers/AccountingController.cs | MyMoney/MyMoney/Controllers/AccountingController.cs | using MyMoney.Models.Enums;
using MyMoney.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace MyMoney.Controllers
{
public class AccountingController : Controller
{
private static List<AccountingViewModel> accountings = new List<AccountingViewModel>
{
new AccountingViewModel {Type=AccountingType.收入, Amount=10000, Date = new DateTime(2016,4,10), Remark="發傳單" },
new AccountingViewModel {Type=AccountingType.支出, Amount=4000, Date = new DateTime(2016,4,11), Remark="咖啡" },
new AccountingViewModel {Type=AccountingType.收入, Amount=91995, Date = new DateTime(2016,5,10), Remark="TDD training" },
};
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(AccountingViewModel pageData)
{
accountings.Add(pageData);
ModelState.Clear();
return View();
}
[ChildActionOnly]
public ActionResult ShowHistory()
{
return View(accountings);
}
}
} | using MyMoney.Models.Enums;
using MyMoney.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
namespace MyMoney.Controllers
{
public class AccountingController : Controller
{
private static List<AccountingViewModel> accountings = new List<AccountingViewModel>
{
new AccountingViewModel {Type=AccountingType.收入, Amount=10000, Date = new DateTime(2016,4,10), Remark="發傳單" },
new AccountingViewModel {Type=AccountingType.支出, Amount=4000, Date = new DateTime(2016,4,11), Remark="咖啡" },
new AccountingViewModel {Type=AccountingType.收入, Amount=91995, Date = new DateTime(2016,5,10), Remark="TDD training" },
};
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(AccountingViewModel pageData)
{
accountings.Add(pageData);
return View();
}
[ChildActionOnly]
public ActionResult ShowHistory()
{
return View(accountings);
}
}
} | mit | C# |
21b39dcd61467ec8490c0875a37e396c9398d9fb | Update XQuadraticBezierSegment.cs | Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Path/Segments/XQuadraticBezierSegment.cs | src/Core2D/Path/Segments/XQuadraticBezierSegment.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.Collections.Generic;
using Core2D.Shapes;
namespace Core2D.Path.Segments
{
/// <summary>
/// Quadratic bezier path segment.
/// </summary>
public class XQuadraticBezierSegment : XPathSegment
{
private XPoint _point1;
private XPoint _point2;
/// <summary>
/// Gets or sets control point.
/// </summary>
public XPoint Point1
{
get => _point1;
set => Update(ref _point1, value);
}
/// <summary>
/// Gets or sets end point.
/// </summary>
public XPoint Point2
{
get => _point2;
set => Update(ref _point2, value);
}
/// <inheritdoc/>
public override IEnumerable<XPoint> GetPoints()
{
yield return Point1;
yield return Point2;
}
/// <summary>
/// Creates a new <see cref="XQuadraticBezierSegment"/> instance.
/// </summary>
/// <param name="point1">The control point.</param>
/// <param name="point2">The end point.</param>
/// <param name="isStroked">The flag indicating whether shape is stroked.</param>
/// <param name="isSmoothJoin">The flag indicating whether shape is smooth join.</param>
/// <returns>The new instance of the <see cref="XQuadraticBezierSegment"/> class.</returns>
public static XQuadraticBezierSegment Create(XPoint point1, XPoint point2, bool isStroked, bool isSmoothJoin)
{
return new XQuadraticBezierSegment()
{
Point1 = point1,
Point2 = point2,
IsStroked = isStroked,
IsSmoothJoin = isSmoothJoin
};
}
/// <inheritdoc/>
public override string ToString() => string.Format("Q{1}{0}{2}", " ", Point1, Point2);
}
}
| // 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.Collections.Generic;
using Core2D.Shapes;
namespace Core2D.Path.Segments
{
/// <summary>
/// Quadratic bezier path segment.
/// </summary>
public class XQuadraticBezierSegment : XPathSegment
{
private XPoint _point1;
private XPoint _point2;
/// <summary>
/// Gets or sets control point.
/// </summary>
public XPoint Point1
{
get { return _point1; }
set { Update(ref _point1, value); }
}
/// <summary>
/// Gets or sets end point.
/// </summary>
public XPoint Point2
{
get { return _point2; }
set { Update(ref _point2, value); }
}
/// <inheritdoc/>
public override IEnumerable<XPoint> GetPoints()
{
yield return Point1;
yield return Point2;
}
/// <summary>
/// Creates a new <see cref="XQuadraticBezierSegment"/> instance.
/// </summary>
/// <param name="point1">The control point.</param>
/// <param name="point2">The end point.</param>
/// <param name="isStroked">The flag indicating whether shape is stroked.</param>
/// <param name="isSmoothJoin">The flag indicating whether shape is smooth join.</param>
/// <returns>The new instance of the <see cref="XQuadraticBezierSegment"/> class.</returns>
public static XQuadraticBezierSegment Create(XPoint point1, XPoint point2, bool isStroked, bool isSmoothJoin)
{
return new XQuadraticBezierSegment()
{
Point1 = point1,
Point2 = point2,
IsStroked = isStroked,
IsSmoothJoin = isSmoothJoin
};
}
/// <inheritdoc/>
public override string ToString()
{
return string.Format("Q{1}{0}{2}", " ", Point1, Point2);
}
}
}
| mit | C# |
51983d05c9e630bb27a1ead12d2821e742cf7bb8 | Build fix (am I the only one getting this?) | PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto | Source/Eto.Test/Eto.Test/DynamicLayoutExtensions.cs | Source/Eto.Test/Eto.Test/DynamicLayoutExtensions.cs | using System;
using Eto.Forms;
namespace Eto.Test
{
public static class DynamicLayoutExtensions
{
public static void AddLabelledSection (this DynamicLayout layout, string text, Control control)
{
var label = new Label { Text = text, VerticalAlign = VerticalAlign.Middle };
#if DESKTOP
layout.AddRow (label, control);
#elif MOBILE
layout.BeginVertical ();
layout.Add (label);
layout.Add (control);
layout.EndVertical ();
#endif
}
}
}
| using System;
using Eto.Forms;
namespace Eto.Test
{
public static class DynamicLayoutExtensions
{
public static void AddLabelledSection (this DynamicLayout layout, string text, Control control)
{
var label = new Label { Text = text, VerticalAlign = VerticalAlign.Middle };
#if DESKTOP
layout.AddRow (Label, control);
#elif MOBILE
layout.BeginVertical ();
layout.Add (label);
layout.Add (control);
layout.EndVertical ();
#endif
}
}
}
| bsd-3-clause | C# |
e3ef6c174e6a6fd382ab7ea27dff814b0ecafe94 | Add group support for NoVehiclesUsage | Trojaner25/Rocket-Regions,Trojaner25/Rocket-Safezone | Model/Flag/Impl/NoVehiclesUsageFlag.cs | Model/Flag/Impl/NoVehiclesUsageFlag.cs | using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
public override bool SupportsGroups => true;
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var group = Region.GetGroup(player);
if(!GetValueSafe(group))
continue;
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
veh.removePlayer(seat, point, angle, true);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
} | using System.Collections.Generic;
using Rocket.Unturned.Player;
using RocketRegions.Util;
using SDG.Unturned;
using UnityEngine;
namespace RocketRegions.Model.Flag.Impl
{
public class NoVehiclesUsageFlag : BoolFlag
{
public override string Description => "Allow/Disallow usage of vehicles in region";
private readonly Dictionary<ulong, bool> _lastVehicleStates = new Dictionary<ulong, bool>();
public override void UpdateState(List<UnturnedPlayer> players)
{
foreach (var player in players)
{
var id = PlayerUtil.GetId(player);
var veh = player.Player.movement.getVehicle();
var isInVeh = veh != null;
if (!_lastVehicleStates.ContainsKey(id))
_lastVehicleStates.Add(id, veh);
var wasDriving = _lastVehicleStates[id];
if (!isInVeh || wasDriving ||
!GetValueSafe(Region.GetGroup(player))) continue;
byte seat;
Vector3 point;
byte angle;
veh.forceRemovePlayer(out seat, PlayerUtil.GetCSteamId(player), out point, out angle);
veh.removePlayer(seat, point, angle, true);
}
}
public override void OnRegionEnter(UnturnedPlayer p)
{
//do nothing
}
public override void OnRegionLeave(UnturnedPlayer p)
{
//do nothing
}
}
} | agpl-3.0 | C# |
41efb49427532bb534b835f6279ddf182c95795c | Convert invoker proxy over to be internal | pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Agent.Connection.Stream/Connection/StreamInvokerProxy.cs | src/Glimpse.Agent.Connection.Stream/Connection/StreamInvokerProxy.cs | using Microsoft.AspNet.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Connection.Stream.Connection
{
internal class StreamInvokerProxy : IStreamInvokerProxy
{
private readonly IHubProxy _hubProxy;
internal StreamInvokerProxy(IHubProxy hubProxy)
{
_hubProxy = hubProxy;
}
public Task Invoke(string method, params object[] args)
{
return _hubProxy.Invoke(method, args);
}
public Task<T> Invoke<T>(string method, params object[] args)
{
return _hubProxy.Invoke<T>(method, args);
}
}
} | using Microsoft.AspNet.SignalR.Client;
using System;
using System.Threading.Tasks;
namespace Glimpse.Agent.Connection.Stream.Connection
{
public class StreamInvokerProxy : IStreamInvokerProxy
{
private readonly IHubProxy _hubProxy;
internal StreamInvokerProxy(IHubProxy hubProxy)
{
_hubProxy = hubProxy;
}
public Task Invoke(string method, params object[] args)
{
return _hubProxy.Invoke(method, args);
}
public Task<T> Invoke<T>(string method, params object[] args)
{
return _hubProxy.Invoke<T>(method, args);
}
}
} | mit | C# |
202f354a3df30d8391cfbf01744098abdfebfe94 | Use commitAcitivty in HasChild query | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Tests/Tests/QueryDsl/Joining/HasChild/HasChildQueryUsageTests.cs | src/Tests/Tests/QueryDsl/Joining/HasChild/HasChildQueryUsageTests.cs | using Nest;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.Integration;
namespace Tests.QueryDsl.Joining.HasChild
{
public class HasChildUsageTests : QueryDslUsageTestsBase
{
public HasChildUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<IHasChildQuery>(a => a.HasChild)
{
q => q.Query = null,
q => q.Query = ConditionlessQuery,
q => q.Type = null,
};
protected override QueryContainer QueryInitializer => new HasChildQuery
{
Name = "named_query",
Boost = 1.1,
Type = Infer.Relation<CommitActivity>(),
InnerHits = new InnerHits { Explain = true },
MaxChildren = 5,
MinChildren = 1,
Query = new MatchAllQuery(),
ScoreMode = ChildScoreMode.Average
};
protected override object QueryJson => new
{
has_child = new
{
_name = "named_query",
boost = 1.1,
type = "commitActivity",
score_mode = "avg",
min_children = 1,
max_children = 5,
query = new { match_all = new { } },
inner_hits = new { explain = true }
}
};
protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q
.HasChild<CommitActivity>(c => c
.Name("named_query")
.Boost(1.1)
.InnerHits(i => i.Explain())
.MaxChildren(5)
.MinChildren(1)
.ScoreMode(ChildScoreMode.Average)
.Query(qq => qq.MatchAll())
);
}
}
| using Nest;
using Tests.Core.ManagedElasticsearch.Clusters;
using Tests.Domain;
using Tests.Framework.Integration;
namespace Tests.QueryDsl.Joining.HasChild
{
public class HasChildUsageTests : QueryDslUsageTestsBase
{
public HasChildUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override ConditionlessWhen ConditionlessWhen => new ConditionlessWhen<IHasChildQuery>(a => a.HasChild)
{
q => q.Query = null,
q => q.Query = ConditionlessQuery,
q => q.Type = null,
};
protected override QueryContainer QueryInitializer => new HasChildQuery
{
Name = "named_query",
Boost = 1.1,
Type = Infer.Relation<Developer>(),
InnerHits = new InnerHits { Explain = true },
MaxChildren = 5,
MinChildren = 1,
Query = new MatchAllQuery(),
ScoreMode = ChildScoreMode.Average
};
protected override object QueryJson => new
{
has_child = new
{
_name = "named_query",
boost = 1.1,
type = "developer",
score_mode = "avg",
min_children = 1,
max_children = 5,
query = new { match_all = new { } },
inner_hits = new { explain = true }
}
};
protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> q) => q
.HasChild<Developer>(c => c
.Name("named_query")
.Boost(1.1)
.InnerHits(i => i.Explain())
.MaxChildren(5)
.MinChildren(1)
.ScoreMode(ChildScoreMode.Average)
.Query(qq => qq.MatchAll())
);
}
}
| apache-2.0 | C# |
473ea01bce331ceef500b939761734eea662e424 | fix price type | Jitrixis/2NET-Restaurant-Management-Software | 2NET-Restaurant-Management-Software/Database/Meal.cs | 2NET-Restaurant-Management-Software/Database/Meal.cs | using System;
using System.Collections.Generic;
namespace _2NET_Restaurant_Management_Software.Database
{
class Meal
{
public int MealId { get; set; }
public string Meal_name { get; set; }
public double Price { get; set; }
public virtual List<Bill> Bill { get; set; }
}
}
| using System;
using System.Collections.Generic;
namespace _2NET_Restaurant_Management_Software.Database
{
class Meal
{
public int MealId { get; set; }
public string Meal_name { get; set; }
public int Price { get; set; }
public virtual List<Bill> Bill { get; set; }
}
}
| mit | C# |
768c3bc31e70272332fde096be6dfb093de0a972 | Use PlayMode instead of GameMode | Drezi126/osu,tacchinotacchi/osu,Damnae/osu,smoogipoo/osu,RedNesto/osu,naoey/osu,theguii/osu,DrabWeb/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,NotKyon/lolisu,ppy/osu,DrabWeb/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,2yangk23/osu,ZLima12/osu,naoey/osu,ZLima12/osu,naoey/osu,johnneijzen/osu,smoogipoo/osu,Nabile-Rahmani/osu,johnneijzen/osu,peppy/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,UselessToucan/osu,EVAST9919/osu,NeoAdonis/osu,default0/osu,peppy/osu,UselessToucan/osu,osu-RP/osu-RP,Frontear/osuKyzer,smoogipooo/osu,nyaamara/osu | osu.Game/Database/BeatmapMetadata.cs | osu.Game/Database/BeatmapMetadata.cs | using System;
using osu.Game.GameModes.Play;
using SQLite;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey]
public int ID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public PlayMode Mode { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
}
} | using System;
using osu.Game.Beatmaps;
using SQLite;
namespace osu.Game.Database
{
public class BeatmapMetadata
{
[PrimaryKey]
public int ID { get; set; }
public string Title { get; set; }
public string TitleUnicode { get; set; }
public string Artist { get; set; }
public string ArtistUnicode { get; set; }
public string Author { get; set; }
public string Source { get; set; }
public string Tags { get; set; }
public GameMode Mode { get; set; }
public int PreviewTime { get; set; }
public string AudioFile { get; set; }
public string BackgroundFile { get; set; }
}
} | mit | C# |
926281831b85353c1ddf878167abfbbad965a56f | Fix missing XMLDoc bit. | UselessToucan/osu,peppy/osu-new,UselessToucan/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu | osu.Game/Database/ICanAcceptFiles.cs | osu.Game/Database/ICanAcceptFiles.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.Collections.Generic;
using System.Threading.Tasks;
namespace osu.Game.Database
{
/// <summary>
/// A class which can accept files for importing.
/// </summary>
public interface ICanAcceptFiles
{
/// <summary>
/// Import the specified paths.
/// </summary>
/// <param name="paths">The files which should be imported.</param>
Task Import(params string[] paths);
/// <summary>
/// Import the specified files from the given import tasks.
/// </summary>
/// <param name="tasks">The import tasks from which the files should be imported.</param>
Task Import(params ImportTask[] tasks);
/// <summary>
/// An array of accepted file extensions (in the standard format of ".abc").
/// </summary>
IEnumerable<string> HandledExtensions { get; }
}
}
| // 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.Collections.Generic;
using System.Threading.Tasks;
namespace osu.Game.Database
{
/// <summary>
/// A class which can accept files for importing.
/// </summary>
public interface ICanAcceptFiles
{
/// <summary>
/// Import the specified paths.
/// </summary>
/// <param name="paths">The files which should be imported.</param>
Task Import(params string[] paths);
/// <summary>
/// Import the specified files from the given import tasks.
/// </summary>
Task Import(params ImportTask[] tasks);
/// <summary>
/// An array of accepted file extensions (in the standard format of ".abc").
/// </summary>
IEnumerable<string> HandledExtensions { get; }
}
}
| mit | C# |
ba211f525943612bb268b7f6e682392a092a9834 | Fix IndexRequest | elastic/elasticsearch-net,elastic/elasticsearch-net | src/Elastic.Clients.Elasticsearch/Api/IndexRequest.cs | src/Elastic.Clients.Elasticsearch/Api/IndexRequest.cs | // Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Text.Json;
using System.Text.Json.Serialization;
using Elastic.Transport;
namespace Elastic.Clients.Elasticsearch
{
public partial class IndexRequest<TDocument> : ICustomJsonWriter
{
public IndexRequest() : this(typeof(TDocument)) { }
//public IndexRequest(TDocument document) : this(typeof(TDocument)) => Document = document;
public IndexRequest(TDocument document, Id id) : this(typeof(TDocument), id) => Document = document;
protected override HttpMethod? DynamicHttpMethod => GetHttpMethod(this);
public IndexRequest(TDocument document, IndexName index = null, Id id = null) : this(index ?? typeof(TDocument), id ?? Id.From(document)) => Document = document;
internal IRequest<IndexRequestParameters> Self => this;
[JsonIgnore] private Id? Id => Self.RouteValues.Get<Id>("id");
void ICustomJsonWriter.WriteJson(Utf8JsonWriter writer, Serializer sourceSerializer) => SourceSerialisation.Serialize(Document, writer, sourceSerializer);
internal static HttpMethod GetHttpMethod(IndexRequest<TDocument> request) =>
request.Id?.StringOrLongValue != null || request.Self.RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST;
}
public sealed partial class IndexRequestDescriptor<TDocument> : ICustomJsonWriter
{
// TODO: Codegen
public IndexRequestDescriptor(TDocument documentWithId, IndexName index = null, Id id = null) : this(index ?? typeof(TDocument), id ?? Elasticsearch.Id.From(documentWithId)) => DocumentFromPath(documentWithId);
// ??
private void DocumentFromPath(TDocument document) => Assign(document, (a, v) => a.DocumentValue = v);
// TODO: Codegen
// Perhaps not required as this should always be set via ctors
public IndexRequestDescriptor<TDocument> Index(IndexName index) => Assign(index, (a, v) => a.RouteValues.Required("index", v));
// TODO: Codegen
public IndexRequestDescriptor<TDocument> Document(TDocument document) => Assign(document, (a, v) => a.DocumentValue = v);
internal Id _id;
public void WriteJson(Utf8JsonWriter writer, Serializer sourceSerializer) => SourceSerialisation.Serialize(DocumentValue, writer, sourceSerializer);
// TODO: Codegen for optional params
public IndexRequestDescriptor<TDocument> Id(Id id) => Assign(id, (a, v) => a.RouteValues.Optional("id", v));
protected override HttpMethod? DynamicHttpMethod => _id is not null || RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST;
}
}
| // Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Text.Json;
using System.Text.Json.Serialization;
using Elastic.Transport;
namespace Elastic.Clients.Elasticsearch
{
public partial class IndexRequest<TDocument> : ICustomJsonWriter
{
public IndexRequest() : this(typeof(TDocument)) { }
public IndexRequest(TDocument document) : this(typeof(TDocument)) => Document = document;
public IndexRequest(TDocument document, Id id) : this(typeof(TDocument), id) => Document = document;
protected override HttpMethod? DynamicHttpMethod => GetHttpMethod(this);
internal IRequest<IndexRequestParameters> Self => this;
[JsonIgnore] private Id? Id => Self.RouteValues.Get<Id>("id");
void ICustomJsonWriter.WriteJson(Utf8JsonWriter writer, Serializer sourceSerializer) => SourceSerialisation.Serialize(Document, writer, sourceSerializer);
internal static HttpMethod GetHttpMethod(IndexRequest<TDocument> request) =>
request.Id?.StringOrLongValue != null || request.Self.RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST;
}
public sealed partial class IndexRequestDescriptor<TDocument> : ICustomJsonWriter
{
// TODO: Codegen
public IndexRequestDescriptor(TDocument documentWithId, IndexName index = null, Id id = null) : this(index ?? typeof(TDocument), id ?? Elasticsearch.Id.From(documentWithId)) => DocumentFromPath(documentWithId);
// ??
private void DocumentFromPath(TDocument document) => Assign(document, (a, v) => a.DocumentValue = v);
// TODO: Codegen
// Perhaps not required as this should always be set via ctors
public IndexRequestDescriptor<TDocument> Index(IndexName index) => Assign(index, (a, v) => a.RouteValues.Required("index", v));
// TODO: Codegen
public IndexRequestDescriptor<TDocument> Document(TDocument document) => Assign(document, (a, v) => a.DocumentValue = v);
internal Id _id;
public void WriteJson(Utf8JsonWriter writer, Serializer sourceSerializer) => SourceSerialisation.Serialize(DocumentValue, writer, sourceSerializer);
// TODO: Codegen for optional params
public IndexRequestDescriptor<TDocument> Id(Id id) => Assign(id, (a, v) => a.RouteValues.Optional("id", v));
protected override HttpMethod? DynamicHttpMethod => _id is not null || RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST;
}
}
| apache-2.0 | C# |
9a9cae13edba18eeed77aea61f687ccc2fc80c90 | Simplify cancellation check. | sjp/Schematic,sjp/Schematic,sjp/Schematic,sjp/Schematic,sjp/SJP.Schema | src/SJP.Schematic.Core/Extensions/OptionExtensions.cs | src/SJP.Schematic.Core/Extensions/OptionExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt;
namespace SJP.Schematic.Core.Extensions
{
public static class OptionExtensions
{
public static T UnwrapSome<T>(this Option<T> input)
{
if (input.IsNone)
throw new ArgumentException("The given optional object does not have a value.", nameof(input));
return input.IfNoneUnsafe(default(T)!);
}
public static async Task<T> UnwrapSomeAsync<T>(this OptionAsync<T> input)
{
var isNone = await input.IsNone.ConfigureAwait(false);
if (isNone)
throw new ArgumentException("The given optional object does not have a value.", nameof(input));
return await input.IfNoneUnsafe(default(T)!).ConfigureAwait(false);
}
public static Option<T> FirstSome<T>(this IEnumerable<Option<T>> input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return input.FirstOrDefault(x => x.IsSome);
}
public static OptionAsync<T> FirstSome<T>(this IEnumerable<OptionAsync<T>> input, CancellationToken cancellationToken = default)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return FirstSomeAsyncCore(input, cancellationToken).ToAsync();
}
private static async Task<Option<T>> FirstSomeAsyncCore<T>(IEnumerable<OptionAsync<T>> input, CancellationToken cancellationToken)
{
foreach (var option in input)
{
cancellationToken.ThrowIfCancellationRequested();
var resolvedOption = await option.ToOption().ConfigureAwait(false);
if (resolvedOption.IsSome)
return resolvedOption;
}
return Option<T>.None;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using LanguageExt;
namespace SJP.Schematic.Core.Extensions
{
public static class OptionExtensions
{
public static T UnwrapSome<T>(this Option<T> input)
{
if (input.IsNone)
throw new ArgumentException("The given optional object does not have a value.", nameof(input));
return input.IfNoneUnsafe(default(T)!);
}
public static async Task<T> UnwrapSomeAsync<T>(this OptionAsync<T> input)
{
var isNone = await input.IsNone.ConfigureAwait(false);
if (isNone)
throw new ArgumentException("The given optional object does not have a value.", nameof(input));
return await input.IfNoneUnsafe(default(T)!).ConfigureAwait(false);
}
public static Option<T> FirstSome<T>(this IEnumerable<Option<T>> input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return input.FirstOrDefault(x => x.IsSome);
}
public static OptionAsync<T> FirstSome<T>(this IEnumerable<OptionAsync<T>> input, CancellationToken cancellationToken = default)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return FirstSomeAsyncCore(input, cancellationToken).ToAsync();
}
private static async Task<Option<T>> FirstSomeAsyncCore<T>(IEnumerable<OptionAsync<T>> input, CancellationToken cancellationToken)
{
foreach (var option in input)
{
if (cancellationToken.IsCancellationRequested)
throw new OperationCanceledException(cancellationToken);
var resolvedOption = await option.ToOption().ConfigureAwait(false);
if (resolvedOption.IsSome)
return resolvedOption;
}
return Option<T>.None;
}
}
}
| mit | C# |
f60b9b57dbd818f9f15a11ff5feeb53c1adc8ad1 | add streamstreamreference with factory | Kukkimonsuta/Odachi | src/Odachi.Extensions.Primitives/StreamStreamReference.cs | src/Odachi.Extensions.Primitives/StreamStreamReference.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Odachi.Abstractions;
using System.IO;
namespace Odachi.Extensions.Primitives
{
public class StreamStreamReference : IStreamReference, IDisposable
{
public StreamStreamReference(string name, Func<Stream> openReadStream)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (openReadStream == null)
throw new ArgumentNullException(nameof(openReadStream));
Name = name;
_openReadStream = openReadStream;
}
public StreamStreamReference(string name, Stream stream)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (stream == null)
throw new ArgumentNullException(nameof(stream));
Name = name;
_stream = stream;
}
private Stream _stream;
private Func<Stream> _openReadStream;
public string Name { get; }
public Stream OpenReadStream()
{
if (_openReadStream != null)
{
return _openReadStream();
}
else
{
if (_stream == null)
throw new InvalidOperationException("StreamStreamReference supports only single stream retrieval");
var result = _stream;
_stream = null;
return result;
}
}
#region IDisposable
public void Dispose()
{
if (_stream != null)
{
_stream.Dispose();
}
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Odachi.Abstractions;
using System.IO;
namespace Odachi.Extensions.Primitives
{
public class StreamStreamReference : IStreamReference, IDisposable
{
public StreamStreamReference(string name, Stream stream)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (stream == null)
throw new ArgumentNullException(nameof(stream));
Name = name;
_stream = stream;
}
private Stream _stream;
public string Name { get; }
public Stream OpenReadStream()
{
if (_stream == null)
throw new InvalidOperationException("StreamStreamReference supports only single stream retrieval");
var result = _stream;
_stream = null;
return result;
}
#region IDisposable
public void Dispose()
{
if (_stream != null)
{
_stream.Dispose();
}
}
#endregion
}
}
| apache-2.0 | C# |
02fbbc506d73036c87f3466774c2eaec0a5e987b | Fix spelling of .editorconfig option | tmeschter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,sharwell/roslyn,tvand7093/roslyn,tannergooding/roslyn,mattscheffer/roslyn,jcouv/roslyn,khyperia/roslyn,gafter/roslyn,davkean/roslyn,robinsedlaczek/roslyn,orthoxerox/roslyn,physhi/roslyn,brettfo/roslyn,tmeschter/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,AnthonyDGreen/roslyn,abock/roslyn,eriawan/roslyn,kelltrick/roslyn,diryboy/roslyn,tmat/roslyn,mavasani/roslyn,cston/roslyn,dpoeschl/roslyn,reaction1989/roslyn,bkoelman/roslyn,mavasani/roslyn,pdelvo/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,mattscheffer/roslyn,VSadov/roslyn,mattscheffer/roslyn,srivatsn/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,lorcanmooney/roslyn,reaction1989/roslyn,CyrusNajmabadi/roslyn,dpoeschl/roslyn,kelltrick/roslyn,aelij/roslyn,jamesqo/roslyn,kelltrick/roslyn,khyperia/roslyn,Hosch250/roslyn,stephentoub/roslyn,eriawan/roslyn,agocke/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,robinsedlaczek/roslyn,sharwell/roslyn,AmadeusW/roslyn,diryboy/roslyn,tvand7093/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,genlu/roslyn,weltkante/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,DustinCampbell/roslyn,DustinCampbell/roslyn,CaptainHayashi/roslyn,Hosch250/roslyn,cston/roslyn,AlekseyTs/roslyn,eriawan/roslyn,Giftednewt/roslyn,VSadov/roslyn,mavasani/roslyn,genlu/roslyn,DustinCampbell/roslyn,sharwell/roslyn,OmarTawfik/roslyn,VSadov/roslyn,paulvanbrenk/roslyn,pdelvo/roslyn,ErikSchierboom/roslyn,jkotas/roslyn,paulvanbrenk/roslyn,khyperia/roslyn,Hosch250/roslyn,CyrusNajmabadi/roslyn,TyOverby/roslyn,tmat/roslyn,mgoertz-msft/roslyn,CaptainHayashi/roslyn,dotnet/roslyn,orthoxerox/roslyn,MattWindsor91/roslyn,Giftednewt/roslyn,physhi/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,jmarolf/roslyn,pdelvo/roslyn,TyOverby/roslyn,ErikSchierboom/roslyn,cston/roslyn,mmitche/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,Giftednewt/roslyn,gafter/roslyn,AnthonyDGreen/roslyn,tvand7093/roslyn,dotnet/roslyn,jcouv/roslyn,KirillOsenkov/roslyn,xasx/roslyn,agocke/roslyn,stephentoub/roslyn,tannergooding/roslyn,dotnet/roslyn,srivatsn/roslyn,gafter/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,xasx/roslyn,heejaechang/roslyn,jamesqo/roslyn,diryboy/roslyn,dpoeschl/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,MattWindsor91/roslyn,bkoelman/roslyn,aelij/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,jcouv/roslyn,agocke/roslyn,AnthonyDGreen/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,jmarolf/roslyn,abock/roslyn,KevinRansom/roslyn,paulvanbrenk/roslyn,OmarTawfik/roslyn,wvdd007/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,robinsedlaczek/roslyn,lorcanmooney/roslyn,xasx/roslyn,weltkante/roslyn,tannergooding/roslyn,aelij/roslyn,bkoelman/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,wvdd007/roslyn,brettfo/roslyn,wvdd007/roslyn,abock/roslyn,MichalStrehovsky/roslyn,stephentoub/roslyn,jkotas/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,jamesqo/roslyn,swaroop-sridhar/roslyn,TyOverby/roslyn,jkotas/roslyn,heejaechang/roslyn,nguerrera/roslyn,genlu/roslyn,brettfo/roslyn,panopticoncentral/roslyn,srivatsn/roslyn,tmat/roslyn,MattWindsor91/roslyn,MattWindsor91/roslyn,davkean/roslyn,lorcanmooney/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,mmitche/roslyn,orthoxerox/roslyn,tmeschter/roslyn,CaptainHayashi/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn | src/Workspaces/Core/Portable/Editing/GenerationOptions.cs | src/Workspaces/Core/Portable/Editing/GenerationOptions.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 Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editing
{
internal class GenerationOptions
{
public static readonly PerLanguageOption<bool> PlaceSystemNamespaceFirst = new PerLanguageOption<bool>(nameof(GenerationOptions),
nameof(PlaceSystemNamespaceFirst), defaultValue: true,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"),
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")});
public static readonly PerLanguageOption<bool> SeparateImportDirectiveGroups = new PerLanguageOption<bool>(
nameof(GenerationOptions), nameof(SeparateImportDirectiveGroups), defaultValue: false,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_separate_import_directive_groups"),
new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")});
}
}
| // 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 Microsoft.CodeAnalysis.Options;
namespace Microsoft.CodeAnalysis.Editing
{
internal class GenerationOptions
{
public static readonly PerLanguageOption<bool> PlaceSystemNamespaceFirst = new PerLanguageOption<bool>(nameof(GenerationOptions),
nameof(PlaceSystemNamespaceFirst), defaultValue: true,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_sort_system_directives_first"),
new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.PlaceSystemNamespaceFirst")});
public static readonly PerLanguageOption<bool> SeparateImportDirectiveGroups = new PerLanguageOption<bool>(
nameof(GenerationOptions), nameof(SeparateImportDirectiveGroups), defaultValue: false,
storageLocations: new OptionStorageLocation[] {
EditorConfigStorageLocation.ForBoolOption("dotnet_seperate_import_directive_groups"),
new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(SeparateImportDirectiveGroups)}")});
}
}
| mit | C# |
2ce0a8316650920744b5ff1557ea9dbe012f633b | Fix formatting and remove unnecessary using | smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework | osu.Framework/Graphics/Shaders/Uniform.cs | osu.Framework/Graphics/Shaders/Uniform.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics.OpenGL;
using System;
namespace osu.Framework.Graphics.Shaders
{
public class Uniform<T> : IUniformWithValue<T>
where T : struct, IEquatable<T>
{
public Shader Owner { get; }
public string Name { get; }
public int Location { get; }
public bool HasChanged { get; private set; } = true;
private T val;
public T Value
{
get => val;
set
{
if (value.Equals(val))
return;
val = value;
HasChanged = true;
if (Owner.IsBound)
Update();
}
}
public Uniform(Shader owner, string name, int uniformLocation)
{
Owner = owner;
Name = name;
Location = uniformLocation;
}
public void UpdateValue(ref T newValue)
{
if (newValue.Equals(val))
return;
val = newValue;
HasChanged = true;
if (Owner.IsBound)
Update();
}
public void Update()
{
if (!HasChanged) return;
GLWrapper.SetUniform(this);
HasChanged = false;
}
ref T IUniformWithValue<T>.GetValueByRef() => ref val;
T IUniformWithValue<T>.GetValue() => val;
}
}
| // 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.Collections.Generic;
using osu.Framework.Graphics.OpenGL;
using System;
namespace osu.Framework.Graphics.Shaders
{
public class Uniform<T> : IUniformWithValue<T>
where T : struct, IEquatable<T>
{
public Shader Owner { get; }
public string Name { get; }
public int Location { get; }
public bool HasChanged { get; private set; } = true;
private T val;
public T Value
{
get => val;
set
{
if (value.Equals(val))
return;
val = value;
HasChanged = true;
if (Owner.IsBound)
Update();
}
}
public Uniform(Shader owner, string name, int uniformLocation)
{
Owner = owner;
Name = name;
Location = uniformLocation;
}
public void UpdateValue(ref T newValue)
{
if (newValue.Equals(val))
return;
val= newValue;
HasChanged = true;
if (Owner.IsBound)
Update();
}
public void Update()
{
if (!HasChanged) return;
GLWrapper.SetUniform(this);
HasChanged = false;
}
ref T IUniformWithValue<T>.GetValueByRef() => ref val;
T IUniformWithValue<T>.GetValue() => val;
}
}
| mit | C# |
bae2c06de47d07ed2969b3d19b496d1edb42e42d | Bump version and copyright year | nmaier/simpleDLNA,bra1nb3am3r/simpleDLNA,antonio-bakula/simpleDLNA | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("Nils Maier")]
[assembly: AssemblyProduct("SimpleDLNA")]
[assembly: AssemblyCopyright("Copyright © 2012-2015s Nils Maier")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.1.*")]
[assembly: AssemblyInformationalVersion("1.1")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: CLSCompliant(true)]
| using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("Nils Maier")]
[assembly: AssemblyProduct("SimpleDLNA")]
[assembly: AssemblyCopyright("Copyright © 2012-2014 Nils Maier")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyInformationalVersion("1.0")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: CLSCompliant(true)]
| bsd-2-clause | C# |
b62981ee820a272b6840acc20512843b069833e8 | Remove filepath non-null constraint. | Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver | src/AsmResolver/IO/ByteArrayInputFile.cs | src/AsmResolver/IO/ByteArrayInputFile.cs | using System;
using System.IO;
namespace AsmResolver.IO
{
/// <summary>
/// Represents a file for which the data is represented by a byte array.
/// </summary>
public sealed class ByteArrayInputFile : IInputFile
{
private readonly ByteArrayDataSource _dataSource;
/// <summary>
/// Creates a new file for the provided file path.
/// </summary>
/// <param name="filePath">The file path.</param>
public ByteArrayInputFile(string filePath)
: this(filePath, File.ReadAllBytes(filePath), 0)
{
}
/// <summary>
/// Creates a new file for the provided file path and raw contents.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <param name="data">The byte array to read from.</param>
/// <param name="baseAddress">The base address to use.</param>
public ByteArrayInputFile(string filePath, byte[] data, ulong baseAddress)
{
FilePath = filePath;
_dataSource = new ByteArrayDataSource(data, baseAddress);
}
/// <inheritdoc />
public string FilePath
{
get;
}
/// <inheritdoc />
public uint Length => (uint) _dataSource.Length;
/// <summary>
/// Constructs a new binary stream reader on the provided byte array.
/// </summary>
/// <param name="data">The byte array to read.</param>
/// <returns>The stream reader.</returns>
public static BinaryStreamReader CreateReader(byte[] data) =>
new(new ByteArrayDataSource(data), 0, 0, (uint) data.Length);
/// <inheritdoc />
public BinaryStreamReader CreateReader(ulong address, uint rva, uint length) =>
new(_dataSource, address, rva, length);
/// <inheritdoc />
void IDisposable.Dispose()
{
}
}
}
| using System;
using System.IO;
namespace AsmResolver.IO
{
/// <summary>
/// Represents a file for which the data is represented by a byte array.
/// </summary>
public sealed class ByteArrayInputFile : IInputFile
{
private readonly ByteArrayDataSource _dataSource;
/// <summary>
/// Creates a new file for the provided file path.
/// </summary>
/// <param name="filePath">The file path.</param>
public ByteArrayInputFile(string filePath)
: this(filePath, File.ReadAllBytes(filePath), 0)
{
}
/// <summary>
/// Creates a new file for the provided file path and raw contents.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <param name="data">The byte array to read from.</param>
/// <param name="baseAddress">The base address to use.</param>
public ByteArrayInputFile(string filePath, byte[] data, ulong baseAddress)
{
FilePath = filePath ?? throw new ArgumentNullException(nameof(filePath));
_dataSource = new ByteArrayDataSource(data, baseAddress);
}
/// <inheritdoc />
public string FilePath
{
get;
}
/// <inheritdoc />
public uint Length => (uint) _dataSource.Length;
/// <summary>
/// Constructs a new binary stream reader on the provided byte array.
/// </summary>
/// <param name="data">The byte array to read.</param>
/// <returns>The stream reader.</returns>
public static BinaryStreamReader CreateReader(byte[] data) =>
new(new ByteArrayDataSource(data), 0, 0, (uint) data.Length);
/// <inheritdoc />
public BinaryStreamReader CreateReader(ulong address, uint rva, uint length) =>
new(_dataSource, address, rva, length);
/// <inheritdoc />
void IDisposable.Dispose()
{
}
}
}
| mit | C# |
643efbe660b2df96b9b29c338e0a84e2dbabd816 | Change version on Binding redirects | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | tooling/Microsoft.VisualStudio.RazorExtension/Properties/BindingRedirectAttributes.cs | tooling/Microsoft.VisualStudio.RazorExtension/Properties/BindingRedirectAttributes.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Mvc.Razor.Extensions",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.1.0.0",
NewVersion = "2.1.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Razor.Language",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.1.0.0",
NewVersion = "2.1.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.CodeAnalysis.Razor",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.1.0.0",
NewVersion = "2.1.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.CodeAnalysis.Razor.Workspaces",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.1.0.0",
NewVersion = "2.1.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.CodeAnalysis.Remote.Razor",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.1.0.0",
NewVersion = "2.1.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.LanguageServices.Razor",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.1.0.0",
NewVersion = "2.1.0.0")] | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Mvc.Razor.Extensions",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.0.0.0",
NewVersion = "2.0.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Razor.Language",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.0.0.0",
NewVersion = "2.0.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.CodeAnalysis.Razor",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.0.0.0",
NewVersion = "2.0.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.CodeAnalysis.Razor.Workspaces",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.0.0.0",
NewVersion = "2.0.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.CodeAnalysis.Remote.Razor",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.0.0.0",
NewVersion = "2.0.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.LanguageServices.Razor",
GenerateCodeBase = true,
PublicKeyToken = "adb9793829ddae60",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "2.0.0.0",
NewVersion = "2.0.0.0")] | apache-2.0 | C# |
a18342b7e00c28af04ee650dbc352396e7eedb64 | Append version number to title | maxinfet/FlaUI,Roemer/FlaUI | src/FlaUInspect/Views/MainWindow.xaml.cs | src/FlaUInspect/Views/MainWindow.xaml.cs | using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using FlaUInspect.ViewModels;
namespace FlaUInspect.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
AppendVersionToTitle();
Height = 550;
Width = 700;
Loaded += MainWindow_Loaded;
_vm = new MainViewModel();
DataContext = _vm;
}
private void AppendVersionToTitle()
{
var attr = Assembly.GetEntryAssembly().GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute;
if (attr != null)
{
Title += " v" + attr.InformationalVersion;
}
}
private void MainWindow_Loaded(object sender, System.EventArgs e)
{
if (!_vm.IsInitialized)
{
var dlg = new ChooseVersionWindow { Owner = this };
if (dlg.ShowDialog() != true)
{
Close();
}
_vm.Initialize(dlg.SelectedAutomationType);
Loaded -= MainWindow_Loaded;
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void TreeViewSelectedHandler(object sender, RoutedEventArgs e)
{
var item = sender as TreeViewItem;
if (item != null)
{
item.BringIntoView();
e.Handled = true;
}
}
}
}
| using System.Windows;
using System.Windows.Controls;
using FlaUInspect.ViewModels;
namespace FlaUInspect.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly MainViewModel _vm;
public MainWindow()
{
InitializeComponent();
Height = 550;
Width = 700;
Loaded += MainWindow_Loaded;
_vm = new MainViewModel();
DataContext = _vm;
}
private void MainWindow_Loaded(object sender, System.EventArgs e)
{
if (!_vm.IsInitialized)
{
var dlg = new ChooseVersionWindow { Owner = this };
if (dlg.ShowDialog() != true)
{
Close();
}
_vm.Initialize(dlg.SelectedAutomationType);
Loaded -= MainWindow_Loaded;
}
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void TreeViewSelectedHandler(object sender, RoutedEventArgs e)
{
var item = sender as TreeViewItem;
if (item != null)
{
item.BringIntoView();
e.Handled = true;
}
}
}
}
| mit | C# |
d9d52dc8eae5fca9bb24d831fa8f05b2a0ae705f | Fix blog pathing | PioneerCode/pioneer-blog,PioneerCode/pioneer-blog,PioneerCode/pioneer-blog,PioneerCode/pioneer-blog | src/Pioneer.Blog/Views/Post/Index.cshtml | src/Pioneer.Blog/Views/Post/Index.cshtml | @{
Layout = "~/Views/Post/_Template.cshtml";
ViewBag.Title = Model[(int)PreviousCurrentNextPosition.Current].Title;
}
@using Microsoft.AspNetCore.Mvc.Rendering
@model List<Post>
<article class="post">
<section class="hero-gradient hg-large" style="background-image: url(/blogs/@Model[(int)PreviousCurrentNextPosition.Current].Url/@Model[(int)PreviousCurrentNextPosition.Current].Image)">
<div class="row hero-gradient-content">
<div class="large-12 columns">
<h1 class="hero-gradient-title">
@Model[(int)PreviousCurrentNextPosition.Current].Title
</h1>
<div class="image-box">
<a href="https://twitter.com/chad_ramos" title="Chad Ramos Twitter" target="_blank" class="name">
By:
Chad Ramos
</a>
</div>
</div>
</div>
</section>
@Html.Partial("_MetaData", Model[(int)PreviousCurrentNextPosition.Current])
<div class="row">
<div class="large-10 large-push-1 columns">
@Html.Raw(Model[(int)PreviousCurrentNextPosition.Current].Article.Content)
@Html.Partial("_SocialShareIcons", Model[(int)PreviousCurrentNextPosition.Current])
</div>
</div>
@Html.Partial("_PreviousNext")
<footer>
<div class="row">
<div class="large-12 columns">
@Html.Partial("_FooterSectionTitle", "Author")
@Html.Partial("_FooterAuthor")
@Html.Partial("_FooterSectionTitle", "Popular Posts")
@Html.Partial("_FooterPopularPosts")
@Html.Partial("_FooterComments", Model[(int)PreviousCurrentNextPosition.Current])
</div>
</div>
</footer>
</article>
<script id="dsq-count-scr" src="@Url.Content("//" + AppConfiguration.Value.DisqusShortname + ".disqus.com/count.js")" async></script> | @{
Layout = "~/Views/Post/_Template.cshtml";
ViewBag.Title = Model[(int)PreviousCurrentNextPosition.Current].Title;
}
@using System.Collections.Generic
@using Microsoft.AspNetCore.Mvc.Rendering
@model List<Post>
<article class="post">
<section class="hero-gradient hg-large" style="background-image: url(@Model[(int)PreviousCurrentNextPosition.Current].Image)">
<div class="row hero-gradient-content">
<div class="large-12 columns">
<h1 class="hero-gradient-title">
@Model[(int)PreviousCurrentNextPosition.Current].Title
</h1>
<div class="image-box">
<a href="https://twitter.com/chad_ramos" title="Chad Ramos Twitter" target="_blank" class="name">
By:
Chad Ramos
</a>
</div>
</div>
</div>
</section>
@Html.Partial("_MetaData", Model[(int)PreviousCurrentNextPosition.Current])
<div class="row">
<div class="large-10 large-push-1 columns">
@Html.Raw(Model[(int)PreviousCurrentNextPosition.Current].Article.Content)
@Html.Partial("_SocialShareIcons", Model[(int)PreviousCurrentNextPosition.Current])
</div>
</div>
@Html.Partial("_PreviousNext")
<footer>
<div class="row">
<div class="large-12 columns">
@Html.Partial("_FooterSectionTitle", "Author")
@Html.Partial("_FooterAuthor")
@Html.Partial("_FooterSectionTitle", "Popular Posts")
@Html.Partial("_FooterPopularPosts")
@Html.Partial("_FooterComments", Model[(int)PreviousCurrentNextPosition.Current])
</div>
</div>
</footer>
</article>
<script id="dsq-count-scr" src="@Url.Content("//" + AppConfiguration.Value.DisqusShortname + ".disqus.com/count.js")" async></script> | mit | C# |
5ddf54bb533dc353e17be3101b32493ffb056d6c | fix enumerator (#1744) | AntShares/AntShares | src/neo/SmartContract/ApplicationEngine.Enumerator.cs | src/neo/SmartContract/ApplicationEngine.Enumerator.cs | using Neo.SmartContract.Enumerators;
using Neo.SmartContract.Iterators;
using Neo.VM.Types;
using System;
using Array = Neo.VM.Types.Array;
namespace Neo.SmartContract
{
partial class ApplicationEngine
{
public static readonly InteropDescriptor System_Enumerator_Create = Register("System.Enumerator.Create", nameof(CreateEnumerator), 0_00000400, TriggerType.All, CallFlags.None, false);
public static readonly InteropDescriptor System_Enumerator_Next = Register("System.Enumerator.Next", nameof(EnumeratorNext), 0_01000000, TriggerType.All, CallFlags.None, false);
public static readonly InteropDescriptor System_Enumerator_Value = Register("System.Enumerator.Value", nameof(EnumeratorValue), 0_00000400, TriggerType.All, CallFlags.None, false);
public static readonly InteropDescriptor System_Enumerator_Concat = Register("System.Enumerator.Concat", nameof(ConcatEnumerators), 0_00000400, TriggerType.All, CallFlags.None, false);
internal IEnumerator CreateEnumerator(StackItem item)
{
return item switch
{
Array array => new ArrayWrapper(array),
VM.Types.Buffer buffer => new ByteArrayWrapper(buffer),
PrimitiveType primitive => new ByteArrayWrapper(primitive),
_ => throw new ArgumentException()
};
}
internal bool EnumeratorNext(IEnumerator enumerator)
{
return enumerator.Next();
}
internal StackItem EnumeratorValue(IEnumerator enumerator)
{
return enumerator.Value();
}
internal IEnumerator ConcatEnumerators(IEnumerator first, IEnumerator second)
{
return new ConcatenatedEnumerator(first, second);
}
}
}
| using Neo.SmartContract.Enumerators;
using Neo.SmartContract.Iterators;
using Neo.VM.Types;
using System;
using Array = Neo.VM.Types.Array;
namespace Neo.SmartContract
{
partial class ApplicationEngine
{
public static readonly InteropDescriptor System_Enumerator_Create = Register("System.Enumerator.Create", nameof(CreateEnumerator), 0_00000400, TriggerType.All, CallFlags.None, false);
public static readonly InteropDescriptor System_Enumerator_Next = Register("System.Enumerator.Next", nameof(EnumeratorNext), 0_01000000, TriggerType.All, CallFlags.None, false);
public static readonly InteropDescriptor System_Enumerator_Value = Register("System.Enumerator.Value", nameof(EnumeratorValue), 0_00000400, TriggerType.All, CallFlags.None, false);
public static readonly InteropDescriptor System_Enumerator_Concat = Register("System.Enumerator.Concat", nameof(ConcatEnumerators), 0_00000400, TriggerType.All, CallFlags.None, false);
internal IEnumerator CreateEnumerator(StackItem item)
{
return item switch
{
Array array => new ArrayWrapper(array),
PrimitiveType primitive => new ByteArrayWrapper(primitive),
_ => throw new ArgumentException()
};
}
internal bool EnumeratorNext(IEnumerator enumerator)
{
return enumerator.Next();
}
internal StackItem EnumeratorValue(IEnumerator enumerator)
{
return enumerator.Value();
}
internal IEnumerator ConcatEnumerators(IEnumerator first, IEnumerator second)
{
return new ConcatenatedEnumerator(first, second);
}
}
}
| mit | C# |
cee7c6219e008ddb0bf108b1313e594e2c0f67dc | Make TrackManager implement IResourceStore | EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework | osu.Framework/Audio/Track/TrackManager.cs | osu.Framework/Audio/Track/TrackManager.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.IO;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Framework.Audio.Track
{
public class TrackManager : AudioCollectionManager<Track>, IResourceStore<Track>
{
private readonly IResourceStore<byte[]> store;
public TrackManager(IResourceStore<byte[]> store)
{
this.store = store;
}
public Track Get(string name)
{
if (string.IsNullOrEmpty(name)) return null;
var dataStream = store.GetStream(name);
if (dataStream == null)
return null;
Track track = new TrackBass(dataStream);
AddItem(track);
return track;
}
public Task<Track> GetAsync(string name) => Task.Run(() => Get(name));
public Stream GetStream(string name) => store.GetStream(name);
}
}
| // 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.IO.Stores;
namespace osu.Framework.Audio.Track
{
public class TrackManager : AudioCollectionManager<Track>
{
private readonly IResourceStore<byte[]> store;
public TrackManager(IResourceStore<byte[]> store)
{
this.store = store;
}
public Track Get(string name)
{
if (string.IsNullOrEmpty(name)) return null;
var dataStream = store.GetStream(name);
if (dataStream == null)
return null;
Track track = new TrackBass(dataStream);
AddItem(track);
return track;
}
}
}
| mit | C# |
de1715b760ce03098a55adedef7c3a60994c8c3c | modify exensions | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | src/Cap.Consistency.EntityFrameworkCore/ConsistencyEntityFrameworkBuilderExtensions.cs | src/Cap.Consistency.EntityFrameworkCore/ConsistencyEntityFrameworkBuilderExtensions.cs | using System;
using System.Reflection;
using Cap.Consistency;
using Cap.Consistency.EntityFrameworkCore;
using Cap.Consistency.Infrastructure;
using Microsoft.EntityFrameworkCore;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// Contains extension methods to <see cref="ConsistencyBuilder"/> for adding entity framework stores.
/// </summary>
public static class ConsistencyEntityFrameworkBuilderExtensions
{
/// <summary>
/// Adds an Entity Framework implementation of message stores.
/// </summary>
/// <typeparam name="TContext">The Entity Framework database context to use.</typeparam>
/// <param name="builder">The <see cref="ConsistencyBuilder"/> instance this method extends.</param>
/// <returns>The <see cref="ConsistencyBuilder"/> instance this method extends.</returns>
public static ConsistencyBuilder AddEntityFrameworkStores<TContext>(this ConsistencyBuilder builder)
where TContext : DbContext {
builder.Services.AddScoped(typeof(IConsistencyMessageStore<>).MakeGenericType(builder.MessageType),
typeof(ConsistencyMessageStore<,>).MakeGenericType(typeof(ConsistencyMessage), typeof(TContext)));
return builder;
}
private static TypeInfo FindGenericBaseType(Type currentType, Type genericBaseType) {
var type = currentType.GetTypeInfo();
while (type.BaseType != null) {
type = type.BaseType.GetTypeInfo();
var genericType = type.IsGenericType ? type.GetGenericTypeDefinition() : null;
if (genericType != null && genericType == genericBaseType) {
return type;
}
}
return null;
}
}
} | using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Cap.Consistency.EntityFrameworkCore
{
/// <summary>
/// Contains extension methods to <see cref="ConsistencyBuilder"/> for adding entity framework stores.
/// </summary>
public static class ConsistencyEntityFrameworkBuilderExtensions
{
/// <summary>
/// Adds an Entity Framework implementation of message stores.
/// </summary>
/// <typeparam name="TContext">The Entity Framework database context to use.</typeparam>
/// <param name="builder">The <see cref="ConsistencyBuilder"/> instance this method extends.</param>
/// <returns>The <see cref="ConsistencyBuilder"/> instance this method extends.</returns>
public static ConsistencyBuilder AddEntityFrameworkStores<TContext>(this ConsistencyBuilder builder)
where TContext : DbContext {
builder.Services.TryAdd(GetDefaultServices(builder.MessageType, typeof(TContext)));
return builder;
}
/// <summary>
/// Adds an Entity Framework implementation of message stores.
/// </summary>
/// <typeparam name="TContext">The Entity Framework database context to use.</typeparam>
/// <typeparam name="TKey">The type of the primary key used for the users and roles.</typeparam>
/// <param name="builder">The <see cref="ConsistencyBuilder"/> instance this method extends.</param>
/// <returns>The <see cref="ConsistencyBuilder"/> instance this method extends.</returns>
public static ConsistencyBuilder AddEntityFrameworkStores<TContext, TKey>(this ConsistencyBuilder builder)
where TContext : DbContext
where TKey : IEquatable<TKey> {
builder.Services.TryAdd(GetDefaultServices(builder.MessageType, typeof(TContext), typeof(TKey)));
return builder;
}
private static IServiceCollection GetDefaultServices(Type messageType, Type contextType, Type keyType = null) {
Type messageStoreType;
keyType = keyType ?? typeof(string);
messageStoreType = typeof(IConsistencyMessageStore<>).MakeGenericType(messageType, contextType, keyType);
var services = new ServiceCollection();
services.AddScoped(
typeof(IConsistencyMessageStore<>).MakeGenericType(messageStoreType),
messageStoreType);
return services;
}
}
} | mit | C# |
3df4cbca2cfd09d81226b530f96fba6a5588e2a9 | Reduce precision of difficulty calculator tests | NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu-new,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game/Tests/Beatmaps/DifficultyCalculatorTest.cs | osu.Game/Tests/Beatmaps/DifficultyCalculatorTest.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.IO;
using System.Reflection;
using NUnit.Framework;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Tests.Beatmaps
{
[TestFixture]
public abstract class DifficultyCalculatorTest
{
private const string resource_namespace = "Testing.Beatmaps";
protected abstract string ResourceAssembly { get; }
protected void Test(double expected, string name, params Mod[] mods)
{
// Platform-dependent math functions (Pow, Cbrt, Exp, etc) may result in minute differences.
Assert.That(CreateDifficultyCalculator(getBeatmap(name)).Calculate(mods).StarRating, Is.EqualTo(expected).Within(0.00001));
}
private WorkingBeatmap getBeatmap(string name)
{
using (var resStream = openResource($"{resource_namespace}.{name}.osu"))
using (var stream = new LineBufferedReader(resStream))
{
var decoder = Decoder.GetDecoder<Beatmap>(stream);
((LegacyBeatmapDecoder)decoder).ApplyOffsets = false;
return new TestWorkingBeatmap(decoder.Decode(stream))
{
BeatmapInfo =
{
Ruleset = CreateRuleset().RulesetInfo
}
};
}
}
private Stream openResource(string name)
{
var localPath = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path)).AsNonNull();
return Assembly.LoadFrom(Path.Combine(localPath, $"{ResourceAssembly}.dll")).GetManifestResourceStream($@"{ResourceAssembly}.Resources.{name}");
}
protected abstract DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap);
protected abstract Ruleset CreateRuleset();
}
}
| // 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.IO;
using System.Reflection;
using NUnit.Framework;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
namespace osu.Game.Tests.Beatmaps
{
[TestFixture]
public abstract class DifficultyCalculatorTest
{
private const string resource_namespace = "Testing.Beatmaps";
protected abstract string ResourceAssembly { get; }
protected void Test(double expected, string name, params Mod[] mods)
=> Assert.AreEqual(expected, CreateDifficultyCalculator(getBeatmap(name)).Calculate(mods).StarRating);
private WorkingBeatmap getBeatmap(string name)
{
using (var resStream = openResource($"{resource_namespace}.{name}.osu"))
using (var stream = new LineBufferedReader(resStream))
{
var decoder = Decoder.GetDecoder<Beatmap>(stream);
((LegacyBeatmapDecoder)decoder).ApplyOffsets = false;
return new TestWorkingBeatmap(decoder.Decode(stream))
{
BeatmapInfo =
{
Ruleset = CreateRuleset().RulesetInfo
}
};
}
}
private Stream openResource(string name)
{
var localPath = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(Assembly.GetExecutingAssembly().CodeBase).Path)).AsNonNull();
return Assembly.LoadFrom(Path.Combine(localPath, $"{ResourceAssembly}.dll")).GetManifestResourceStream($@"{ResourceAssembly}.Resources.{name}");
}
protected abstract DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap);
protected abstract Ruleset CreateRuleset();
}
}
| mit | C# |
a2239381d41dd4974bf74dbb7860909320f6029b | Rename tests | dotnet/roslyn-analyzers,dotnet/roslyn-analyzers,pakdev/roslyn-analyzers,pakdev/roslyn-analyzers,mavasani/roslyn-analyzers,mavasani/roslyn-analyzers | src/Roslyn.Diagnostics.Analyzers/UnitTests/AvoidOptSuffixForNullableEnableCodeTests.cs | src/Roslyn.Diagnostics.Analyzers/UnitTests/AvoidOptSuffixForNullableEnableCodeTests.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Roslyn.Diagnostics.CSharp.Analyzers.CSharpAvoidOptSuffixForNullableEnableCode,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Roslyn.Diagnostics.Analyzers.UnitTests
{
public class AvoidOptSuffixForNullableEnableCodeTests
{
[Fact]
public async Task RS0042_CSharp8_NullableEnabledCode_Diagnostic()
{
await new VerifyCS.Test
{
TestCode =
@"
#nullable enable
public class Class1
{
private Class1? _instanceOpt;
public void Method1(string? sOpt)
{
}
}",
LanguageVersion = LanguageVersion.CSharp8
}.RunAsync();
}
[Fact]
public async Task RS0042_CSharp8_NonNullableEnabledCode_NoDiagnostic()
{
await new VerifyCS.Test
{
TestCode =
@"
public class Class1
{
private Class1? _instanceOpt;
public void Method1(string? sOpt)
{
}
}",
LanguageVersion = LanguageVersion.CSharp8
}.RunAsync();
}
[Fact]
public async Task RS0042_PriorToCSharp8_NoDiagnostic()
{
await new VerifyCS.Test
{
TestCode =
@"
public class Class1
{
private Class1 _instanceOpt;
public void Method1(string sOpt)
{
}
}",
LanguageVersion = LanguageVersion.CSharp7_3
}.RunAsync();
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Roslyn.Diagnostics.CSharp.Analyzers.CSharpAvoidOptSuffixForNullableEnableCode,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Roslyn.Diagnostics.Analyzers.UnitTests
{
public class AvoidOptSuffixForNullableEnableCodeTests
{
[Fact]
public async Task RS0037_CSharp8_NullableEnabledCode_Diagnostic()
{
await new VerifyCS.Test
{
TestCode =
@"
#nullable enable
public class Class1
{
private Class1? _instanceOpt;
public void Method1(string? sOpt)
{
}
}",
LanguageVersion = LanguageVersion.CSharp8
}.RunAsync();
}
[Fact]
public async Task RS0037_CSharp8_NonNullableEnabledCode_NoDiagnostic()
{
await new VerifyCS.Test
{
TestCode =
@"
public class Class1
{
private Class1? _instanceOpt;
public void Method1(string? sOpt)
{
}
}",
LanguageVersion = LanguageVersion.CSharp8
}.RunAsync();
}
[Fact]
public async Task RS0037_PriorToCSharp8_NoDiagnostic()
{
await new VerifyCS.Test
{
TestCode =
@"
public class Class1
{
private Class1 _instanceOpt;
public void Method1(string sOpt)
{
}
}",
LanguageVersion = LanguageVersion.CSharp7_3
}.RunAsync();
}
}
}
| mit | C# |
d15b3bdd0453fa1a66e97e5ee06778d5c4e9c1fa | remove implicit conversion because its confusing an error prone | akatakritos/SassSharp | SassSharp/Selector.cs | SassSharp/Selector.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SassSharp
{
public struct Selector : IEquatable<Selector>
{
public string Value { get; private set; }
public Selector(string selector)
: this()
{
Value = selector;
}
public Selector DescendFrom(Selector parent)
{
return new Selector(parent.Value + " " + this.Value);
}
public override string ToString()
{
return Value;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public bool Equals(Selector other)
{
return this.Value == other.Value;
}
public override bool Equals(object other)
{
if (other is Selector)
return this.Equals((Selector)other);
else
return false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SassSharp
{
public struct Selector : IEquatable<Selector>
{
public string Value { get; private set; }
public Selector(string selector)
: this()
{
Value = selector;
}
public Selector DescendFrom(Selector parent)
{
return new Selector(parent.Value + " " + this.Value);
}
public static implicit operator String(Selector s)
{
return s.Value;
}
public static implicit operator Selector(string s)
{
return new Selector(s);
}
public override string ToString()
{
return Value;
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
public bool Equals(Selector other)
{
if (other == null)
return false;
return this.Value == other.Value;
}
public override bool Equals(object other)
{
if (other is Selector)
return this.Equals((Selector)other);
else
return false;
}
}
}
| mit | C# |
5a81a0437a4b57952bdbe23fea2c854bddacb042 | Fix MicrogameTraitsSingleScene | Barleytree/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Scripts/Microgame/MicrogameTraitsSingleScene.cs | Assets/Scripts/Microgame/MicrogameTraitsSingleScene.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Microgame Traits/Traits (Single Scene)")]
public class MicrogameTraitsSingleScene : MicrogameTraits
{
public override bool SceneDeterminesDifficulty => false;
public override string GetSceneName(MicrogameSession session) => session.MicrogameId;
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Microgame Traits/Traits (Single Scene)")]
public class MicrogameTraitsSingleScene : MicrogameTraits
{
public string commandKeySuffix;
[SerializeField]
private DifficultyCommand difficulty1;
[SerializeField]
private DifficultyCommand difficulty2;
[SerializeField]
private DifficultyCommand difficulty3;
[System.Serializable]
public class DifficultyCommand
{
public string commandKeySuffix;
public string defaultValue;
}
public override string GetLocalizedCommand(MicrogameSession session)
{
var difficulty = new DifficultyCommand[] { null, difficulty1, difficulty2, difficulty3 }[session.Difficulty];
return TextHelper.getLocalizedText("microgame." + session.MicrogameId + ".command" + difficulty.commandKeySuffix, difficulty.defaultValue);
}
}
| mit | C# |
90354ec107ee66b7134b38bdfcd7b534893948b5 | Refactor Dynamic Document clone | ajlopez/SharpMongo | Src/SharpMongo.Core/DynamicDocument.cs | Src/SharpMongo.Core/DynamicDocument.cs | namespace SharpMongo.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DynamicDocument : DynamicObject
{
public DynamicDocument(params object[] arguments)
: base(arguments)
{
}
internal DynamicDocument(IDictionary<string, object> values)
: base(values)
{
}
public object Id
{
get
{
return this.GetMember("Id");
}
set
{
this.SetMember("Id", value);
}
}
public DynamicDocument Clone()
{
var newdocument = new DynamicDocument();
newdocument.Update(this);
return newdocument;
}
}
}
| namespace SharpMongo.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class DynamicDocument : DynamicObject
{
public DynamicDocument(params object[] arguments)
: base(arguments)
{
}
internal DynamicDocument(IDictionary<string, object> values)
: base(values)
{
}
public object Id
{
get
{
return this.GetMember("Id");
}
set
{
this.SetMember("Id", value);
}
}
public DynamicDocument Clone()
{
return new DynamicDocument(this.values);
}
}
}
| mit | C# |
90c75a64cf9e30e213821706e8d54de262d2b629 | Fix legacy control point precision having an adverse effect on the editor | peppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu | osu.Game/Screens/Edit/Timing/DifficultySection.cs | osu.Game/Screens/Edit/Timing/DifficultySection.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable,
KeyboardStep = 0.1f
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
var selectedPointBindable = point.NewValue.SpeedMultiplierBindable;
// there may be legacy control points, which contain infinite precision for compatibility reasons (see LegacyDifficultyControlPoint).
// generally that level of precision could only be set by externally editing the .osu file, so at the point
// a user is looking to update this within the editor it should be safe to obliterate this additional precision.
double expectedPrecision = new DifficultyControlPoint().SpeedMultiplierBindable.Precision;
if (selectedPointBindable.Precision < expectedPrecision)
selectedPointBindable.Precision = expectedPrecision;
multiplierSlider.Current = selectedPointBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Game.Beatmaps.ControlPoints;
namespace osu.Game.Screens.Edit.Timing
{
internal class DifficultySection : Section<DifficultyControlPoint>
{
private SliderWithTextBoxInput<double> multiplierSlider;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new[]
{
multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier")
{
Current = new DifficultyControlPoint().SpeedMultiplierBindable,
KeyboardStep = 0.1f
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point)
{
if (point.NewValue != null)
{
multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable;
multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override DifficultyControlPoint CreatePoint()
{
var reference = Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time);
return new DifficultyControlPoint
{
SpeedMultiplier = reference.SpeedMultiplier,
};
}
}
}
| mit | C# |
d6fce070c2591858ce190d40a1781651df44ebac | Add tag replacement on backup paths | 15below/Ensconce,BlythMeister/Ensconce,15below/Ensconce,BlythMeister/Ensconce | src/Ensconce.Console/Backup.cs | src/Ensconce.Console/Backup.cs | using System.IO;
using System.IO.Compression;
namespace Ensconce.Console
{
internal static class Backup
{
internal static void DoBackup()
{
var backupSource = Arguments.BackupSource.Render();
var backupDestination = Arguments.BackupDestination.Render();
if (File.Exists(backupDestination) && Arguments.BackupOverwrite)
{
File.Delete(backupDestination);
}
ZipFile.CreateFromDirectory(backupSource, backupDestination, CompressionLevel.Optimal, false);
}
}
}
| using System.IO;
using System.IO.Compression;
namespace Ensconce.Console
{
internal static class Backup
{
internal static void DoBackup()
{
if (File.Exists(Arguments.BackupDestination) && Arguments.BackupOverwrite)
{
File.Delete(Arguments.BackupDestination);
}
ZipFile.CreateFromDirectory(Arguments.BackupSource, Arguments.BackupDestination, CompressionLevel.Optimal, false);
}
}
}
| mit | C# |
bbee11afd1141e20a0d28e9c33026d742648651d | Resolve potential breaking change for clients using ReleaseDate | scooper91/SevenDigital.Api.Schema,7digital/SevenDigital.Api.Schema | src/Schema/Releases/Release.cs | src/Schema/Releases/Release.cs | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Artists;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.Legacy;
using SevenDigital.Api.Schema.Media;
using SevenDigital.Api.Schema.Packages;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
using SevenDigital.Api.Schema.Pricing;
namespace SevenDigital.Api.Schema.Releases
{
[Serializable]
[XmlRoot("release")]
[ApiEndpoint("release/details")]
public class Release : HasReleaseIdParameter
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("type")]
public ReleaseType Type { get; set; }
[XmlElement("barcode")]
public string Barcode { get; set; }
[XmlElement("year")]
public string Year { get; set; }
[XmlElement("explicitContent")]
public bool ExplicitContent { get; set; }
[XmlElement("artist")]
public Artist Artist { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("releaseDate")]
public DateTime? LegacyReleaseDate { get; set; }
[XmlIgnore]
public DateTime? ReleaseDate {
get { return Download != null ? Download.ReleaseDate : LegacyReleaseDate; }
}
[XmlElement("addedDate")]
public DateTime AddedDate { get; set; }
[XmlIgnore]
public bool AddedDateSpecified { get { return AddedDate > DateTime.MinValue; } }
[Obsolete]
public Price Price { get { return PriceLegacyMapper.PrimaryPackagePrice(Download); } }
[Obsolete]
public FormatList Formats { get { return FormatLegacyMapper.PrimaryPackageFormats(Download); } }
[XmlElement("label")]
public Label Label { get; set; }
[XmlElement("licensor")]
public Licensor Licensor { get; set; }
[XmlElement("streamingReleaseDate")]
public DateTime? StreamingReleaseDate { get; set; }
[XmlElement("duration")]
public int Duration { get; set; }
[XmlElement("trackCount")]
public int? TrackCount { get; set; }
[XmlElement("download")]
public Download Download { get; set; }
[XmlElement("subscriptionStreaming")]
public Streaming SubscriptionStreaming { get; set; }
[XmlElement("slug")]
public string Slug { get; set; }
public override string ToString()
{
return string.Format("{0}: {1} {2} {3}, Barcode {4}", Id, Title, Version, Type, Barcode);
}
}
} | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Artists;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.Legacy;
using SevenDigital.Api.Schema.Media;
using SevenDigital.Api.Schema.Packages;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
using SevenDigital.Api.Schema.Pricing;
namespace SevenDigital.Api.Schema.Releases
{
[Serializable]
[XmlRoot("release")]
[ApiEndpoint("release/details")]
public class Release : HasReleaseIdParameter
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("type")]
public ReleaseType Type { get; set; }
[XmlElement("barcode")]
public string Barcode { get; set; }
[XmlElement("year")]
public string Year { get; set; }
[XmlElement("explicitContent")]
public bool ExplicitContent { get; set; }
[XmlElement("artist")]
public Artist Artist { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("releaseDate")]
public DateTime? ReleaseDate { get; set; }
[XmlElement("addedDate")]
public DateTime AddedDate { get; set; }
[XmlIgnore]
public bool AddedDateSpecified { get { return AddedDate > DateTime.MinValue; } }
[Obsolete]
public Price Price { get { return PriceLegacyMapper.PrimaryPackagePrice(Download); } }
[Obsolete]
public FormatList Formats { get { return FormatLegacyMapper.PrimaryPackageFormats(Download); } }
[XmlElement("label")]
public Label Label { get; set; }
[XmlElement("licensor")]
public Licensor Licensor { get; set; }
[XmlElement("streamingReleaseDate")]
public DateTime? StreamingReleaseDate { get; set; }
[XmlElement("duration")]
public int Duration { get; set; }
[XmlElement("trackCount")]
public int? TrackCount { get; set; }
[XmlElement("download")]
public Download Download { get; set; }
[XmlElement("subscriptionStreaming")]
public Streaming SubscriptionStreaming { get; set; }
[XmlElement("slug")]
public string Slug { get; set; }
public override string ToString()
{
return string.Format("{0}: {1} {2} {3}, Barcode {4}", Id, Title, Version, Type, Barcode);
}
}
} | mit | C# |
d88649ecd2dbea412381a38cfcb4692fd166f13d | Increment projects copyright year to 2020 | atata-framework/atata-sample-app-tests | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2020")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Yevgeniy Shunevych")]
[assembly: AssemblyProduct("Atata Framework")]
[assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| apache-2.0 | C# |
6ecfa4b0658806b0478f6bc21744d4b1a4afeb9e | Remove unused using directive. | fhchina/elmah-mvc,jmptrader/elmah-mvc,alexbeletsky/elmah-mvc,mmsaffari/elmah-mvc | src/Elmah.Mvc/Settings.cs | src/Elmah.Mvc/Settings.cs | //
// ELMAH.Mvc
// Copyright (c) 2011 Atif Aziz, James Driscoll. All rights reserved.
//
// Author(s):
//
// James Driscoll
//
// 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.Configuration;
namespace Elmah.Mvc
{
internal class Settings
{
public static string AllowedRoles
{
get { return ConfigurationManager.AppSettings["elmah.mvc.allowedRoles"] ?? "*"; }
}
public static string AllowedUsers
{
get { return ConfigurationManager.AppSettings["elmah.mvc.allowedUsers"] ?? "*"; }
}
public static string Route
{
get { return ConfigurationManager.AppSettings["elmah.mvc.route"] ?? "elmah"; }
}
public static bool DisableHandleErrorFilter
{
get { return GetBoolValue("elmah.mvc.disableHandleErrorFilter", false); }
}
public static bool DisableHandler
{
get { return GetBoolValue("elmah.mvc.disableHandler", false); }
}
public static bool RequiresAuthentication
{
get { return GetBoolValue("elmah.mvc.requiresAuthentication", false); }
}
public static bool IgnoreDefaultRoute
{
get { return GetBoolValue("elmah.mvc.IgnoreDefaultRoute", false); }
}
public static bool UserAuthCaseSensitive
{
get
{
return GetBoolValue("elmah.mvc.UserAuthCaseSensitive", false);
}
}
private static bool GetBoolValue(string key, bool defaultValue)
{
var value = ConfigurationManager.AppSettings[key];
if (value == null)
return defaultValue;
bool returnValue;
if (!bool.TryParse(value, out returnValue))
return defaultValue;
return returnValue;
}
}
} | //
// ELMAH.Mvc
// Copyright (c) 2011 Atif Aziz, James Driscoll. All rights reserved.
//
// Author(s):
//
// James Driscoll
//
// 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.Configuration;
namespace Elmah.Mvc
{
internal class Settings
{
public static string AllowedRoles
{
get { return ConfigurationManager.AppSettings["elmah.mvc.allowedRoles"] ?? "*"; }
}
public static string AllowedUsers
{
get { return ConfigurationManager.AppSettings["elmah.mvc.allowedUsers"] ?? "*"; }
}
public static string Route
{
get { return ConfigurationManager.AppSettings["elmah.mvc.route"] ?? "elmah"; }
}
public static bool DisableHandleErrorFilter
{
get { return GetBoolValue("elmah.mvc.disableHandleErrorFilter", false); }
}
public static bool DisableHandler
{
get { return GetBoolValue("elmah.mvc.disableHandler", false); }
}
public static bool RequiresAuthentication
{
get { return GetBoolValue("elmah.mvc.requiresAuthentication", false); }
}
public static bool IgnoreDefaultRoute
{
get { return GetBoolValue("elmah.mvc.IgnoreDefaultRoute", false); }
}
public static bool UserAuthCaseSensitive
{
get
{
return GetBoolValue("elmah.mvc.UserAuthCaseSensitive", false);
}
}
private static bool GetBoolValue(string key, bool defaultValue)
{
var value = ConfigurationManager.AppSettings[key];
if (value == null)
return defaultValue;
bool returnValue;
if (!bool.TryParse(value, out returnValue))
return defaultValue;
return returnValue;
}
}
} | apache-2.0 | C# |
73a4e370a251e10e2186e4018387ef223d02c0e8 | Fix MonoTouch build | cwensley/maccore,jorik041/maccore,beni55/maccore,mono/maccore | src/Foundation/NSValue.cs | src/Foundation/NSValue.cs | //
// Copyright 2010, Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace MonoMac.Foundation {
public partial class NSValue : NSObject {
#if !COREBUILD
public string ObjCType {
get {
return Marshal.PtrToStringAnsi (ObjCTypePtr ());
}
}
#endif
}
}
| //
// Copyright 2010, Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
namespace MonoMac.Foundation {
public partial class NSValue : NSObject {
public string ObjCType {
get {
return Marshal.PtrToStringAnsi (ObjCTypePtr ());
}
}
}
}
| apache-2.0 | C# |
c85935783e8c55744ca3215a8dab65e8daa92ef3 | Add comment | 60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope | QueueDataGraphic/QueueDataGraphic/CSharpFiles/Debug.cs | QueueDataGraphic/QueueDataGraphic/CSharpFiles/Debug.cs | /********************************************************************
* Develop by Jimmy Hu *
* This program is licensed under the Apache License 2.0. *
* Debug.cs *
* 本檔案用於宣告偵錯相關工具物件 *
********************************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueDataGraphic.CSharpFiles
{
class Debug // Debug class, Debug類別
{ // Debug class start, 進入Debug類別
/// <summary>
/// DebugMode would be setted "true" during debugging.
/// 在偵錯模式中將DebugMode設為true
/// </summary>
public readonly static bool DebugMode = true;
} // Debug class eud, 結束Debug類別
}
| /********************************************************************
* Develop by Jimmy Hu *
* This program is licensed under the Apache License 2.0. *
* Debug.cs *
* 本檔案用於宣告偵錯相關工具物件 *
********************************************************************
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QueueDataGraphic.CSharpFiles
{
class Debug // Debug class, Debug類別
{ // Debug class start, 進入Debug類別
/// <summary>
/// DebugMode would be setted "true" during debugging.
/// 在偵錯模式中將DebugMode設為true
/// </summary>
public readonly static bool DebugMode = true;
}
}
| apache-2.0 | C# |
b28057a218daadb6a8cb9830f2ea616b6ea24d49 | Remove unreachable condition | bartdesmet/roslyn,mavasani/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,bartdesmet/roslyn | src/Features/CSharp/Portable/Completion/KeywordRecommenders/NameOfKeywordRecommender.cs | src/Features/CSharp/Portable/Completion/KeywordRecommenders/NameOfKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class NameOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public NameOfKeywordRecommender()
: base(SyntaxKind.NameOfKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsAnyExpressionContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.LeftToken.IsInCastExpressionTypeWhereExpressionIsMissingOrInNextLine();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class NameOfKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public NameOfKeywordRecommender()
: base(SyntaxKind.NameOfKeyword)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
context.IsAnyExpressionContext ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
IsAttributeArgumentContext(context) ||
context.LeftToken.IsInCastExpressionTypeWhereExpressionIsMissingOrInNextLine();
}
private static bool IsAttributeArgumentContext(CSharpSyntaxContext context)
{
return
context.IsAnyExpressionContext &&
context.LeftToken.GetAncestor<AttributeSyntax>() != null;
}
}
}
| mit | C# |
f48e1ef2c205aea5ab0901cc2bb470377f7bd2a3 | Move from ASCII to UTF-8 | sqt-android/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,olofd/google-api-dotnet-client,kekewong/google-api-dotnet-client,nicolasdavel/google-api-dotnet-client,ephraimncory/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,eydjey/google-api-dotnet-client,ajmal744/google-api-dotnet-client,jskeet/google-api-dotnet-client,neil-119/google-api-dotnet-client,karishmal/google-api-dotnet-client,PiRSquared17/google-api-dotnet-client,sawanmishra/google-api-dotnet-client,hurcane/google-api-dotnet-client,googleapis/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,hurcane/google-api-dotnet-client,DJJam/google-api-dotnet-client,inetdream/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,duckhamqng/google-api-dotnet-client,jesusog/google-api-dotnet-client,ajaypradeep/google-api-dotnet-client,pgallastegui/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,peleyal/google-api-dotnet-client,milkmeat/google-api-dotnet-client,initaldk/google-api-dotnet-client,kelvinRosa/google-api-dotnet-client,asifshaon/google-api-dotnet-client,rburgstaler/google-api-dotnet-client,smarly-net/google-api-dotnet-client,ErAmySharma/google-api-dotnet-client,neil-119/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,kapil-chauhan-ngi/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,hurcane/google-api-dotnet-client,eshivakant/google-api-dotnet-client,amit-learning/google-api-dotnet-client,shumaojie/google-api-dotnet-client,googleapis/google-api-dotnet-client,amitla/google-api-dotnet-client,googleapis/google-api-dotnet-client,Senthilvera/google-api-dotnet-client,joesoc/google-api-dotnet-client,bacm/google-api-dotnet-client,cdanielm58/google-api-dotnet-client,abujehad139/google-api-dotnet-client,mjacobsen4DFM/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,eshangin/google-api-dotnet-client,hurcane/google-api-dotnet-client,mylemans/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,liuqiaosz/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,peleyal/google-api-dotnet-client,arjunRanosys/google-api-dotnet-client,amitla/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,RavindraPatidar/google-api-dotnet-client,amnsinghl/google-api-dotnet-client,MesutGULECYUZ/google-api-dotnet-client,jskeet/google-api-dotnet-client,hoangduit/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,line21c/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,aoisensi/google-api-dotnet-client,SimonAntony/google-api-dotnet-client,jskeet/google-api-dotnet-client,aoisensi/google-api-dotnet-client,shumaojie/google-api-dotnet-client,ssett/google-api-dotnet-client,chenneo/google-api-dotnet-client,lli-klick/google-api-dotnet-client,maha-khedr/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,hivie7510/google-api-dotnet-client,peleyal/google-api-dotnet-client,MyOwnClone/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,luantn2/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,initaldk/google-api-dotnet-client,initaldk/google-api-dotnet-client | Src/GoogleApis/Apis/Discovery/StringDiscoveryDevice.cs | Src/GoogleApis/Apis/Discovery/StringDiscoveryDevice.cs | /*
Copyright 2010 Google 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.IO;
using System.Text;
using System.Net;
namespace Google.Apis.Discovery
{
/// <summary>
/// Hosts the DiscoveryDocument in a user defined stream.
///
/// Handy for testing.
/// </summary>
public class StringDiscoveryDevice: IDiscoveryDevice {
/// <summary>
/// The discovery document.
/// </summary>
public String Document {get;set;}
private Stream outputStream {get;set;}
/// <summary>
/// Fetches the Discovery Document from an user supplied string
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public Stream Fetch() {
byte[] text = Encoding.UTF8.GetBytes( Document );
outputStream = new MemoryStream(text);
return outputStream;
}
#region IDisposable implementation
public void Dispose ()
{
if(outputStream != null) {
outputStream.Dispose();
}
}
#endregion
}
}
| /*
Copyright 2010 Google 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.IO;
using System.Text;
using System.Net;
namespace Google.Apis.Discovery
{
/// <summary>
/// Hosts the DiscoveryDocument in a user defined stream.
///
/// Handy for testing.
/// </summary>
public class StringDiscoveryDevice: IDiscoveryDevice {
/// <summary>
/// The discovery document.
/// </summary>
public String Document {get;set;}
private Stream outputStream {get;set;}
/// <summary>
/// Fetches the Discovery Document from an user supplied string
/// </summary>
/// <returns>
/// A <see cref="System.String"/>
/// </returns>
public Stream Fetch() {
byte[] text = Encoding.ASCII.GetBytes( Document );
outputStream = new MemoryStream(text);
return outputStream;
}
#region IDisposable implementation
public void Dispose ()
{
if(outputStream != null) {
outputStream.Dispose();
}
}
#endregion
}
}
| apache-2.0 | C# |
2c0c4c00e873ba10b149786546c7b63152643595 | fix role creation | wilcommerce/Wilcommerce.Auth | src/Wilcommerce.Auth/Services/RoleFactory.cs | src/Wilcommerce.Auth/Services/RoleFactory.cs | using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Wilcommerce.Auth.Services.Interfaces;
namespace Wilcommerce.Auth.Services
{
/// <summary>
/// Implementation of <see cref="IRoleFactory"/>
/// </summary>
public class RoleFactory : IRoleFactory
{
private readonly RoleManager<IdentityRole> _roleManager;
/// <summary>
/// Construct the role factory
/// </summary>
/// <param name="roleManager">The role manager instance</param>
public RoleFactory(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager));
}
/// <summary>
/// Implementation of <see cref="IRoleFactory.Administrator"/>
/// </summary>
/// <returns></returns>
public virtual async Task<IdentityRole> Administrator()
{
return await CreateRoleIfNotExists(AuthenticationDefaults.AdministratorRole);
}
/// <summary>
/// Implementation of <see cref="IRoleFactory.Customer"/>
/// </summary>
/// <returns></returns>
public virtual async Task<IdentityRole> Customer()
{
return await CreateRoleIfNotExists(AuthenticationDefaults.CustomerRole);
}
#region Protected Methods
/// <summary>
/// Create the role with the specified name if not exists and returns it
/// </summary>
/// <param name="roleName">The role name</param>
/// <returns>The role instance</returns>
protected virtual async Task<IdentityRole> CreateRoleIfNotExists(string roleName)
{
var role = await _roleManager.FindByNameAsync(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
await _roleManager.CreateAsync(role);
}
return role;
}
#endregion
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Wilcommerce.Auth.Services.Interfaces;
namespace Wilcommerce.Auth.Services
{
/// <summary>
/// Implementation of <see cref="IRoleFactory"/>
/// </summary>
public class RoleFactory : IRoleFactory
{
private readonly RoleManager<IdentityRole> _roleManager;
/// <summary>
/// Construct the role factory
/// </summary>
/// <param name="roleManager">The role manager instance</param>
public RoleFactory(RoleManager<IdentityRole> roleManager)
{
_roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager));
}
/// <summary>
/// Implementation of <see cref="IRoleFactory.Administrator"/>
/// </summary>
/// <returns></returns>
public virtual async Task<IdentityRole> Administrator()
{
return await CreateRoleIfNotExists(AuthenticationDefaults.CustomerRole);
}
/// <summary>
/// Implementation of <see cref="IRoleFactory.Customer"/>
/// </summary>
/// <returns></returns>
public virtual async Task<IdentityRole> Customer()
{
return await CreateRoleIfNotExists(AuthenticationDefaults.CustomerRole);
}
#region Protected Methods
/// <summary>
/// Create the role with the specified name if not exists and returns it
/// </summary>
/// <param name="roleName">The role name</param>
/// <returns>The role instance</returns>
protected virtual async Task<IdentityRole> CreateRoleIfNotExists(string roleName)
{
var role = await _roleManager.FindByNameAsync(roleName);
if (role == null)
{
return new IdentityRole(roleName);
}
return role;
}
#endregion
}
}
| mit | C# |
3965b0703cacbdbf489138bdd8a9adfbff2d2012 | Create a Help section | awseward/Squirrel.Windows,bowencode/Squirrel.Windows,kenbailey/Squirrel.Windows,punker76/Squirrel.Windows,josenbo/Squirrel.Windows,aneeff/Squirrel.Windows,yovannyr/Squirrel.Windows,EdZava/Squirrel.Windows,JonMartinTx/AS400Report,markuscarlen/Squirrel.Windows,willdean/Squirrel.Windows,Squirrel/Squirrel.Windows,markuscarlen/Squirrel.Windows,flagbug/Squirrel.Windows,Suninus/Squirrel.Windows,airtimemedia/Squirrel.Windows,bowencode/Squirrel.Windows,ChaseFlorell/Squirrel.Windows,yovannyr/Squirrel.Windows,EdZava/Squirrel.Windows,sickboy/Squirrel.Windows,flagbug/Squirrel.Windows,airtimemedia/Squirrel.Windows,ruisebastiao/Squirrel.Windows,jochenvangasse/Squirrel.Windows,1gurucoder/Squirrel.Windows,BarryThePenguin/Squirrel.Windows,josenbo/Squirrel.Windows,cguedel/Squirrel.Windows,hammerandchisel/Squirrel.Windows,Squirrel/Squirrel.Windows,jbeshir/Squirrel.Windows,vaginessa/Squirrel.Windows,BloomBooks/Squirrel.Windows,punker76/Squirrel.Windows,Katieleeb84/Squirrel.Windows,EdZava/Squirrel.Windows,ChaseFlorell/Squirrel.Windows,willdean/Squirrel.Windows,hammerandchisel/Squirrel.Windows,ruisebastiao/Squirrel.Windows,awseward/Squirrel.Windows,airtimemedia/Squirrel.Windows,cguedel/Squirrel.Windows,jbeshir/Squirrel.Windows,Katieleeb84/Squirrel.Windows,BloomBooks/Squirrel.Windows,vaginessa/Squirrel.Windows,NeilSorensen/Squirrel.Windows,hammerandchisel/Squirrel.Windows,1gurucoder/Squirrel.Windows,flagbug/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,markwal/Squirrel.Windows,cguedel/Squirrel.Windows,jbeshir/Squirrel.Windows,awseward/Squirrel.Windows,jochenvangasse/Squirrel.Windows,sickboy/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,Suninus/Squirrel.Windows,ChaseFlorell/Squirrel.Windows,JonMartinTx/AS400Report,Suninus/Squirrel.Windows,josenbo/Squirrel.Windows,BloomBooks/Squirrel.Windows,allanrsmith/Squirrel.Windows,yovannyr/Squirrel.Windows,willdean/Squirrel.Windows,BarryThePenguin/Squirrel.Windows,aneeff/Squirrel.Windows,GeertvanHorrik/Squirrel.Windows,bowencode/Squirrel.Windows,JonMartinTx/AS400Report,markuscarlen/Squirrel.Windows,ruisebastiao/Squirrel.Windows,BarryThePenguin/Squirrel.Windows,sickboy/Squirrel.Windows,markwal/Squirrel.Windows,Katieleeb84/Squirrel.Windows,punker76/Squirrel.Windows,allanrsmith/Squirrel.Windows,NeilSorensen/Squirrel.Windows,Squirrel/Squirrel.Windows,aneeff/Squirrel.Windows,markwal/Squirrel.Windows,kenbailey/Squirrel.Windows,akrisiun/Squirrel.Windows,allanrsmith/Squirrel.Windows,kenbailey/Squirrel.Windows,vaginessa/Squirrel.Windows,1gurucoder/Squirrel.Windows,NeilSorensen/Squirrel.Windows,jochenvangasse/Squirrel.Windows | src/Update/Program.cs | src/Update/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Options;
namespace Update
{
class Program
{
static OptionSet opts;
static int Main(string[] args)
{
if (args.Any(x => x.StartsWith("/squirrel", StringComparison.OrdinalIgnoreCase))) {
// NB: We're marked as Squirrel-aware, but we don't want to do
// anything in response to these events
return 0;
}
opts = new OptionSet() {
"Usage: Update.exe command [OPTS]",
"Manages Squirrel packages",
"",
"Options:",
{ "h|?|help", "Display Help and exit", v => ShowHelp() }
};
opts.Parse(args);
return 0;
}
static void ShowHelp()
{
opts.WriteOptionDescriptions(Console.Out);
Environment.Exit(0);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mono.Options;
namespace Update
{
class Program
{
static int Main(string[] args)
{
if (args.Any(x => x.StartsWith("/squirrel", StringComparison.OrdinalIgnoreCase))) {
// NB: We're marked as Squirrel-aware, but we don't want to do
// anything in response to these events
return 0;
}
var opts = new OptionSet() {
{ "h|?|help", v => ShowHelp() }
};
opts.Parse(args);
return 0;
}
static void ShowHelp()
{
Console.WriteLine("Help!");
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.