Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix build for UE4.2 - Add SlateCore as new module dependency | // Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
using UnrealBuildTool;
public class GitSourceControl : ModuleRules
{
public GitSourceControl(TargetInfo Target)
{
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"Slate",
"EditorStyle",
"SourceControl",
}
);
}
}
| // Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
using UnrealBuildTool;
public class GitSourceControl : ModuleRules
{
public GitSourceControl(TargetInfo Target)
{
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"Slate",
"SlateCore",
"EditorStyle",
"SourceControl",
}
);
}
}
|
Enable callback test only when url is set | @page
@model SupportManager.Web.Pages.User.ApiKeys.ListModel
@{
Layout = "/Features/Shared/_Layout.cshtml";
ViewData["Title"] = "API Keys";
}
<h2>API Keys</h2>
@if (!Model.Data.ApiKeys.Any())
{
<div class="jumbotron">
<p>
No API keys created yet.
</p>
<p>
<a class="btn btn-primary btn-lg" asp-page="Create">Create API key</a>
</p>
</div>
}
else
{
<p>
<a asp-page="Create">Create API key</a>
</p>
<table class="table table-striped">
<thead>
<tr>
<th>
Key
</th>
<th>
Callback URL
</th>
<th></th>
</tr>
</thead>
<tbody>
@{ int i = 0;}
@foreach (var item in Model.Data.ApiKeys)
{
<tr>
<td>
<code>@Model.Data.ApiKeys[i].Value</code>
</td>
<td>
@Model.Data.ApiKeys[i].CallbackUrl
</td>
<td>
<a asp-page="Test" asp-route-id="@item.Id">Test</a>
<a asp-page="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
i++;
}
</tbody>
</table>
}
| @page
@model SupportManager.Web.Pages.User.ApiKeys.ListModel
@{
Layout = "/Features/Shared/_Layout.cshtml";
ViewData["Title"] = "API Keys";
}
<h2>API Keys</h2>
@if (!Model.Data.ApiKeys.Any())
{
<div class="jumbotron">
<p>
No API keys created yet.
</p>
<p>
<a class="btn btn-primary btn-lg" asp-page="Create">Create API key</a>
</p>
</div>
}
else
{
<p>
<a asp-page="Create">Create API key</a>
</p>
<table class="table table-striped">
<thead>
<tr>
<th>
Key
</th>
<th>
Callback URL
</th>
<th></th>
</tr>
</thead>
<tbody>
@{ int i = 0;}
@foreach (var item in Model.Data.ApiKeys)
{
<tr>
<td>
<code>@Model.Data.ApiKeys[i].Value</code>
</td>
<td>
@Model.Data.ApiKeys[i].CallbackUrl
</td>
<td>
@if (@Model.Data.ApiKeys[i].CallbackUrl != null)
{
<a asp-page="Test" asp-route-id="@item.Id">Test</a>
}
<a asp-page="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
i++;
}
</tbody>
</table>
}
|
Use String.Split(...) instead of recreating it. | namespace Fixie.Assertions
{
using System;
using System.Collections.Generic;
public class AssertException : Exception
{
public static string FilterStackTraceAssemblyPrefix = "Fixie.Assertions.";
public AssertException(string message)
: base(message)
{
}
public override string StackTrace => FilterStackTrace(base.StackTrace);
static string FilterStackTrace(string stackTrace)
{
if (stackTrace == null)
return null;
var results = new List<string>();
foreach (var line in SplitLines(stackTrace))
{
var trimmedLine = line.TrimStart();
if (!trimmedLine.StartsWith( "at " + FilterStackTraceAssemblyPrefix) )
results.Add(line);
}
return string.Join(Environment.NewLine, results.ToArray());
}
// Our own custom string.Split because Silverlight/CoreCLR doesn't support the version we were using
static IEnumerable<string> SplitLines(string input)
{
while (true)
{
int idx = input.IndexOf(Environment.NewLine);
if (idx < 0)
{
yield return input;
break;
}
yield return input.Substring(0, idx);
input = input.Substring(idx + Environment.NewLine.Length);
}
}
}
} | namespace Fixie.Assertions
{
using System;
using System.Collections.Generic;
public class AssertException : Exception
{
public static string FilterStackTraceAssemblyPrefix = "Fixie.Assertions.";
public AssertException(string message)
: base(message)
{
}
public override string StackTrace => FilterStackTrace(base.StackTrace);
static string FilterStackTrace(string stackTrace)
{
if (stackTrace == null)
return null;
var results = new List<string>();
foreach (var line in Lines(stackTrace))
{
var trimmedLine = line.TrimStart();
if (!trimmedLine.StartsWith("at " + FilterStackTraceAssemblyPrefix))
results.Add(line);
}
return string.Join(Environment.NewLine, results.ToArray());
}
static string[] Lines(string input)
{
return input.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
}
}
} |
Load footer image in JavaScript disabled | @model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
| @model SiteOptions
<hr />
<footer>
<p>
© @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year |
<a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information">
Site Status & Uptime
</a>
| Built from
<a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub">
@string.Join(string.Empty, GitMetadata.Commit.Take(7))
</a>
on
<a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub">
@GitMetadata.Branch
</a>
| Sponsored by
<a id="link-browserstack" href="https://www.browserstack.com/">
<noscript>
<img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" />
</noscript>
<lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" />
</a>
</p>
</footer>
|
Update for SSL error with site | using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HackyNewsWeb
{
public class Global : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
| using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HackyNewsWeb
{
public class Global : HttpApplication
{
protected void Application_Start()
{
// to account for SSL error
ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
|
Add checking for end of text | using System;
namespace LeanGoldfish
{
public class IsCharacter : ParsingUnit
{
private char character;
public IsCharacter(char character)
{
this.character = character;
}
internal override ParsingResult TryParse(string text, int position)
{
if (text[position] != character)
{
return new ParsingResult()
{
Succeeded = false,
StartPosition = position,
EndPosition = position
};
}
return new ParsingResult()
{
Succeeded = true,
StartPosition = position,
EndPosition = position
};
}
}
}
| using System;
namespace LeanGoldfish
{
public class IsCharacter : ParsingUnit
{
private char character;
public IsCharacter(char character)
{
this.character = character;
}
internal override ParsingResult TryParse(string text, int position)
{
if (position >= text.Length ||
text[position] != character)
{
return new ParsingResult()
{
Succeeded = false,
StartPosition = position,
EndPosition = position
};
}
return new ParsingResult()
{
Succeeded = true,
StartPosition = position,
EndPosition = position
};
}
}
}
|
Improve ABI to work better on x64 (values seems better off passed by value instead of byval*). | using SharpLLVM;
namespace SharpLang.CompilerServices
{
class DefaultABI : IABI
{
private readonly ContextRef context;
private readonly TargetDataRef targetData;
private readonly int intPtrSize;
public DefaultABI(ContextRef context, TargetDataRef targetData)
{
this.context = context;
this.targetData = targetData;
var intPtrLLVM = LLVM.PointerType(LLVM.Int8TypeInContext(context), 0);
intPtrSize = (int)LLVM.ABISizeOfType(targetData, intPtrLLVM);
}
public ABIParameterInfo GetParameterInfo(Type type)
{
if (type.StackType == StackValueType.Value)
{
// Types smaller than register size will be coerced to integer register type
var structSize = LLVM.ABISizeOfType(targetData, type.DefaultTypeLLVM);
if (structSize <= (ulong)intPtrSize)
{
return new ABIParameterInfo(ABIParameterInfoKind.Coerced, LLVM.IntTypeInContext(context, (uint)structSize * 8));
}
// Otherwise, fallback to passing by pointer + byval
return new ABIParameterInfo(ABIParameterInfoKind.Indirect);
}
// Other types are passed by value
return new ABIParameterInfo(ABIParameterInfoKind.Direct);
}
}
} | using SharpLLVM;
namespace SharpLang.CompilerServices
{
class DefaultABI : IABI
{
private readonly ContextRef context;
private readonly TargetDataRef targetData;
private readonly int intPtrSize;
public DefaultABI(ContextRef context, TargetDataRef targetData)
{
this.context = context;
this.targetData = targetData;
var intPtrLLVM = LLVM.PointerType(LLVM.Int8TypeInContext(context), 0);
intPtrSize = (int)LLVM.ABISizeOfType(targetData, intPtrLLVM);
}
public ABIParameterInfo GetParameterInfo(Type type)
{
if (type.StackType == StackValueType.Value)
{
// Types smaller than register size will be coerced to integer register type
var structSize = LLVM.ABISizeOfType(targetData, type.DefaultTypeLLVM);
if (structSize <= (ulong)intPtrSize)
{
return new ABIParameterInfo(ABIParameterInfoKind.Coerced, LLVM.IntTypeInContext(context, (uint)structSize * 8));
}
// Otherwise, fallback to passing by pointer + byval (x86) or direct (x64)
if (intPtrSize == 8)
return new ABIParameterInfo(ABIParameterInfoKind.Direct);
return new ABIParameterInfo(ABIParameterInfoKind.Indirect);
}
// Other types are passed by value (pointers, int32, int64, float, etc...)
return new ABIParameterInfo(ABIParameterInfoKind.Direct);
}
}
} |
Put the null db initializer back in there. | using Data.Mappings;
using Domain.Entities;
using System.Data.Entity;
namespace Data
{
public class DriversEdContext : DbContext
{
public DriversEdContext()
{
// Database.SetInitializer<DriversEdContext>(null);
}
public DbSet<Driver> Drivers { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.AddFromAssembly(typeof(DriversEdContext).Assembly);
}
}
}
| using Data.Mappings;
using Domain.Entities;
using System.Data.Entity;
namespace Data
{
public class DriversEdContext : DbContext
{
public DriversEdContext()
{
Database.SetInitializer<DriversEdContext>(null);
}
public DbSet<Driver> Drivers { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.AddFromAssembly(typeof(DriversEdContext).Assembly);
}
}
}
|
Update assembly details for NuGet | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Mammoth")]
[assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.0.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Mammoth")]
[assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Williamson")]
[assembly: AssemblyProduct("Mammoth")]
[assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.0.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
|
Set IndexedAttachments to version 2.0.2.0 | using System.Reflection;
[assembly: AssemblyTitle("Raven.Bundles.Contrib.IndexedAttachments")]
[assembly: AssemblyDescription("Plugin for RavenDB that extracts text from attachments so they can be indexed.")]
[assembly: AssemblyVersion("2.0.1.0")]
[assembly: AssemblyFileVersion("2.0.1.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Raven.Bundles.Contrib.IndexedAttachments")]
[assembly: AssemblyDescription("Plugin for RavenDB that extracts text from attachments so they can be indexed.")]
[assembly: AssemblyVersion("2.0.2.0")]
[assembly: AssemblyFileVersion("2.0.2.0")]
|
Rename retrys token to retries | using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces;
using StreamCompanionTypes.Interfaces.Sources;
namespace PlaysReplacements
{
public class PlaysReplacements : IPlugin, ITokensSource
{
private int Plays, Retrys;
private Tokens.TokenSetter _tokenSetter;
public string Description { get; } = "";
public string Name { get; } = nameof(PlaysReplacements);
public string Author { get; } = "Piotrekol";
public string Url { get; } = "";
public string UpdateUrl { get; } = "";
public PlaysReplacements()
{
_tokenSetter = Tokens.CreateTokenSetter(Name);
UpdateTokens();
}
public void CreateTokens(MapSearchResult map)
{
//ignore replays/spect
if (map.Action != OsuStatus.Playing)
return;
switch (map.SearchArgs.EventType)
{
case OsuEventType.SceneChange:
case OsuEventType.MapChange:
Plays++;
break;
case OsuEventType.PlayChange:
Retrys++;
break;
}
UpdateTokens();
}
private void UpdateTokens()
{
_tokenSetter("plays", Plays);
_tokenSetter("retrys", Retrys);
}
}
} | using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces;
using StreamCompanionTypes.Interfaces.Sources;
namespace PlaysReplacements
{
public class PlaysReplacements : IPlugin, ITokensSource
{
private int Plays, Retries;
private Tokens.TokenSetter _tokenSetter;
public string Description { get; } = "";
public string Name { get; } = nameof(PlaysReplacements);
public string Author { get; } = "Piotrekol";
public string Url { get; } = "";
public string UpdateUrl { get; } = "";
public PlaysReplacements()
{
_tokenSetter = Tokens.CreateTokenSetter(Name);
UpdateTokens();
}
public void CreateTokens(MapSearchResult map)
{
//ignore replays/spect
if (map.Action != OsuStatus.Playing)
return;
switch (map.SearchArgs.EventType)
{
case OsuEventType.SceneChange:
case OsuEventType.MapChange:
Plays++;
break;
case OsuEventType.PlayChange:
Retries++;
break;
}
UpdateTokens();
}
private void UpdateTokens()
{
_tokenSetter("plays", Plays);
_tokenSetter("retries", Retries);
}
}
} |
Revert accidental change of the async flag. | using System;
using System.Diagnostics;
namespace NuGetConsole.Implementation.PowerConsole {
/// <summary>
/// Represents a host with extra info.
/// </summary>
class HostInfo : ObjectWithFactory<PowerConsoleWindow> {
Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; }
public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider)
: base(factory) {
UtilityMethods.ThrowIfArgumentNull(hostProvider);
this.HostProvider = hostProvider;
}
/// <summary>
/// Get the HostName attribute value of this host.
/// </summary>
public string HostName {
get { return HostProvider.Metadata.HostName; }
}
IWpfConsole _wpfConsole;
/// <summary>
/// Get/create the console for this host. If not already created, this
/// actually creates the (console, host) pair.
///
/// Note: Creating the console is handled by this package and mostly will
/// succeed. However, creating the host could be from other packages and
/// fail. In that case, this console is already created and can be used
/// subsequently in limited ways, such as displaying an error message.
/// </summary>
public IWpfConsole WpfConsole {
get {
if (_wpfConsole == null) {
_wpfConsole = Factory.WpfConsoleService.CreateConsole(
Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName);
_wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: false);
}
return _wpfConsole;
}
}
}
}
| using System;
using System.Diagnostics;
namespace NuGetConsole.Implementation.PowerConsole {
/// <summary>
/// Represents a host with extra info.
/// </summary>
class HostInfo : ObjectWithFactory<PowerConsoleWindow> {
Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; }
public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider)
: base(factory) {
UtilityMethods.ThrowIfArgumentNull(hostProvider);
this.HostProvider = hostProvider;
}
/// <summary>
/// Get the HostName attribute value of this host.
/// </summary>
public string HostName {
get { return HostProvider.Metadata.HostName; }
}
IWpfConsole _wpfConsole;
/// <summary>
/// Get/create the console for this host. If not already created, this
/// actually creates the (console, host) pair.
///
/// Note: Creating the console is handled by this package and mostly will
/// succeed. However, creating the host could be from other packages and
/// fail. In that case, this console is already created and can be used
/// subsequently in limited ways, such as displaying an error message.
/// </summary>
public IWpfConsole WpfConsole {
get {
if (_wpfConsole == null) {
_wpfConsole = Factory.WpfConsoleService.CreateConsole(
Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName);
_wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: true);
}
return _wpfConsole;
}
}
}
}
|
Advance version number scheme to include pressure regulator gadget. | using System;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.terranova
{
public class VersioningInfo
{
public String VersionNumber {
get {
return "v1.0.1";
}
}
public String EngineIdentifier {
get {
return "Network Reasoner, stlab.dsi.unifi.it";
}
}
}
}
| using System;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.terranova
{
public class VersioningInfo
{
/// <summary>
/// Gets the version number.
///
/// Here are the stack of versions with a brief description:
///
/// v1.1.0: introduce pressure regulator gadget for edges.
///
/// v1.0.1: enhancement to tackle turbolent behavior due to
/// Reynolds number.
///
/// v1.0.0: basic version with checker about negative pressures
/// associated to nodes with load gadget.
///
/// </summary>
/// <value>The version number.</value>
public String VersionNumber {
get {
return "v1.1.0";
}
}
public String EngineIdentifier {
get {
return "Network Reasoner, stlab.dsi.unifi.it";
}
}
}
}
|
Replace Single with SingleOrDefault for Url Reposiory | using System;
using System.Collections.Generic;
using System.Linq;
using UrlShortenerApi.Data;
using UrlShortenerApi.Models;
namespace UrlShortenerApi.Repositories
{
public class UrlRepository : IUrlRepository
{
ApplicationDbContext _context;
public UrlRepository(ApplicationDbContext context)
{
_context = context;
}
public void Add(Url item)
{
item.ShortFormat = UrlShortenerLib.Shortener.GenerateShortFormat(6);
item.CreationDate = DateTime.Now;
_context.Urls.Add(item);
_context.SaveChanges();
}
public IEnumerable<Url> GetAll()
{
return _context.Urls.ToList();
}
public Url Find(int id)
{
return _context.Urls.Single(m => m.ID == id);
}
public Url Find(string shortFormat)
{
return _context.Urls.Single(m => m.ShortFormat == shortFormat);
}
public void Remove(int id)
{
var student = _context.Urls.Single(m => m.ID == id);
if (student != null)
{
_context.Urls.Remove(student);
}
}
public void Update(Url item)
{
_context.Update(item);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using UrlShortenerApi.Data;
using UrlShortenerApi.Models;
namespace UrlShortenerApi.Repositories
{
public class UrlRepository : IUrlRepository
{
ApplicationDbContext _context;
public UrlRepository(ApplicationDbContext context)
{
_context = context;
}
public void Add(Url item)
{
item.ShortFormat = UrlShortenerLib.Shortener.GenerateShortFormat(6);
item.CreationDate = DateTime.Now;
_context.Urls.Add(item);
_context.SaveChanges();
}
public IEnumerable<Url> GetAll()
{
return _context.Urls.ToList();
}
public Url Find(int id)
{
return _context.Urls.SingleOrDefault(m => m.ID == id);
}
public Url Find(string shortFormat)
{
return _context.Urls.SingleOrDefault(m => m.ShortFormat == shortFormat);
}
public void Remove(int id)
{
var student = _context.Urls.Single(m => m.ID == id);
if (student != null)
{
_context.Urls.Remove(student);
}
}
public void Update(Url item)
{
_context.Update(item);
}
}
}
|
Add validation implementation in recommendations module. | namespace TraktApiSharp.Modules
{
using Objects.Basic;
using Objects.Get.Recommendations;
using Requests;
using Requests.WithOAuth.Recommendations;
using System.Threading.Tasks;
public class TraktRecommendationsModule : TraktBaseModule
{
public TraktRecommendationsModule(TraktClient client) : base(client) { }
public async Task<TraktListResult<TraktMovieRecommendation>> GetUserMovieRecommendationsAsync(int? limit = null,
TraktExtendedOption extended = null)
{
return await QueryAsync(new TraktUserMovieRecommendationsRequest(Client)
{
PaginationOptions = new TraktPaginationOptions(null, limit),
ExtendedOption = extended != null ? extended : new TraktExtendedOption()
});
}
public async Task HideMovieRecommendationAsync(string movieId)
{
await QueryAsync(new TraktUserRecommendationHideMovieRequest(Client) { Id = movieId });
}
public async Task<TraktListResult<TraktShowRecommendation>> GetUserShowRecommendationsAsync(int? limit = null,
TraktExtendedOption extended = null)
{
return await QueryAsync(new TraktUserShowRecommendationsRequest(Client)
{
PaginationOptions = new TraktPaginationOptions(null, limit),
ExtendedOption = extended != null ? extended : new TraktExtendedOption()
});
}
public async Task HideShowRecommendationAsync(string showId)
{
await QueryAsync(new TraktUserRecommendationHideShowRequest(Client) { Id = showId });
}
}
}
| namespace TraktApiSharp.Modules
{
using Objects.Basic;
using Objects.Get.Recommendations;
using Requests;
using Requests.WithOAuth.Recommendations;
using System;
using System.Threading.Tasks;
public class TraktRecommendationsModule : TraktBaseModule
{
public TraktRecommendationsModule(TraktClient client) : base(client) { }
public async Task<TraktListResult<TraktMovieRecommendation>> GetUserMovieRecommendationsAsync(int? limit = null,
TraktExtendedOption extended = null)
{
return await QueryAsync(new TraktUserMovieRecommendationsRequest(Client)
{
PaginationOptions = new TraktPaginationOptions(null, limit),
ExtendedOption = extended != null ? extended : new TraktExtendedOption()
});
}
public async Task HideMovieRecommendationAsync(string movieId)
{
Validate(movieId);
await QueryAsync(new TraktUserRecommendationHideMovieRequest(Client) { Id = movieId });
}
public async Task<TraktListResult<TraktShowRecommendation>> GetUserShowRecommendationsAsync(int? limit = null,
TraktExtendedOption extended = null)
{
return await QueryAsync(new TraktUserShowRecommendationsRequest(Client)
{
PaginationOptions = new TraktPaginationOptions(null, limit),
ExtendedOption = extended != null ? extended : new TraktExtendedOption()
});
}
public async Task HideShowRecommendationAsync(string showId)
{
Validate(showId);
await QueryAsync(new TraktUserRecommendationHideShowRequest(Client) { Id = showId });
}
private void Validate(string id)
{
if (string.IsNullOrEmpty(id))
throw new ArgumentException("id not valid", "id");
}
}
}
|
Rework regex to allow whitespace | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Cake.VisualStudio.Helpers;
namespace Cake.VisualStudio.TaskRunner
{
class TaskParser
{
private static string _loadPattern = "#load \"";
public static SortedList<string, string> LoadTasks(string configPath)
{
var list = new SortedList<string, string>();
try
{
var script = new ScriptContent(configPath);
script.Parse(_loadPattern, s => s.Replace("#load", string.Empty).Trim().Trim('"', ';'));
var document = script.ToString();
var r = new Regex("Task\\([\\w\\\"](.+)\\b\\\"*\\)");
var matches = r.Matches(document);
var taskNames = matches.Cast<Match>().Select(m => m.Groups[1].Value);
foreach (var name in taskNames)
{
list.Add(name, $"-Target=\"{name}\"");
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
return list;
}
}
} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Cake.VisualStudio.Helpers;
namespace Cake.VisualStudio.TaskRunner
{
class TaskParser
{
private static string _loadPattern = "#load \"";
public static SortedList<string, string> LoadTasks(string configPath)
{
var list = new SortedList<string, string>();
try
{
var script = new ScriptContent(configPath);
script.Parse(_loadPattern, s => s.Replace("#load", string.Empty).Trim().Trim('"', ';'));
var document = script.ToString();
var r = new Regex("Task\\s*\\(\\s*\\\"(.+)\\b\\\"\\s*\\)");
var matches = r.Matches(document);
var taskNames = matches.Cast<Match>().Select(m => m.Groups[1].Value);
foreach (var name in taskNames)
{
list.Add(name, $"-Target=\"{name}\"");
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
return list;
}
}
} |
Update to hello support snippet | // 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
namespace SupportActions;
// snippet-start:[Support.dotnetv3.HelloSupport]
using Amazon.AWSSupport;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public static class HelloSupport
{
static async Task Main(string[] args)
{
// 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();
// Now the client is available for injection.
var supportClient = host.Services.GetRequiredService<IAmazonAWSSupport>();
// We can use await and any of the async methods to get a response.
var response = await supportClient.DescribeServicesAsync();
Console.WriteLine($"\tHello AWS Support! There are {response.Services.Count} services available.");
}
}
// snippet-end:[Support.dotnetv3.HelloSupport]
|
Remove extra braces at the end of the file | using System;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Healthcheck
{
internal class Program
{
private static void Main(string[] args)
{
var client = new HttpClient();
var port = Environment.GetEnvironmentVariable("PORT");
if (port == null)
throw new Exception("PORT is not defined");
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
{
if (addr.Address.AddressFamily != AddressFamily.InterNetwork) continue;
if (addr.Address.ToString().StartsWith("127.")) continue;
try
{
var task =
client.GetAsync(String.Format("http://{0}:{1}", addr.Address.ToString(), port));
if (task.Wait(1000))
{
if (task.Result.IsSuccessStatusCode)
{
Console.WriteLine("healthcheck passed");
Environment.Exit(0);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Console.WriteLine("healthcheck failed");
Environment.Exit(1);
}
}
}
} | using System;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Healthcheck
{
internal class Program
{
private static void Main(string[] args)
{
var client = new HttpClient();
var port = Environment.GetEnvironmentVariable("PORT");
if (port == null)
throw new Exception("PORT is not defined");
foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
IPInterfaceProperties ipProps = netInterface.GetIPProperties();
foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses)
{
if (addr.Address.AddressFamily != AddressFamily.InterNetwork) continue;
if (addr.Address.ToString().StartsWith("127.")) continue;
try
{
var task =
client.GetAsync(String.Format("http://{0}:{1}", addr.Address.ToString(), port));
if (task.Wait(1000))
{
if (task.Result.IsSuccessStatusCode)
{
Console.WriteLine("healthcheck passed");
Environment.Exit(0);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
Console.WriteLine("healthcheck failed");
Environment.Exit(1);
}
}
} |
Use same null default value when JS is disabled | using System;
using System.Web.Mvc;
namespace AspNetBrowserLocale.Core
{
public static class HtmlHelpers
{
public static MvcHtmlString InitializeLocaleDateTime(this HtmlHelper htmlHelper)
{
return MvcHtmlString.Create(
@"<script>
var elements = document.querySelectorAll('[data-aspnet-browser-locale]');
for (var i = 0; i < elements.length; i++) {{
var element = elements[i];
var msString = element.dataset.aspnetBrowserLocale;
if (msString) {{
var jsDate = new Date(parseInt(msString, 10));
element.innerHTML = jsDate.toLocaleString();
}}
else {{
element.innerHTML = '—';
}}
}}
</script>");
}
public static MvcHtmlString LocaleDateTime(this HtmlHelper htmlHelper, DateTime? dateTime)
{
long? msSinceUnixEpoch = null;
if (dateTime.HasValue)
{
msSinceUnixEpoch = (long)((TimeSpan)(dateTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
}
return MvcHtmlString.Create(string.Format(
@"<span data-aspnet-browser-locale=""{0}"">{1}</span>",
msSinceUnixEpoch,
dateTime.HasValue ? dateTime.Value.ToUniversalTime().ToString() + " UTC" : null));
}
}
} | using System;
using System.Web.Mvc;
namespace AspNetBrowserLocale.Core
{
public static class HtmlHelpers
{
private const string NullValueDisplay = "—";
public static MvcHtmlString InitializeLocaleDateTime(this HtmlHelper htmlHelper)
{
return MvcHtmlString.Create(string.Format(
@"<script>
var elements = document.querySelectorAll('[data-aspnet-browser-locale]');
for (var i = 0; i < elements.length; i++) {{
var element = elements[i];
var msString = element.dataset.aspnetBrowserLocale;
if (msString) {{
var jsDate = new Date(parseInt(msString, 10));
element.innerHTML = jsDate.toLocaleString();
}}
else {{
element.innerHTML = '{0}';
}}
}}
</script>",
NullValueDisplay));
}
public static MvcHtmlString LocaleDateTime(this HtmlHelper htmlHelper, DateTime? dateTime)
{
long? msSinceUnixEpoch = null;
if (dateTime.HasValue)
{
msSinceUnixEpoch = (long)((TimeSpan)(dateTime.Value.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))).TotalMilliseconds;
}
return MvcHtmlString.Create(string.Format(
@"<span data-aspnet-browser-locale=""{0}"">{1}</span>",
msSinceUnixEpoch,
dateTime.HasValue ? dateTime.Value.ToUniversalTime().ToString() + " UTC" : NullValueDisplay));
}
}
} |
Remove unnecessary "@" prefix from method argument variable name. | namespace Bakery.Text
{
using System;
public static class StringRemoveExtensions
{
public static String Remove(this String @string, String @remove)
{
return @string.Replace(@remove, String.Empty);
}
}
}
| namespace Bakery.Text
{
using System;
public static class StringRemoveExtensions
{
public static String Remove(this String @string, String remove)
{
if (remove == null)
throw new ArgumentNullException(nameof(remove));
return @string.Replace(remove, String.Empty);
}
}
}
|
Change Demo Trading intervall -> performance | using Main;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoTrader
{
public class StdTraders : Trader {
public StdTraders()
: base() {
}
public override string Name {
get { return "DemoTrader"; }
}
public override string Version {
get { return "0.0.1"; }
}
public override bool Active {
get {
return true;
}
}
public override void Initiale() {
log("Tradeengine started.... Balance: btc=" + Portfolio.btc + "; eur=" + Portfolio.eur);
base.Initiale();
}
public override void Update() {
if (!Data.checkIfDataFalid(2)) return;
double shortvl = Data.ma(2);
double longvl = Data.ma(1);
double mymacd = (longvl - shortvl) / longvl;
plot("ma short", shortvl);
plot("ma long", longvl);
plot("ema short", Data.ema(2));
plot("price", Data.Candle().value.Last);
plot("macd", mymacd, true);
if (TickCount % 2 == 0) {
buyBtc(10);
} else {
sellBtc(10);
}
base.Update();
}
public override void Stop() {
base.Stop();
}
}
}
| using Main;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DemoTrader
{
public class StdTraders : Trader {
public StdTraders()
: base() {
}
public override string Name {
get { return "DemoTrader"; }
}
public override string Version {
get { return "0.0.1"; }
}
public override bool Active {
get {
return true;
}
}
public override void Initiale() {
log("Tradeengine started.... Balance: btc=" + Portfolio.btc + "; eur=" + Portfolio.eur);
base.Initiale();
}
public override void Update() {
if (!Data.checkIfDataFalid(2)) return;
double shortvl = Data.ma(2);
double longvl = Data.ma(1);
double mymacd = (longvl - shortvl) / longvl;
plot("ma short", shortvl);
plot("ma long", longvl);
plot("ema short", Data.ema(2));
plot("price", Data.Candle().value.Last);
plot("macd", mymacd, true);
int tradeint = 100;
if (TickCount % tradeint == 0) {
if (TickCount % (tradeint * 2) == 0) {
buyBtc(10);
} else {
sellBtc(10);
}
}
base.Update();
}
public override void Stop() {
base.Stop();
}
}
}
|
Disable authentication with empty access key | using System;
using Skylight.Miscellaneous;
namespace Skylight
{
public class InputCodeForRoom
{
private readonly Out _out;
public InputCodeForRoom(Out @out)
{
_out = @out;
}
/// <summary>
/// Inputs the edit key.
/// </summary>
/// <param name="editKey">The edit key.</param>
public void InputCode(string editKey)
{
try
{
_out.C.Send("access", editKey);
}
catch (Exception)
{
Tools.SkylightMessage("Error: attempted to use Out.InputCode before connecting");
}
}
}
} | using System;
using Skylight.Miscellaneous;
namespace Skylight
{
public class InputCodeForRoom
{
private readonly Out _out;
public InputCodeForRoom(Out @out)
{
_out = @out;
}
/// <summary>
/// Inputs the edit key.
/// </summary>
/// <param name="editKey">The edit key.</param>
public void InputCode(string editKey)
{
if (String.IsNullOrWhiteSpace(editKey)) {throw new ArgumentException("editKey cannot be empty or null.");}
try
{
_out.C.Send("access", editKey);
}
catch (Exception)
{
Tools.SkylightMessage("Error: attempted to use Out.InputCode before connecting");
}
}
}
} |
Add another RunProject function with args to script. | using System;
using System.IO;
namespace SikuliSharp
{
public static class Sikuli
{
public static ISikuliSession CreateSession()
{
return new SikuliSession(CreateRuntime());
}
public static SikuliRuntime CreateRuntime()
{
return new SikuliRuntime(
new AsyncDuplexStreamsHandlerFactory(),
new SikuliScriptProcessFactory()
);
}
public static string RunProject(string projectPath)
{
if (projectPath == null) throw new ArgumentNullException("projectPath");
if(!Directory.Exists(projectPath))
throw new DirectoryNotFoundException(string.Format("Project not found in path '{0}'", projectPath));
var processFactory = new SikuliScriptProcessFactory();
using (var process = processFactory.Start(string.Format("-r {0}", projectPath)))
{
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
}
}
}
| using System;
using System.IO;
namespace SikuliSharp
{
public static class Sikuli
{
public static ISikuliSession CreateSession()
{
return new SikuliSession(CreateRuntime());
}
public static SikuliRuntime CreateRuntime()
{
return new SikuliRuntime(
new AsyncDuplexStreamsHandlerFactory(),
new SikuliScriptProcessFactory()
);
}
public static string RunProject(string projectPath)
{
if (projectPath == null) throw new ArgumentNullException("projectPath");
if(!Directory.Exists(projectPath))
throw new DirectoryNotFoundException(string.Format("Project not found in path '{0}'", projectPath));
var processFactory = new SikuliScriptProcessFactory();
using (var process = processFactory.Start(string.Format("-r {0}", projectPath)))
{
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
}
public static string RunProject(string projectPath, string args)
{
if (projectPath == null) throw new ArgumentNullException("projectPath");
if (!Directory.Exists(projectPath))
throw new DirectoryNotFoundException(string.Format("Project not found in path '{0}'", projectPath));
var processFactory = new SikuliScriptProcessFactory();
using (var process = processFactory.Start(string.Format("-r {0} {1}", projectPath, args)))
{
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return output;
}
}
}
}
|
Revert "measure time of GetSharedSecret" | using NUnit.Framework;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Elliptic.Tests
{
[Explicit]
[TestFixture]
public class Curve25519TimingTests
{
[Test]
public void Curve25519_GetPublicKey()
{
var millis = new List<long>();
for (var i = 0; i < 255; i++)
{
var privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32));
Curve25519.GetPublicKey(privateKey);
var stopwatch = Stopwatch.StartNew();
for (var j = 0; j < 100; j++)
{
Curve25519.GetPublicKey(privateKey);
}
millis.Add(stopwatch.ElapsedMilliseconds);
}
var text = new StringBuilder();
foreach (var ms in millis)
text.Append(ms + ",");
Assert.Inconclusive(text.ToString());
}
[Test]
public void Curve25519_GetSharedSecret()
{
var millis = new List<long>();
for (var i = 0; i < 255; i++)
{
var privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32));
var publicKey = Curve25519.GetPublicKey(privateKey);
Curve25519.GetSharedSecret(privateKey, publicKey);
var stopwatch = Stopwatch.StartNew();
for (var j = 0; j < 100; j++)
{
Curve25519.GetSharedSecret(privateKey, publicKey);
}
millis.Add(stopwatch.ElapsedMilliseconds);
}
var text = new StringBuilder();
foreach (var ms in millis)
text.Append(ms + ",");
Assert.Inconclusive(text.ToString());
}
}
} | using NUnit.Framework;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Elliptic.Tests
{
[Explicit]
[TestFixture]
public class Curve25519TimingTests
{
[Test]
public void Curve25519_GetPublicKey()
{
var millis = new List<long>();
for (int i = 0; i < 255; i++)
{
byte[] privateKey = Curve25519.ClampPrivateKey(TestHelpers.GetUniformBytes((byte)i, 32));
Curve25519.GetPublicKey(privateKey);
Stopwatch stopwatch = Stopwatch.StartNew();
for (int j = 0; j < 100; j++)
{
Curve25519.GetPublicKey(privateKey);
}
millis.Add(stopwatch.ElapsedMilliseconds);
}
var text = new StringBuilder();
foreach (var ms in millis)
text.Append(ms + ",");
Assert.Inconclusive(text.ToString());
}
}
} |
Update variable names to reflect class name changes | /*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CvsGitConverter
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException("Need a cvs.log file");
var parser = new CvsLogParser(args[0]);
var commits = parser.Parse();
var changeSets = new Dictionary<string, ChangeSet>();
foreach (var commit in commits)
{
ChangeSet changeSet;
if (changeSets.TryGetValue(commit.CommitId, out changeSet))
{
changeSet.Add(commit);
}
else
{
changeSet = new ChangeSet(commit.CommitId) { commit };
changeSets.Add(changeSet.CommitId, changeSet);
}
}
foreach (var changeSet in changeSets.Values.OrderBy(c => c.Time))
{
Console.Out.WriteLine("Commit: {0} {1}", changeSet.CommitId, changeSet.Time);
foreach (var commit in changeSet)
Console.Out.WriteLine(" {0} r{1}", commit.File, commit.Revision);
}
}
}
} | /*
* John Hall <john.hall@xjtag.com>
* Copyright (c) Midas Yellow Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CvsGitConverter
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
throw new ArgumentException("Need a cvs.log file");
var parser = new CvsLogParser(args[0]);
var revisions = parser.Parse();
var commits = new Dictionary<string, Commit>();
foreach (var revision in revisions)
{
Commit changeSet;
if (commits.TryGetValue(revision.CommitId, out changeSet))
{
changeSet.Add(revision);
}
else
{
changeSet = new Commit(revision.CommitId) { revision };
commits.Add(changeSet.CommitId, changeSet);
}
}
foreach (var commit in commits.Values.OrderBy(c => c.Time))
{
Console.Out.WriteLine("Commit: {0} {1}", commit.CommitId, commit.Time);
foreach (var revision in commit)
Console.Out.WriteLine(" {0} r{1}", revision.File, revision.Revision);
}
}
}
} |
Fix for missing author info | using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using RestSharp;
using Dapper;
using DapperExtensions;
using WPMGMT.BESScraper.Model;
namespace WPMGMT.BESScraper
{
class Program
{
static void Main(string[] args)
{
BesApi besApi = new BesApi(new Uri("https://pc120006933:52311/api/"), "iemadmin", "bigfix");
//WPMGMT.BESScraper.Model.Action action = besApi.GetAction(1854);
//Actions actions = besApi.GetActions();
//ActionDetail detail = besApi.GetActionDetail(1854);
WPMGMT.BESScraper.Model.Action action = new Model.Action();
action.ID = 1855;
action.Name = "TEST POC TROLL";
using (SqlConnection cn = new SqlConnection(@"Data Source=10.50.20.128\YPTOSQL002LP;Initial Catalog=YPTO_WPMGMT;Integrated Security=SSPI;"))
{
cn.Open();
var id = cn.Insert(action);
cn.Close();
}
Console.Read();
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using RestSharp;
using Dapper;
using DapperExtensions;
using WPMGMT.BESScraper.Model;
namespace WPMGMT.BESScraper
{
class Program
{
static void Main(string[] args)
{
BesApi besApi = new BesApi(new Uri("https://pc120006933:52311/api/"), "iemadmin", "bigfix");
//WPMGMT.BESScraper.Model.Action action = besApi.GetAction(1854);
//Actions actions = besApi.GetActions();
//ActionDetail detail = besApi.GetActionDetail(1854);
WPMGMT.BESScraper.Model.Action action = new Model.Action();
action.ID = 1855;
action.Name = "TEST POC TROLL";
using (SqlConnection cn = new SqlConnection(@"Data Source=10.50.20.128\YPTOSQL002LP;Initial Catalog=YPTO_WPMGMT;Integrated Security=SSPI;"))
{
cn.Open();
// TEST
var id = cn.Insert(action);
cn.Close();
}
Console.Read();
}
}
}
|
Check Environment.UserInteractive instead of argument | using System;
using System.Linq;
using System.ServiceProcess;
namespace PolymeliaDeployAgent
{
using PolymeliaDeploy;
using PolymeliaDeploy.Controller;
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
var service = new Service();
DeployServices.ReportClient = new ReportRemoteClient();
DeployServices.ActivityClient = new ActivityRemoteClient();
if (args.Any(arg => arg == "/c"))
{
Console.WriteLine("Start polling deploy controller for tasks...");
using(var poller = new DeployPoller())
{
poller.StartPoll();
Console.ReadLine();
}
return;
}
ServiceBase.Run(service);
}
}
}
| using System;
using System.Linq;
using System.ServiceProcess;
namespace PolymeliaDeployAgent
{
using PolymeliaDeploy;
using PolymeliaDeploy.Controller;
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
var service = new Service();
DeployServices.ReportClient = new ReportRemoteClient();
DeployServices.ActivityClient = new ActivityRemoteClient();
if (Environment.UserInteractive)
{
Console.WriteLine("Start polling deploy controller for tasks...");
using(var poller = new DeployPoller())
{
poller.StartPoll();
Console.ReadLine();
}
return;
}
ServiceBase.Run(service);
}
}
}
|
Clean up fluent node builder to not leak implementation details | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SassSharp.Ast
{
public class FluentAstBuilder
{
private IList<Node> nodes;
public FluentAstBuilder()
{
nodes = new List<Node>();
}
public FluentAstBuilder Node(string selector, Action<FluentNodeBuilder> nodeBuilder)
{
var builder = new FluentNodeBuilder();
nodeBuilder(builder);
nodes.Add(Ast.Node.Create(selector, DeclarationSet.FromList(builder.Declarations), builder.Children));
return this;
}
public SassSyntaxTree Build()
{
return new SassSyntaxTree(nodes);
}
public class FluentNodeBuilder
{
private IList<Declaration> declarations;
private IList<Node> children;
public FluentNodeBuilder()
{
declarations = new List<Declaration>();
children = new List<Node>();
}
public IList<Declaration> Declarations
{
get { return declarations; }
}
public IEnumerable<Node> Children
{
get { return children; }
}
public void Declaration(string property, string value)
{
declarations.Add(new Declaration(property, value));
}
public void Child(string selector, Action<FluentNodeBuilder> nodeBuilder)
{
var builder = new FluentNodeBuilder();
nodeBuilder(builder);
children.Add(Ast.Node.Create(selector, DeclarationSet.FromList(builder.Declarations), builder.Children));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SassSharp.Ast
{
public class FluentAstBuilder
{
private IList<Node> nodes;
public FluentAstBuilder()
{
nodes = new List<Node>();
}
public FluentAstBuilder Node(string selector, Action<FluentNodeBuilder> nodeBuilder)
{
nodes.Add(FluentNodeBuilder.CreateNode(selector, nodeBuilder));
return this;
}
public SassSyntaxTree Build()
{
return new SassSyntaxTree(nodes);
}
public class FluentNodeBuilder
{
private IList<Declaration> declarations;
private IList<Node> children;
public FluentNodeBuilder(IList<Declaration> declarations, IList<Node> children)
{
this.declarations = declarations;
this.children = children;
}
public void Declaration(string property, string value)
{
declarations.Add(new Declaration(property, value));
}
public void Child(string selector, Action<FluentNodeBuilder> nodeBuilder)
{
children.Add(FluentNodeBuilder.CreateNode(selector, nodeBuilder));
}
public static Node CreateNode(string selector, Action<FluentNodeBuilder> nodeBuilder)
{
var declarations = new List<Declaration>();
var children = new List<Node>();
var builder = new FluentNodeBuilder(declarations, children);
nodeBuilder(builder);
return Ast.Node.Create(selector, DeclarationSet.FromList(declarations), children);
}
}
}
}
|
Remove work-in progress enum, not presently required. | #if DESKTOP
using System;
using System.Collections.ObjectModel;
namespace Eto.Forms
{
public interface IMenuItem : IMenu
{
}
public enum MenuItemType
{
Check,
Image,
Radio,
Separator,
}
public abstract class MenuItem : BaseAction
{
protected MenuItem (Generator g, Type type, bool initialize = true)
: base(g, type, initialize)
{
}
}
public class MenuItemCollection : Collection<MenuItem>
{
readonly ISubMenu subMenu;
public ISubMenuWidget Parent {
get;
private set;
}
public MenuItemCollection (ISubMenuWidget parent, ISubMenu parentMenu)
{
this.Parent = parent;
this.subMenu = parentMenu;
}
protected override void InsertItem (int index, MenuItem item)
{
base.InsertItem (index, item);
subMenu.AddMenu (index, item);
}
protected override void RemoveItem (int index)
{
var item = this [index];
base.RemoveItem (index);
subMenu.RemoveMenu (item);
}
protected override void ClearItems ()
{
base.ClearItems ();
subMenu.Clear ();
}
}
}
#endif | #if DESKTOP
using System;
using System.Collections.ObjectModel;
namespace Eto.Forms
{
public interface IMenuItem : IMenu
{
}
public abstract class MenuItem : BaseAction
{
protected MenuItem (Generator g, Type type, bool initialize = true)
: base(g, type, initialize)
{
}
}
public class MenuItemCollection : Collection<MenuItem>
{
readonly ISubMenu subMenu;
public ISubMenuWidget Parent {
get;
private set;
}
public MenuItemCollection (ISubMenuWidget parent, ISubMenu parentMenu)
{
this.Parent = parent;
this.subMenu = parentMenu;
}
protected override void InsertItem (int index, MenuItem item)
{
base.InsertItem (index, item);
subMenu.AddMenu (index, item);
}
protected override void RemoveItem (int index)
{
var item = this [index];
base.RemoveItem (index);
subMenu.RemoveMenu (item);
}
protected override void ClearItems ()
{
base.ClearItems ();
subMenu.Clear ();
}
}
}
#endif |
Fix use of `ThreadsResponse` (type changed for threads container) | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Threading;
using System.Threading.Tasks;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class ThreadsHandler : IThreadsHandler
{
public Task<ThreadsResponse> Handle(ThreadsArguments request, CancellationToken cancellationToken)
{
return Task.FromResult(new ThreadsResponse
{
// TODO: What do I do with these?
Threads = new Container<OmniSharp.Extensions.DebugAdapter.Protocol.Models.Thread>(
new OmniSharp.Extensions.DebugAdapter.Protocol.Models.Thread
{
Id = 1,
Name = "Main Thread"
})
});
}
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System.Threading;
using System.Threading.Tasks;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class ThreadsHandler : IThreadsHandler
{
public Task<ThreadsResponse> Handle(ThreadsArguments request, CancellationToken cancellationToken)
{
return Task.FromResult(new ThreadsResponse
{
// TODO: This is an empty container of threads...do we need to make a thread?
Threads = new Container<System.Threading.Thread>()
});
}
}
}
|
Revert "Revert "Revert "added try catch, test commit""" | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.CrossDomainImagesWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
{
//set access token in hidden field for client calls
hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;
//set images
Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
Services.ImgService svc = new Services.ImgService();
Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
}
}
catch (Exception)
{
throw;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Core.CrossDomainImagesWeb
{
public partial class Default : System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
Uri redirectUrl;
switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl))
{
case RedirectionStatus.Ok:
return;
case RedirectionStatus.ShouldRedirect:
Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true);
break;
case RedirectionStatus.CanNotRedirect:
Response.Write("An error occurred while processing your request.");
Response.End();
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
using (var clientContext = spContext.CreateUserClientContextForSPAppWeb())
{
//set access token in hidden field for client calls
hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb;
//set images
Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png";
Services.ImgService svc = new Services.ImgService();
Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png");
}
}
}
} |
Add NUL to invalid characters | using System;
namespace Villermen.RuneScapeCacheTools.Extensions
{
public static class PathExtensions
{
public static char[] InvalidCharacters = { '/', ':', '"', '*', '?', '>', '<', '|' };
/// <summary>
/// Parses the given directory and unifies its format, to be applied to unpredictable user input.
/// Converts backslashes to forward slashes, and appends a directory separator.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string FixDirectory(string path)
{
// Expand environment variables
var result = Environment.ExpandEnvironmentVariables(path);
// Replace backslashes with forward slashes
result = result.Replace('\\', '/');
// Add trailing slash if not present
if (!result.EndsWith("/"))
{
result += "/";
}
return result;
}
}
} | using System;
namespace Villermen.RuneScapeCacheTools.Extensions
{
public static class PathExtensions
{
public static char[] InvalidCharacters = { '/', ':', '"', '*', '?', '>', '<', '|', '\0' };
/// <summary>
/// Parses the given directory and unifies its format, to be applied to unpredictable user input.
/// Converts backslashes to forward slashes, and appends a directory separator.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string FixDirectory(string path)
{
// Expand environment variables
var result = Environment.ExpandEnvironmentVariables(path);
// Replace backslashes with forward slashes
result = result.Replace('\\', '/');
// Add trailing slash if not present
if (!result.EndsWith("/"))
{
result += "/";
}
return result;
}
}
} |
Update default project to start an engine and tick a few times. | using System;
using Ninject;
using Ninject.Extensions.Logging;
using Ninject.Extensions.Logging.NLog4;
using OpenAOE.Engine;
namespace OpenAOE
{
class Program
{
static void Main(string[] args)
{
var context = new StandardKernel(
new NinjectSettings()
{
LoadExtensions = false
}, new EngineModule(), new Games.AGE2.Module(), new NLogModule());
var log = context.Get<ILoggerFactory>().GetCurrentClassLogger();
log.Info("Starting");
/*context.Bind<IDataService>().ToConstant(VersionedDataService.FromRoot(new Root()));
var instance = context.Get<ISimulationInstance>();
context.Unbind(typeof(IDataService));*/
log.Info("Done");
Console.ReadKey(true);
log.Info("Exiting");
}
}
}
| using System;
using System.Collections.Generic;
using Ninject;
using Ninject.Extensions.Logging;
using Ninject.Extensions.Logging.NLog4;
using OpenAOE.Engine;
using OpenAOE.Engine.Entity;
namespace OpenAOE
{
class Program
{
static void Main(string[] args)
{
var context = new StandardKernel(
new NinjectSettings()
{
LoadExtensions = false
}, new Engine.EngineModule(), new Games.AGE2.Module(), new NLogModule());
var log = context.Get<ILoggerFactory>().GetCurrentClassLogger();
log.Info("Starting");
var engineFactory = context.Get<IEngineFactory>();
log.Info("Creating Engine");
var engine = engineFactory.Create(new List<EntityData>(), new List<EntityTemplate>());
for (var i = 0; i < 10; ++i)
{
var tick = engine.Tick(new EngineTickInput());
tick.Start();
tick.Wait();
engine.Synchronize();
}
/*context.Bind<IDataService>().ToConstant(VersionedDataService.FromRoot(new Root()));
var instance = context.Get<ISimulationInstance>();
context.Unbind(typeof(IDataService));*/
log.Info("Done");
Console.ReadKey(true);
log.Info("Exiting");
}
}
}
|
Check if column exist in table | using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace Tellurium.MvcPages.WebPages
{
public class WebTableRow : WebElementCollection<PageFragment>
{
private readonly IWebElement webElement;
private Dictionary<string, int> columnsMap;
public WebTableRow(RemoteWebDriver driver, IWebElement webElement, Dictionary<string, int> columnsMap) : base(driver, webElement)
{
this.webElement = webElement;
this.columnsMap = columnsMap;
}
protected override IWebElement GetItemsContainer()
{
return webElement;
}
protected override PageFragment MapToItem(IWebElement webElementItem)
{
return new PageFragment(Driver, webElementItem);
}
public IPageFragment this[string columnName]
{
get
{
if (string.IsNullOrWhiteSpace(columnName))
{
throw new ArgumentException("Column name cannot be empty", nameof(columnName));
}
var index = columnsMap[columnName];
return this[index];
}
}
}
} | using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
namespace Tellurium.MvcPages.WebPages
{
public class WebTableRow : WebElementCollection<PageFragment>
{
private readonly IWebElement webElement;
private Dictionary<string, int> columnsMap;
public WebTableRow(RemoteWebDriver driver, IWebElement webElement, Dictionary<string, int> columnsMap) : base(driver, webElement)
{
this.webElement = webElement;
this.columnsMap = columnsMap;
}
protected override IWebElement GetItemsContainer()
{
return webElement;
}
protected override PageFragment MapToItem(IWebElement webElementItem)
{
return new PageFragment(Driver, webElementItem);
}
public IPageFragment this[string columnName]
{
get
{
if (string.IsNullOrWhiteSpace(columnName))
{
throw new ArgumentException("Column name cannot be empty", nameof(columnName));
}
if (columnsMap.ContainsKey(columnName) == false)
{
throw new ArgumentException($"There is no column with header {columnName}", nameof(columnName));
}
var index = columnsMap[columnName];
return this[index];
}
}
}
} |
Add Windows auth to service, and authorize to the SpiderCrab Operators group | namespace SpiderCrab.Agent
{
using Ninject;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
using Owin;
using Properties;
using System.Reflection;
using System.Web.Http;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
app.UseNinjectMiddleware(CreateKernel)
.UseNinjectWebApi(config);
}
private IKernel CreateKernel()
{
var kernel = new StandardKernel(new ServiceModule(Settings.Default));
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
}
} | namespace SpiderCrab.Agent
{
using Newtonsoft.Json.Serialization;
using Ninject;
using Ninject.Web.Common.OwinHost;
using Ninject.Web.WebApi.OwinHost;
using Owin;
using Properties;
using System;
using System.Net;
using System.Reflection;
using System.Web.Http;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var listenerKey = typeof(HttpListener).FullName;
if (app.Properties==null || !app.Properties.ContainsKey(listenerKey))
{
throw new ArgumentOutOfRangeException(
nameof(app), "Cannnot access HTTP listener property");
}
// Authn; Authz
var listener = (HttpListener)app.Properties[listenerKey];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
var config = new HttpConfiguration();
config.Filters.Add(
new AuthorizeAttribute { Roles = $"{Environment.MachineName}\\SpiderCrab Operators" });
// Routes
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
// Serialization
config.Formatters.XmlFormatter.UseXmlSerializer = true;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver
= new CamelCasePropertyNamesContractResolver();
// Dependency injection
app.UseNinjectMiddleware(CreateKernel)
.UseNinjectWebApi(config);
}
private IKernel CreateKernel()
{
var kernel = new StandardKernel(new ServiceModule(Settings.Default));
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
}
} |
Use 3x3x3.vox as default example | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Voxels.SkiaSharp;
namespace Voxels.CommandLine {
class Program {
static void Main(string[] args) {
var filename = args.Length == 1 ? args[0] : "monu9.vox"; // "3x3x3.vox";
using (var stream = File.OpenRead(filename)) {
var voxelData = MagicaVoxel.Read(stream);
var guid = Guid.NewGuid();
File.WriteAllBytes($"output{guid}.png", Renderer.RenderPng(512, voxelData));
File.WriteAllBytes($"output{guid}.svg", Renderer.RenderSvg(512, voxelData));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Voxels.SkiaSharp;
namespace Voxels.CommandLine {
class Program {
static void Main(string[] args) {
var filename = args.Length == 1 ? args[0] : "3x3x3.vox";
using (var stream = File.OpenRead(filename)) {
var voxelData = MagicaVoxel.Read(stream);
var guid = Guid.NewGuid();
File.WriteAllBytes($"output{guid}.png", Renderer.RenderPng(512, voxelData));
File.WriteAllBytes($"output{guid}.svg", Renderer.RenderSvg(512, voxelData));
}
}
}
}
|
Fix the expected / actual order to correct the message | using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Dbus
{
public class ReceivedMessage : IDisposable
{
private readonly MessageHeader messageHeader;
public ReceivedMessage(
MessageHeader messageHeader,
Decoder decoder
)
{
this.messageHeader = messageHeader;
Decoder = decoder;
}
public SafeHandle[]? UnixFds => messageHeader.UnixFds;
public Stream GetStream(int index) => messageHeader.GetStream(index);
public Decoder Decoder { get; }
public void AssertSignature(Signature signature)
=> signature.AssertEqual(messageHeader.BodySignature!);
public void Dispose() => Decoder.Dispose();
}
}
| using System;
using System.IO;
using System.Runtime.InteropServices;
namespace Dbus
{
public class ReceivedMessage : IDisposable
{
private readonly MessageHeader messageHeader;
public ReceivedMessage(
MessageHeader messageHeader,
Decoder decoder
)
{
this.messageHeader = messageHeader;
Decoder = decoder;
}
public SafeHandle[]? UnixFds => messageHeader.UnixFds;
public Stream GetStream(int index) => messageHeader.GetStream(index);
public Decoder Decoder { get; }
public void AssertSignature(Signature expectedSignature)
=> messageHeader.BodySignature!.AssertEqual(expectedSignature);
public void Dispose() => Decoder.Dispose();
}
}
|
Change the deployment structure a bit |
using System;
using Tamir.SharpSsh;
namespace MCloud {
public class ScriptDeployment : SSHDeployment {
public ScriptDeployment (string local_path) : this (local_path, String.Concat ("/root/", local_path))
{
}
public ScriptDeployment (string local_path, string remote_path)
{
LocalScriptPath = local_path;
RemoteScriptPath = remote_path;
}
public string LocalScriptPath {
get;
private set;
}
public string RemoteScriptPath {
get;
private set;
}
protected override void RunImpl (Node node, NodeAuth auth)
{
if (node == null)
throw new ArgumentNullException ("node");
if (auth == null)
throw new ArgumentNullException ("auth");
if (node.PublicIPs.Count < 1)
throw new ArgumentException ("node", "No public IPs available on node.");
string host = node.PublicIPs [0].ToString ();
CopyScript (host, auth);
RunCommand (RemoteScriptPath, host, auth);
}
private void CopyScript (string host, NodeAuth auth)
{
Scp scp = new Scp (host, auth.UserName);
SetupSSH (scp, auth);
scp.Put (LocalScriptPath, RemoteScriptPath);
scp.Close ();
}
}
}
|
using System;
using Tamir.SharpSsh;
namespace MCloud {
public class ScriptDeployment : PutFileDeployment {
public ScriptDeployment (string local) : base (local)
{
}
public ScriptDeployment (string local, string remote_dir) : base (local, remote_dir)
{
}
protected override void RunImpl (Node node, NodeAuth auth)
{
string host = node.PublicIPs [0].ToString ();
string remote = String.Concat (RemoteDirectory, FileName);
PutFile (host, auth, FileName, remote);
RunCommand (remote, host, auth);
}
}
}
|
Remove NavMeshAgent handling from decision script (not its role) | using UnityEngine;
[CreateAssetMenu (menuName = "AI/Decisions/TargetReached")]
public class Decision_OnTargetReached : Decision {
public bool overrideDistanceToReach;
public float distanceToReach;
public override bool Decide(StateController controller) {
return isTargetReached(controller);
}
private bool isTargetReached(StateController controller) {
var enemyControl = controller as Enemy_StateController;
enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position;
if(!overrideDistanceToReach)
distanceToReach = enemyControl.navMeshAgent.stoppingDistance;
if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) {
enemyControl.navMeshAgent.isStopped = true;
return true;
} else {
enemyControl.navMeshAgent.isStopped = false;
return false;
}
}
}
| using UnityEngine;
[CreateAssetMenu (menuName = "AI/Decisions/TargetReached")]
public class Decision_OnTargetReached : Decision {
public bool overrideDistanceToReach;
public float distanceToReach;
public override bool Decide(StateController controller) {
return isTargetReached(controller);
}
private bool isTargetReached(StateController controller) {
var enemyControl = controller as Enemy_StateController;
enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position;
if(!overrideDistanceToReach)
distanceToReach = enemyControl.navMeshAgent.stoppingDistance;
if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) {
return true;
} else {
return false;
}
}
}
|
Fix correct count 6 -> 7 | using System.Linq;
using Thinktecture.IdentityServer.Core.Services.Contrib;
using Xunit;
namespace Unittests
{
public class AvailableTranslations
{
[Theory]
[InlineData("Default")]
[InlineData("pirate")]
[InlineData("nb-NO")]
[InlineData("tr-TR")]
[InlineData("de-DE")]
[InlineData("sv-SE")]
[InlineData("es-AR")]
public void ContainsLocales(string locale)
{
Assert.Contains(GlobalizedLocalizationService.GetAvailableLocales(), s => s.Equals(locale));
}
[Fact]
public void HasCorrectCount()
{
Assert.Equal(6, GlobalizedLocalizationService.GetAvailableLocales().Count());
}
}
} | using System.Linq;
using Thinktecture.IdentityServer.Core.Services.Contrib;
using Xunit;
namespace Unittests
{
public class AvailableTranslations
{
[Theory]
[InlineData("Default")]
[InlineData("pirate")]
[InlineData("nb-NO")]
[InlineData("tr-TR")]
[InlineData("de-DE")]
[InlineData("sv-SE")]
[InlineData("es-AR")]
public void ContainsLocales(string locale)
{
Assert.Contains(GlobalizedLocalizationService.GetAvailableLocales(), s => s.Equals(locale));
}
[Fact]
public void HasCorrectCount()
{
Assert.Equal(7, GlobalizedLocalizationService.GetAvailableLocales().Count());
}
}
} |
Fix MSBuild tests on macOS/Linux | using System.IO;
namespace TestUtility
{
public static class StringExtensions
{
/// <summary>
/// Given a file or directory path, return a path where all directory separators
/// are replaced with a forward slash (/) character.
/// </summary>
public static string EnsureForwardSlashes(this string path)
=> path.Replace(Path.DirectorySeparatorChar, '/');
}
}
| using System.IO;
namespace TestUtility
{
public static class StringExtensions
{
/// <summary>
/// Given a file or directory path, return a path where all directory separators
/// are replaced with a forward slash (/) character.
/// </summary>
public static string EnsureForwardSlashes(this string path)
=> path.Replace('\\', '/');
}
}
|
Add tests for SA1024 in tuple expressions | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules
{
using Test.SpacingRules;
public class SA1024CSharp7UnitTests : SA1024UnitTests
{
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules
{
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using StyleCop.Analyzers.Test.SpacingRules;
using TestHelper;
using Xunit;
public class SA1024CSharp7UnitTests : SA1024UnitTests
{
/// <summary>
/// Verifies spacing around a <c>:</c> character in tuple expressions.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestSpacingAroundColonInTupleExpressionsAsync()
{
const string testCode = @"using System;
public class Foo
{
public void TestMethod()
{
var values = (x :3, y :4);
}
}";
const string fixedCode = @"using System;
public class Foo
{
public void TestMethod()
{
var values = (x: 3, y: 4);
}
}";
DiagnosticResult[] expected =
{
this.CSharpDiagnostic().WithLocation(7, 25).WithArguments(" not", "preceded", string.Empty),
this.CSharpDiagnostic().WithLocation(7, 25).WithArguments(string.Empty, "followed", string.Empty),
this.CSharpDiagnostic().WithLocation(7, 31).WithArguments(" not", "preceded", string.Empty),
this.CSharpDiagnostic().WithLocation(7, 31).WithArguments(string.Empty, "followed", string.Empty),
};
await this.VerifyCSharpDiagnosticAsync(testCode, expected, CancellationToken.None).ConfigureAwait(false);
await this.VerifyCSharpDiagnosticAsync(fixedCode, EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false);
await this.VerifyCSharpFixAsync(testCode, fixedCode, cancellationToken: CancellationToken.None).ConfigureAwait(false);
}
protected override Solution CreateSolution(ProjectId projectId, string language)
{
Solution solution = base.CreateSolution(projectId, language);
Assembly systemRuntime = AppDomain.CurrentDomain.GetAssemblies().Single(x => x.GetName().Name == "System.Runtime");
return solution
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(systemRuntime.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ValueTuple).Assembly.Location));
}
}
}
|
Fix names and spelling in comments | using System.Reflection;
[assembly: AssemblyCompany("Kentor")]
[assembly: AssemblyCopyright("Copyright Kentor and contributors 2015")]
// Kentor.AuthServices uses semantic versioning in three parts
//
// Major Version
// Minor Version
// Patch Number
//
// An odd patch number is a development version, an even patch number is
// a relased version.
[assembly: AssemblyVersion("0.0.31")]
[assembly: AssemblyFileVersion("0.0.31")]
[assembly: AssemblyInformationalVersion("0.0.31")]
| using System.Reflection;
[assembly: AssemblyCompany("Kentor")]
[assembly: AssemblyCopyright("Copyright Kentor and contributors 2015")]
// Kentor.PU-Adapter uses semantic versioning in three parts
//
// Major Version
// Minor Version
// Patch Number
//
// An odd patch number is a development version, an even patch number is
// a released version.
[assembly: AssemblyVersion("0.0.31")]
[assembly: AssemblyFileVersion("0.0.31")]
[assembly: AssemblyInformationalVersion("0.0.31")]
|
Fix AppVeyor message limit by printing a warning for the 501st report message | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;
namespace Nuke.Common.CI.AppVeyor
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class AppVeyorOutputSink : AnsiColorOutputSink
{
private readonly AppVeyor _appVeyor;
internal AppVeyorOutputSink(AppVeyor appVeyor)
{
_appVeyor = appVeyor;
}
protected override string TraceCode => "90";
protected override string InformationCode => "36;1";
protected override string WarningCode => "33;1";
protected override string ErrorCode => "31;1";
protected override string SuccessCode => "32;1";
protected override void ReportWarning(string text, string details = null)
{
_appVeyor.WriteWarning(text, details);
}
protected override void ReportError(string text, string details = null)
{
_appVeyor.WriteError(text, details);
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Common.OutputSinks;
namespace Nuke.Common.CI.AppVeyor
{
[UsedImplicitly]
[ExcludeFromCodeCoverage]
internal class AppVeyorOutputSink : AnsiColorOutputSink
{
private readonly AppVeyor _appVeyor;
private int _messageCount;
internal AppVeyorOutputSink(AppVeyor appVeyor)
{
_appVeyor = appVeyor;
}
protected override string TraceCode => "90";
protected override string InformationCode => "36;1";
protected override string WarningCode => "33;1";
protected override string ErrorCode => "31;1";
protected override string SuccessCode => "32;1";
protected override void ReportWarning(string text, string details = null)
{
IncreaseAndCheckMessageCount();
_appVeyor.WriteWarning(text, details);
}
protected override void ReportError(string text, string details = null)
{
IncreaseAndCheckMessageCount();
_appVeyor.WriteError(text, details);
}
private void IncreaseAndCheckMessageCount()
{
_messageCount++;
if (_messageCount == 501)
{
base.WriteWarning("AppVeyor has a default limit of 500 messages. " +
"If you're getting an exception from 'appveyor.exe' after this message, " +
"contact https://appveyor.com/support to resolve this issue for your account.");
}
}
}
}
|
Switch to using NSWindow instead of presenter | using MonoMac.Foundation;
using MonoMac.AppKit;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Mac.Platform;
using Cirrious.MvvmCross.Mac.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using System.Drawing;
namespace Pina.Mac
{
public partial class AppDelegate : MvxApplicationDelegate
{
MainWindowController mainWindowController;
public AppDelegate()
{
}
public override void FinishedLaunching (NSObject notification)
{
mainWindowController = new MainWindowController ();
var presenter = new MvxMacViewPresenter (this, mainWindowController.Window);
var setup = new Setup (this, presenter);
setup.Initialize ();
var startup = Mvx.Resolve<IMvxAppStart> ();
startup.Start ();
mainWindowController.Window.MakeKeyAndOrderFront (this);
return;
}
}
}
| using MonoMac.Foundation;
using MonoMac.AppKit;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Mac.Platform;
using Cirrious.MvvmCross.Mac.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using System.Drawing;
namespace Pina.Mac
{
public partial class AppDelegate : MvxApplicationDelegate
{
MainWindowController mainWindowController;
public AppDelegate()
{
}
public override void FinishedLaunching (NSObject notification)
{
mainWindowController = new MainWindowController ();
var setup = new Setup (this, mainWindowController.Window);
setup.Initialize ();
var startup = Mvx.Resolve<IMvxAppStart> ();
startup.Start ();
mainWindowController.Window.MakeKeyAndOrderFront (this);
return;
}
}
}
|
Check when internet connection is disabled | namespace VkApiGenerator.Console
{
class Program
{
static void Main(string[] args)
{
var methods = new[]
{
"notes.get",
"notes.getById",
"notes.getFriendsNotes",
"notes.add",
"notes.edit",
"notes.delete",
"notes.getComments",
"notes.createComment",
"notes.editComment",
"notes.deleteComment",
"notes.restoreComment"
};
var parser = new VkApiParser();
foreach (string methodName in methods)
{
System.Console.WriteLine("*** {0} ***", methodName);
var methodInfo = parser.Parse(methodName);
System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description);
System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText);
System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType);
System.Console.WriteLine("PAPAMETERS:");
foreach (var p in methodInfo.Params)
{
System.Console.WriteLine(" {0} - {1}", p.Name, p.Description);
}
System.Console.WriteLine("\n========================================\n");
System.Console.ReadLine();
}
System.Console.WriteLine("done.");
}
}
}
| using System.Net;
using VkApiGenerator.Model;
namespace VkApiGenerator.Console
{
class Program
{
static void Main(string[] args)
{
var methods = new[]
{
"notes.get",
"notes.getById",
"notes.getFriendsNotes",
"notes.add",
"notes.edit",
"notes.delete",
"notes.getComments",
"notes.createComment",
"notes.editComment",
"notes.deleteComment",
"notes.restoreComment"
};
var parser = new VkApiParser();
foreach (string methodName in methods)
{
System.Console.WriteLine("*** {0} ***", methodName);
VkMethodInfo methodInfo;
try
{
methodInfo = parser.Parse(methodName);
}
catch (WebException ex)
{
System.Console.WriteLine(ex.Message);
continue;
}
System.Console.WriteLine("DESCRIPTION: {0}", methodInfo.Description);
System.Console.WriteLine("RETURN TEXT: {0}", methodInfo.ReturnText);
System.Console.WriteLine("RETURN TYPE: {0}", methodInfo.ReturnType);
System.Console.WriteLine("PAPAMETERS:");
foreach (var p in methodInfo.Params)
{
System.Console.WriteLine(" {0} - {1}", p.Name, p.Description);
}
System.Console.WriteLine("\n========================================\n");
System.Console.ReadLine();
}
System.Console.WriteLine("done.");
}
}
}
|
Add coroutine usage in AEX | using UnityEngine;
using System.Collections;
using ActionEngine;
public static class VeryAwesomeAEX {
public static ActionBase Create (IAEScriptContext ctx) {
var simpleAEX = ctx.GetAEScript("$simple");
var cube = ctx.GetTransform("$cube");
var sphere = ctx.GetTransform("$sphere");
return
AE.Sequence(
AE.Parallel(
// You can use another AEX
simpleAEX.Create(),
// Basic tweens
cube.AEMove(new Vector3(0, -3, 0), 3.5f).Easing(Easings.BounceInOut),
sphere.AEMove(new Vector3(0, 3, 0), 4.5f).Easing(Easings.ElasticOut)
),
AE.Parallel(
cube.AEMove(new Vector3(0, 3, 0), 2.5f).Relative(true).Easing(Easings.BackOut),
sphere.AEMove(new Vector3(0, -3, 0), 3.5f).Relative(true).Easing(Easings.QuadOut)
),
AE.Delay(0.5f),
AE.Debug("All Completed!")
);
}
} | using ActionEngine;
using System.Collections;
using UnityEngine;
public static class VeryAwesomeAEX {
public static ActionBase Create (IAEScriptContext ctx) {
var simpleAEX = ctx.GetAEScript("$simple");
var cube = ctx.GetTransform("$cube");
var sphere = ctx.GetTransform("$sphere");
return
AE.Sequence(
AE.Parallel(
// You can use another AEX
simpleAEX.Create(),
// Basic tweens
cube.AEMove(new Vector3(0, -3, 0), 3.5f).Easing(Easings.BounceInOut),
sphere.AEMove(new Vector3(0, 3, 0), 4.5f).Easing(Easings.ElasticOut)
),
AE.Parallel(
cube.AEMove(new Vector3(0, 3, 0), 2.5f).Relative(true).Easing(Easings.BackOut),
sphere.AEMove(new Vector3(0, -3, 0), 3.5f).Relative(true).Easing(Easings.QuadOut)
),
AE.Coroutine(() => ExampleCoroutine()),
AE.Debug("All Completed!")
);
}
private static IEnumerator ExampleCoroutine () {
Debug.Log("Coroutine Started: " + Time.time);
yield return new WaitForSeconds(2f);
Debug.Log("Coroutine End: " + Time.time);
}
}
|
Add ability to return token from rule | namespace slang.Lexing.Rules.Core
{
public abstract class Rule
{
public static Rule operator | (Rule left, Rule right)
{
return new Or (left, right);
}
public static Rule operator + (Rule left, Rule right)
{
return new And (left, right);
}
public static implicit operator Rule (char value)
{
return new Constant (value);
}
}
}
| using slang.Lexing.Tokens;
using System;
namespace slang.Lexing.Rules.Core
{
public abstract class Rule
{
public Func<Token> TokenCreator { get; set; }
public static Rule operator | (Rule left, Rule right)
{
return new Or (left, right);
}
public static Rule operator + (Rule left, Rule right)
{
return new And (left, right);
}
public static implicit operator Rule (char value)
{
return new Constant (value);
}
public Rule Returns(Func<Token> tokenCreator = null)
{
TokenCreator = tokenCreator ?? new Func<Token>(() => Token.Empty);
return this;
}
}
}
|
Add MVC and middleware to listening only for 'api' requests | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace TodoList.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.IO;
namespace TodoList.Web
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Redirect any non-api calls to the Angular app.
app.Use(async (context, next) => {
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
app.UseMvcWithDefaultRoute();
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
}
|
Mark the playback states with integer values | namespace Espera.Network
{
public enum NetworkPlaybackState
{
None,
Playing,
Paused,
Stopped,
Finished
}
} | namespace Espera.Network
{
public enum NetworkPlaybackState
{
None = 0,
Playing = 1,
Paused = 2,
Stopped = 3,
Finished = 4
}
} |
Check the use of default(T) instead exception. | using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace NHibernate.Test.NHSpecificTest.NH1119
{
[TestFixture]
public class Fixture : BugTestCase
{
public override string BugNumber
{
get { return "NH1119"; }
}
[Test]
public void SelectMinFromEmptyTable()
{
using (ISession s = OpenSession())
{
try
{
DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>();
string msg = "Calling UniqueResult<T> where T is a value type"
+ " should throw InvalidCastException when the result"
+ " is null";
Assert.Fail(msg);
}
catch (InvalidCastException) { }
}
}
}
}
| using System;
using NUnit.Framework;
namespace NHibernate.Test.NHSpecificTest.NH1119
{
[TestFixture]
public class Fixture : BugTestCase
{
public override string BugNumber
{
get { return "NH1119"; }
}
[Test]
public void SelectMinFromEmptyTable()
{
using (ISession s = OpenSession())
{
DateTime dt = s.CreateQuery("select max(tc.DateTimeProperty) from TestClass tc").UniqueResult<DateTime>();
Assert.AreEqual(default(DateTime), dt);
}
}
}
}
|
Set the detail instead of the title | using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static Hellang.Middleware.ProblemDetails.ProblemDetailsOptionsSetup;
using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
internal class ProblemDetailsResultFilter : IAlwaysRunResultFilter, IOrderedFilter
{
public ProblemDetailsResultFilter(MvcProblemDetailsFactory factory)
{
Factory = factory;
}
/// <summary>
/// The same order as the built-in ClientErrorResultFilter.
/// </summary>
public int Order => -2000;
private MvcProblemDetailsFactory Factory { get; }
public void OnResultExecuting(ResultExecutingContext context)
{
// Only handle ObjectResult for now.
if (context.Result is not ObjectResult result)
{
return;
}
// Make sure the result should be treated as a problem.
if (!IsProblemStatusCode(result.StatusCode))
{
return;
}
// Only handle the string case for now.
if (result.Value is not string title)
{
return;
}
var problemDetails = Factory.CreateProblemDetails(context.HttpContext, result.StatusCode, title);
context.Result = new ObjectResult(problemDetails)
{
StatusCode = problemDetails.Status,
ContentTypes = {
"application/problem+json",
"application/problem+xml",
},
};
}
void IResultFilter.OnResultExecuted(ResultExecutedContext context)
{
// Not needed.
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using static Hellang.Middleware.ProblemDetails.ProblemDetailsOptionsSetup;
using MvcProblemDetails = Microsoft.AspNetCore.Mvc.ProblemDetails;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
internal class ProblemDetailsResultFilter : IAlwaysRunResultFilter, IOrderedFilter
{
public ProblemDetailsResultFilter(MvcProblemDetailsFactory factory)
{
Factory = factory;
}
/// <summary>
/// The same order as the built-in ClientErrorResultFilter.
/// </summary>
public int Order => -2000;
private MvcProblemDetailsFactory Factory { get; }
public void OnResultExecuting(ResultExecutingContext context)
{
// Only handle ObjectResult for now.
if (context.Result is not ObjectResult result)
{
return;
}
// Make sure the result should be treated as a problem.
if (!IsProblemStatusCode(result.StatusCode))
{
return;
}
// Only handle the string case for now.
if (result.Value is not string detail)
{
return;
}
var problemDetails = Factory.CreateProblemDetails(context.HttpContext, result.StatusCode, detail: detail);
context.Result = new ObjectResult(problemDetails)
{
StatusCode = problemDetails.Status,
ContentTypes = {
"application/problem+json",
"application/problem+xml",
},
};
}
void IResultFilter.OnResultExecuted(ResultExecutedContext context)
{
// Not needed.
}
}
}
|
Fix missing logger by moving the expanded detail to the exception | using System;
using System.Collections.Generic;
using System.IO;
public class ConfigFileFinder
{
public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory)
{
var files = new List<string>();
var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml");
if (File.Exists(solutionConfigFilePath))
{
files.Add(solutionConfigFilePath);
logger.LogDebug($"Found path to weavers file '{solutionConfigFilePath}'.");
}
var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml");
if (!File.Exists(projectConfigFilePath))
{
logger.LogDebug($@"Could not file a FodyWeavers.xml at the project level ({projectConfigFilePath}). Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content:
<Weavers>
<WeaverName/>
</Weavers>
");
}
else
{
files.Add(projectConfigFilePath);
logger.LogDebug($"Found path to weavers file '{projectConfigFilePath}'.");
}
if (files.Count == 0)
{
// ReSharper disable once UnusedVariable
var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath);
throw new WeavingException($"Could not find path to weavers file. Searched '{pathsSearched}'.");
}
return files;
}
} | using System;
using System.Collections.Generic;
using System.IO;
public class ConfigFileFinder
{
public static List<string> FindWeaverConfigs(string solutionDirectoryPath, string projectDirectory)
{
var files = new List<string>();
var solutionConfigFilePath = Path.Combine(solutionDirectoryPath, "FodyWeavers.xml");
if (File.Exists(solutionConfigFilePath))
{
files.Add(solutionConfigFilePath);
}
var projectConfigFilePath = Path.Combine(projectDirectory, "FodyWeavers.xml");
if (File.Exists(projectConfigFilePath))
{
files.Add(projectConfigFilePath);
}
if (files.Count == 0)
{
// ReSharper disable once UnusedVariable
var pathsSearched = string.Join("', '", solutionConfigFilePath, projectConfigFilePath);
throw new WeavingException($@"Could not find path to weavers file. Searched '{pathsSearched}'. Some project types do not support using NuGet to add content files e.g. netstandard projects. In these cases it is necessary to manually add a FodyWeavers.xml to the project. Example content:
<Weavers>
<WeaverName/>
</Weavers>
");
}
return files;
}
} |
Change LinterVersion output to json format | namespace Linterhub.Cli.Strategy
{
using Runtime;
using Engine;
using Linterhub.Engine.Exceptions;
public class LinterVersionStrategy : IStrategy
{
public object Run(RunContext context, LinterFactory factory, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
var result = "";
var versionCmd = factory.BuildVersionCommand(context.Linter);
//System.Console.WriteLine(versionCmd);
var version = string.IsNullOrEmpty(versionCmd) ? "Unknown" : new LinterhubWrapper(context).LinterVersion(context.Linter, versionCmd).Trim();
result += $"\n{context.Linter}: {version}";
return result;
}
}
} | namespace Linterhub.Cli.Strategy
{
using Runtime;
using Engine;
using Linterhub.Engine.Exceptions;
using Newtonsoft.Json;
using System.Dynamic;
public class LinterVersionStrategy : IStrategy
{
public object Run(RunContext context, LinterFactory factory, LogManager log)
{
if (string.IsNullOrEmpty(context.Linter))
{
throw new LinterEngineException("Linter is not specified: " + context.Linter);
}
dynamic result = new ExpandoObject();
var versionCmd = factory.BuildVersionCommand(context.Linter);
var version = new LinterhubWrapper(context).LinterVersion(context.Linter, versionCmd).Trim();
result.LinterName = context.Linter;
result.Installed = version.Contains("Can\'t find " + context.Linter) ? "No" : "Yes";
result.Version = ((string)result.Installed).Contains("No") ? "Unknown" : version;
return JsonConvert.SerializeObject(result);
}
}
} |
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.FakeItEasy 3.0.0-beta")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.FakeItEasy 3.0.0-beta")]
|
Add back test cleanup before run | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
{
host.Run(new OsuTestCaseTestRunner(this));
}
// clean up after each run
//storage.DeleteDirectory(string.Empty);
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Game.Tests.Visual
{
public abstract class OsuTestCase : TestCase
{
public override void RunTest()
{
using (var host = new HeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false))
{
host.Storage.DeleteDirectory(string.Empty);
host.Run(new OsuTestCaseTestRunner(this));
}
}
public class OsuTestCaseTestRunner : OsuGameBase
{
private readonly OsuTestCase testCase;
public OsuTestCaseTestRunner(OsuTestCase testCase)
{
this.testCase = testCase;
}
protected override void LoadComplete()
{
base.LoadComplete();
Add(new TestCaseTestRunner.TestRunner(testCase));
}
}
}
}
|
Fix sidereal calculations for sun | using System;
namespace LunaClient.Extensions
{
public static class CelestialBodyExtension
{
public static double SiderealDayLength(this CelestialBody body)
{
//Taken from CelestialBody.Start()
if (body == null) return 0;
var siderealOrbitalPeriod = 6.28318530717959 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
return body.rotationPeriod * siderealOrbitalPeriod / (siderealOrbitalPeriod + body.rotationPeriod);
}
}
}
| using System;
namespace LunaClient.Extensions
{
public static class CelestialBodyExtension
{
public static double SiderealDayLength(this CelestialBody body)
{
//Taken from CelestialBody.Start()
//body.solarRotationPeriod will be false if it's the sun!
if (body == null || body.orbit == null || !body.solarRotationPeriod) return 0;
var siderealOrbitalPeriod = 6.28318530717959 * Math.Sqrt(Math.Pow(Math.Abs(body.orbit.semiMajorAxis), 3) / body.orbit.referenceBody.gravParameter);
return body.rotationPeriod * siderealOrbitalPeriod / (siderealOrbitalPeriod + body.rotationPeriod);
}
}
}
|
Use Smtp PickUp delivery for stubbing saving of emails locally | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using VORBS.Utils.interfaces;
namespace VORBS.Utils
{
public class StubbedEmailClient : ISmtpClient
{
private NLog.Logger _logger;
public StubbedEmailClient()
{
_logger = NLog.LogManager.GetCurrentClassLogger();
_logger.Trace(LoggerHelper.InitializeClassMessage());
}
public LinkedResource GetLinkedResource(string path, string id)
{
LinkedResource resource = new LinkedResource(path);
resource.ContentId = id;
_logger.Trace(LoggerHelper.ExecutedFunctionMessage(resource, path, id));
return resource;
}
public void Send(MailMessage message)
{
string rootDirectory = $@"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Logs/{DateTime.Now.ToString("yyyy-MM-dd")}/EmailLogs/{message.To.FirstOrDefault().User}";
if (!Directory.Exists(rootDirectory))
Directory.CreateDirectory(rootDirectory);
string fileName = $"{message.Subject}_{DateTime.Now.ToString("hh-mm-ss")}";
using (FileStream fs = File.Create($"{rootDirectory}/{fileName}.html"))
{
StringBuilder builder = new StringBuilder();
builder.AppendLine($"From: {message.From}");
builder.AppendLine($"To: {message.To}");
builder.AppendLine($"BCC: {message.Bcc}");
builder.AppendLine($"Subject: {message.Subject}");
builder.AppendLine(message.Body);
byte[] info = new UTF8Encoding(true).GetBytes(builder.ToString());
fs.Write(info, 0, info.Length);
// writing data in bytes already
byte[] data = new byte[] { 0x0 };
fs.Write(data, 0, data.Length);
}
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Web;
using VORBS.Utils.interfaces;
namespace VORBS.Utils
{
public class StubbedEmailClient : ISmtpClient
{
private NLog.Logger _logger;
public StubbedEmailClient()
{
_logger = NLog.LogManager.GetCurrentClassLogger();
_logger.Trace(LoggerHelper.InitializeClassMessage());
}
public LinkedResource GetLinkedResource(string path, string id)
{
LinkedResource resource = new LinkedResource(path);
resource.ContentId = id;
_logger.Trace(LoggerHelper.ExecutedFunctionMessage(resource, path, id));
return resource;
}
public void Send(MailMessage message)
{
SmtpClient client = new SmtpClient("stubbedhostname");
client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
string rootDirectory = $@"{AppDomain.CurrentDomain.SetupInformation.ApplicationBase}Logs/{DateTime.Now.ToString("yyyy-MM-dd")}/EmailLogs/{message.To.FirstOrDefault().User}";
if (!Directory.Exists(rootDirectory))
Directory.CreateDirectory(rootDirectory);
client.PickupDirectoryLocation = rootDirectory;
client.Send(message);
}
}
} |
Add Google Plus +1 to AddThis defaults | @using CkanDotNet.Web.Models.Helpers
<!-- AddThis Button BEGIN -->
<div class="share-buttons">
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=@SettingsHelper.GetAddThisProfileId()"></script>
<!-- AddThis Button END --> | @using CkanDotNet.Web.Models.Helpers
<!-- AddThis Button BEGIN -->
<div class="share-buttons">
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_google_plusone"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=@SettingsHelper.GetAddThisProfileId()"></script>
<!-- AddThis Button END --> |
Implement proper disposable pattern to satisfy sonarcloud's compaint of a code smell :/ | /* © 2019 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */
using NuLog.Configuration;
using NuLog.LogEvents;
using System;
namespace NuLog.CLI.Benchmarking {
/// <summary>
/// A dummy target for performance testing - we need to see the raw results of the engine, not
/// the individual target.
/// </summary>
public class DummyTarget : ITarget {
public string Name { get; set; }
public void Configure(TargetConfig config) {
// noop
}
public void Dispose() {
// noop
}
public void Write(LogEvent logEvent) {
// noop
}
}
} | /* © 2019 Ivan Pointer
MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE
Source on GitHub: https://github.com/ivanpointer/NuLog */
using NuLog.Configuration;
using NuLog.LogEvents;
using System;
namespace NuLog.CLI.Benchmarking {
/// <summary>
/// A dummy target for performance testing - we need to see the raw results of the engine, not
/// the individual target.
/// </summary>
public class DummyTarget : ITarget {
public string Name { get; set; }
public void Configure(TargetConfig config) {
// noop
}
public void Write(LogEvent logEvent) {
// noop
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing) {
if (!disposedValue) {
if (disposing) {
// noop
}
// noop
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion IDisposable Support
}
} |
Remove usage of legacy code | #region Usings
using System;
using System.Collections.Generic;
using System.Windows.Input;
using ReactiveUI.Legacy;
using UI.WPF.Launcher.Common.Classes;
#endregion
namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
public class InstallationViewModel : ReactiveObjectBase
{
private InstallationItemParent _installationParent;
private InstallationItemParent _uninstallationParent;
public ICommand CloseCommand { get; private set; }
public InstallationViewModel(Action closeAction)
{
var cmd = new ReactiveCommand();
cmd.Subscribe(_ => closeAction());
CloseCommand = cmd;
}
public InstallationItemParent InstallationParent
{
get { return _installationParent; }
private set { RaiseAndSetIfPropertyChanged(ref _installationParent, value); }
}
public InstallationItemParent UninstallationParent
{
get { return _uninstallationParent; }
private set { RaiseAndSetIfPropertyChanged(ref _uninstallationParent, value); }
}
public IEnumerable<InstallationItem> InstallationItems
{
set { InstallationParent = new InstallationItemParent(null, value); }
}
public IEnumerable<InstallationItem> UninstallationItems
{
set { UninstallationParent = new InstallationItemParent(null, value); }
}
}
}
| #region Usings
using System;
using System.Collections.Generic;
using System.Windows.Input;
using ReactiveUI;
using UI.WPF.Launcher.Common.Classes;
#endregion
namespace UI.WPF.Modules.Installation.ViewModels.Installation
{
public class InstallationViewModel : ReactiveObjectBase
{
private InstallationItemParent _installationParent;
private InstallationItemParent _uninstallationParent;
public ICommand CloseCommand { get; private set; }
public InstallationViewModel(Action closeAction)
{
var cmd = ReactiveCommand.Create();
cmd.Subscribe(_ => closeAction());
CloseCommand = cmd;
}
public InstallationItemParent InstallationParent
{
get { return _installationParent; }
private set { RaiseAndSetIfPropertyChanged(ref _installationParent, value); }
}
public InstallationItemParent UninstallationParent
{
get { return _uninstallationParent; }
private set { RaiseAndSetIfPropertyChanged(ref _uninstallationParent, value); }
}
public IEnumerable<InstallationItem> InstallationItems
{
set { InstallationParent = new InstallationItemParent(null, value); }
}
public IEnumerable<InstallationItem> UninstallationItems
{
set { UninstallationParent = new InstallationItemParent(null, value); }
}
}
}
|
Use file name as the name of a Cursor Set | using System.Collections.Generic;
using System.Linq;
using Alensia.Core.Common;
using UnityEngine;
namespace Alensia.Core.UI.Cursor
{
public class CursorSet : ScriptableObject, IDirectory<CursorDefinition>, IEditorSettings
{
protected IDictionary<string, CursorDefinition> CursorMap
{
get
{
lock (this)
{
if (_cursorMap != null) return _cursorMap;
_cursorMap = new Dictionary<string, CursorDefinition>();
foreach (var cursor in _cursors.Concat<CursorDefinition>(_animatedCursors))
{
_cursorMap.Add(cursor.Name, cursor);
}
return _cursorMap;
}
}
}
[SerializeField] private StaticCursor[] _cursors;
[SerializeField] private AnimatedCursor[] _animatedCursors;
private IDictionary<string, CursorDefinition> _cursorMap;
public bool Contains(string key) => CursorMap.ContainsKey(key);
public CursorDefinition this[string key] => CursorMap[key];
private void OnEnable()
{
_cursors = _cursors?.OrderBy(c => c.Name).ToArray();
_animatedCursors = _animatedCursors?.OrderBy(c => c.Name).ToArray();
}
private void OnValidate() => _cursorMap = null;
private void OnDestroy() => _cursorMap = null;
}
} | using System.Collections.Generic;
using System.Linq;
using Alensia.Core.Common;
using UnityEngine;
namespace Alensia.Core.UI.Cursor
{
public class CursorSet : ScriptableObject, INamed, IDirectory<CursorDefinition>, IEditorSettings
{
public string Name => name;
protected IDictionary<string, CursorDefinition> CursorMap
{
get
{
lock (this)
{
if (_cursorMap != null) return _cursorMap;
_cursorMap = new Dictionary<string, CursorDefinition>();
foreach (var cursor in _cursors.Concat<CursorDefinition>(_animatedCursors))
{
_cursorMap.Add(cursor.Name, cursor);
}
return _cursorMap;
}
}
}
[SerializeField] private StaticCursor[] _cursors;
[SerializeField] private AnimatedCursor[] _animatedCursors;
private IDictionary<string, CursorDefinition> _cursorMap;
public bool Contains(string key) => CursorMap.ContainsKey(key);
public CursorDefinition this[string key] => CursorMap[key];
private void OnEnable()
{
_cursors = _cursors?.OrderBy(c => c.Name).ToArray();
_animatedCursors = _animatedCursors?.OrderBy(c => c.Name).ToArray();
}
private void OnValidate() => _cursorMap = null;
private void OnDestroy() => _cursorMap = null;
}
} |
Fix new lines in console | using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace GUI.Utils
{
internal class ConsoleTab
{
internal class MyLogger : TextWriter
{
private TextBox control;
public MyLogger(TextBox control)
{
this.control = control;
}
public override Encoding Encoding => null;
public override void WriteLine(string value)
{
var logLine = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] {value}\n";
control.AppendText(logLine);
}
}
public TabPage CreateTab()
{
var control = new TextBox
{
Dock = DockStyle.Fill,
Multiline = true,
ReadOnly = true,
WordWrap = true,
ScrollBars = ScrollBars.Vertical,
BorderStyle = BorderStyle.None,
BackColor = Color.Black,
ForeColor = Color.WhiteSmoke,
};
var tab = new TabPage("Console");
tab.Controls.Add(control);
Console.SetOut(new MyLogger(control));
return tab;
}
}
}
| using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace GUI.Utils
{
internal class ConsoleTab
{
internal class MyLogger : TextWriter
{
private TextBox control;
public MyLogger(TextBox control)
{
this.control = control;
}
public override Encoding Encoding => null;
public override void WriteLine(string value)
{
var logLine = $"[{DateTime.Now.ToString("HH:mm:ss.fff")}] {value}{Environment.NewLine}";
control.AppendText(logLine);
}
}
public TabPage CreateTab()
{
var control = new TextBox
{
Dock = DockStyle.Fill,
Multiline = true,
ReadOnly = true,
WordWrap = true,
ScrollBars = ScrollBars.Vertical,
BorderStyle = BorderStyle.None,
BackColor = Color.Black,
ForeColor = Color.WhiteSmoke,
};
var tab = new TabPage("Console");
tab.Controls.Add(control);
Console.SetOut(new MyLogger(control));
return tab;
}
}
}
|
Modify DialogsPage to allow testing of startup location. | using Avalonia.Controls;
using Avalonia.Markup.Xaml;
#pragma warning disable 4014
namespace ControlCatalog.Pages
{
public class DialogsPage : UserControl
{
public DialogsPage()
{
this.InitializeComponent();
this.FindControl<Button>("OpenFile").Click += delegate
{
new OpenFileDialog()
{
Title = "Open file"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("SaveFile").Click += delegate
{
new SaveFileDialog()
{
Title = "Save file"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("SelectFolder").Click += delegate
{
new OpenFolderDialog()
{
Title = "Select folder"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("DecoratedWindow").Click += delegate
{
new DecoratedWindow().Show();
};
this.FindControl<Button>("DecoratedWindowDialog").Click += delegate
{
new DecoratedWindow().ShowDialog(GetWindow());
};
this.FindControl<Button>("Dialog").Click += delegate
{
new MainWindow().ShowDialog(GetWindow());
};
}
Window GetWindow() => (Window)this.VisualRoot;
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| using Avalonia.Controls;
using Avalonia.Markup.Xaml;
#pragma warning disable 4014
namespace ControlCatalog.Pages
{
public class DialogsPage : UserControl
{
public DialogsPage()
{
this.InitializeComponent();
this.FindControl<Button>("OpenFile").Click += delegate
{
new OpenFileDialog()
{
Title = "Open file"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("SaveFile").Click += delegate
{
new SaveFileDialog()
{
Title = "Save file"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("SelectFolder").Click += delegate
{
new OpenFolderDialog()
{
Title = "Select folder"
}.ShowAsync(GetWindow());
};
this.FindControl<Button>("DecoratedWindow").Click += delegate
{
new DecoratedWindow().Show();
};
this.FindControl<Button>("DecoratedWindowDialog").Click += delegate
{
new DecoratedWindow().ShowDialog(GetWindow());
};
this.FindControl<Button>("Dialog").Click += delegate
{
var window = new Window();
window.Height = 200;
window.Width = 200;
window.Content = new TextBlock { Text = "Hello world!" };
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
window.ShowDialog(GetWindow());
};
}
Window GetWindow() => (Window)this.VisualRoot;
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
|
Add copyright to one more .cs source file. | namespace ShoutLib
{
internal class Constants
{
public const string ProjectId = "YOUR-PROJECT-ID";
public const string ServiceAccountEmail = "YOUR-SERVICE-ACCOUNT@developer.gserviceaccount.com";
public const string ServiceAccountP12KeyPath = @"C:\PATH\TO\YOUR\FILE.p12";
public const string Subscription = "shout-tasks-workers";
public const string UserAgent = "Shouter";
}
} | // Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace ShoutLib
{
internal class Constants
{
public const string ProjectId = "YOUR-PROJECT-ID";
public const string ServiceAccountEmail = "YOUR-SERVICE-ACCOUNT@developer.gserviceaccount.com";
public const string ServiceAccountP12KeyPath = @"C:\PATH\TO\YOUR\FILE.p12";
public const string Subscription = "shout-tasks-workers";
public const string UserAgent = "Shouter";
}
} |
Add a timer and log to sms sending | using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber)
{
this._twilioAccountSId = twilioAccountSid;
this._twilioAuthToken = twilioAuthToken;
this._twilioSourceNumber = twilioSourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
// TODO Add logging
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
} | using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber)
{
this._twilioAccountSId = twilioAccountSid;
this._twilioAuthToken = twilioAuthToken;
this._twilioSourceNumber = twilioSourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync"))
{
Log.Info("Sending SMSNotification {@Notification}", notification);
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
}
} |
Fix support for input and fix some bugs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class GenericInput : BasicObject
{
public override byte objectTypeId { get { return 11; } }
public byte inputPin { get; set; }
public byte debounceTime { get; set; }
protected override void Serialize(List<byte> buffer)
{
buffer.Add(this.inputPin);
buffer.Add(this.debounceTime);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class GenericInput : BasicObject
{
public override byte objectTypeId { get { return 11; } }
public byte inputPin { get; set; }
public byte debounceTime { get; set; }
public byte releaseHoldTime { get; set; }
protected override void Serialize(List<byte> buffer)
{
buffer.Add(this.inputPin);
buffer.Add(this.debounceTime);
buffer.Add(this.releaseHoldTime);
}
}
}
|
Comment out the sample tests | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using System.IO;
namespace ParkingSpace.Facts.Sample {
public class SampleFileFacts {
public static IEnumerable<object[]> getFilesFromCurrentFolder() {
var di = new DirectoryInfo(Environment.CurrentDirectory);
foreach(var file in di.EnumerateFiles()) {
yield return new object[] { file.Name };
}
}
[Trait("Category", "Sample")]
[Theory]
[MemberData("getFilesFromCurrentFolder")]
//[InlineData("sample1.txt")]
//[InlineData("sample20.exe")]
public void FileNameMustHasThreeCharactersExtension(string fileName) {
var length = Path.GetExtension(fileName).Length;
Assert.Equal(4, length); // include 'dot' in front of the extension (.dll, .exe)
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using System.IO;
namespace ParkingSpace.Facts.Sample {
public class SampleFileFacts {
public static IEnumerable<object[]> getFilesFromCurrentFolder() {
var di = new DirectoryInfo(Environment.CurrentDirectory);
foreach(var file in di.EnumerateFiles()) {
yield return new object[] { file.Name };
}
}
//[Trait("Category", "Sample")]
//[Theory]
//[MemberData("getFilesFromCurrentFolder")]
////[InlineData("sample1.txt")]
////[InlineData("sample20.exe")]
//public void FileNameMustHasThreeCharactersExtension(string fileName) {
// var length = Path.GetExtension(fileName).Length;
// Assert.Equal(4, length); // include 'dot' in front of the extension (.dll, .exe)
//}
}
}
|
Save all the lines of code! | using ReactiveMarrow;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace Espera.Core
{
internal static class ReactiveHelpers
{
/// <summary>
/// Takes the left observable and combines it with the latest value of the right observable.
/// This method is like <see cref="Observable.CombineLatest{TSource1,TSource2,TResult}"/>,
/// except it propagates only when the value of the left observable sequence changes.
/// </summary>
public static IObservable<TResult> Left<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> resultSelector)
{
TRight latest = default(TRight);
bool initialized = false;
var disp = new CompositeDisposable(2);
right.Subscribe(x =>
{
latest = x;
initialized = true;
}).DisposeWith(disp);
return Observable.Create<TResult>(o =>
{
left.Subscribe(x =>
{
if (initialized)
{
o.OnNext(resultSelector(x, latest));
}
}, o.OnError, o.OnCompleted).DisposeWith(disp);
return disp;
});
}
}
} | using ReactiveMarrow;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace Espera.Core
{
internal static class ReactiveHelpers
{
/// <summary>
/// Takes the left observable and combines it with the latest value of the right observable.
/// This method is like <see cref="Observable.CombineLatest{TSource1,TSource2,TResult}"/>,
/// except it propagates only when the value of the left observable sequence changes.
/// </summary>
public static IObservable<TResult> Left<TLeft, TRight, TResult>(this IObservable<TLeft> left, IObservable<TRight> right, Func<TLeft, TRight, TResult> resultSelector)
{
TRight latest = default(TRight);
bool initialized = false;
var disp = new CompositeDisposable(2);
right.Subscribe(x =>
{
latest = x;
initialized = true;
}).DisposeWith(disp);
return Observable.Create<TResult>(o =>
{
left.Where(_ => initialized)
.Subscribe(x => o.OnNext(resultSelector(x, latest)),
o.OnError, o.OnCompleted)
.DisposeWith(disp);
return disp;
});
}
}
} |
Add license to new unit test class file | using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestUsefullFunctions
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.IsTrue(true);
}
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestUsefullFunctions
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.IsTrue(true);
}
}
} |
Set property item as localizable only if Localizable attribute value is true | using Serenity.ComponentModel;
using Serenity.Data;
using System;
using System.ComponentModel;
using System.Reflection;
namespace Serenity.PropertyGrid
{
public partial class LocalizablePropertyProcessor : PropertyProcessor
{
private ILocalizationRowHandler localizationRowHandler;
public override void Initialize()
{
if (BasedOnRow == null)
return;
var attr = BasedOnRow.GetType().GetCustomAttribute<LocalizationRowAttribute>(false);
if (attr != null)
localizationRowHandler = Activator.CreateInstance(typeof(LocalizationRowHandler<>)
.MakeGenericType(BasedOnRow.GetType())) as ILocalizationRowHandler;
}
public override void Process(IPropertySource source, PropertyItem item)
{
var attr = source.GetAttribute<LocalizableAttribute>();
if (attr != null)
{
item.Localizable = true;
return;
}
if (!ReferenceEquals(null, source.BasedOnField) &&
localizationRowHandler != null &&
localizationRowHandler.IsLocalized(source.BasedOnField))
{
item.Localizable = true;
}
}
public override int Priority
{
get { return 15; }
}
}
} | using Serenity.ComponentModel;
using Serenity.Data;
using System;
using System.ComponentModel;
using System.Reflection;
namespace Serenity.PropertyGrid
{
public partial class LocalizablePropertyProcessor : PropertyProcessor
{
private ILocalizationRowHandler localizationRowHandler;
public override void Initialize()
{
if (BasedOnRow == null)
return;
var attr = BasedOnRow.GetType().GetCustomAttribute<LocalizationRowAttribute>(false);
if (attr != null)
localizationRowHandler = Activator.CreateInstance(typeof(LocalizationRowHandler<>)
.MakeGenericType(BasedOnRow.GetType())) as ILocalizationRowHandler;
}
public override void Process(IPropertySource source, PropertyItem item)
{
var attr = source.GetAttribute<LocalizableAttribute>();
if (attr != null)
{
if (item.IsLocalizable)
item.Localizable = true;
return;
}
if (!ReferenceEquals(null, source.BasedOnField) &&
localizationRowHandler != null &&
localizationRowHandler.IsLocalized(source.BasedOnField))
{
item.Localizable = true;
}
}
public override int Priority
{
get { return 15; }
}
}
}
|
Improve persistent session client test | using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class PersistentSessionHttpClientTests
{
[TestMethod]
public void GetTest()
{
const string testCookieName = "testCookieName";
const string testCookieValue = "testCookieValue";
var client = new PersistentSessionHttpClient();
client.Get($"http://httpbin.org/cookies/set/{testCookieName}/{testCookieValue}");
var response = client.Get("http://httpbin.org/cookies");
Assert.IsTrue(response.Contains(testCookieName) && response.Contains(testCookieValue), $"Response should contain both {testCookieName} and {testCookieValue}");
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
using RohlikAPI;
namespace RohlikAPITests
{
[TestClass]
public class PersistentSessionHttpClientTests
{
[TestMethod]
public void HTTPGet_PersistsCookies()
{
const string testCookieName = "testCookieName";
const string testCookieValue = "testCookieValue";
var client = new PersistentSessionHttpClient();
client.Get($"http://httpbin.org/cookies/set/{testCookieName}/{testCookieValue}");
var response = client.Get("http://httpbin.org/cookies");
Assert.IsTrue(response.Contains(testCookieName) && response.Contains(testCookieValue), $"Response should contain both {testCookieName} and {testCookieValue}");
}
}
} |
Check parameters and add friendly exceptions. | using System;
using System.Linq;
namespace MQTTnet.Extensions
{
public static class UserPropertyExtension
{
public static string GetUserProperty(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
return message?.UserProperties?.SingleOrDefault(up => up.Name.Equals(propertyName, comparisonType))?.Value;
}
public static T GetUserProperty<T>(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
return (T) Convert.ChangeType(GetUserProperty(message, propertyName, comparisonType), typeof(T));
}
}
}
| using System;
using System.Linq;
namespace MQTTnet.Extensions
{
public static class UserPropertyExtension
{
public static string GetUserProperty(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
if (message == null) throw new ArgumentNullException(nameof(message));
if (propertyName == null) throw new ArgumentNullException(nameof(propertyName));
return message.UserProperties?.SingleOrDefault(up => up.Name.Equals(propertyName, comparisonType))?.Value;
}
public static T GetUserProperty<T>(this MqttApplicationMessage message, string propertyName, StringComparison comparisonType = StringComparison.OrdinalIgnoreCase)
{
var value = GetUserProperty(message, propertyName, comparisonType);
try
{
return (T) Convert.ChangeType(value, typeof(T));
}
catch (Exception ex)
{
throw new InvalidOperationException($"Cannot convert value({value}) of UserProperty({propertyName}) to {typeof(T).FullName}.", ex);
}
}
}
}
|
Fix new unit test to fail if it does not throw properly | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Linq;
using Microsoft.WindowsAzure.MobileServices.Test.Functional;
using Microsoft.WindowsAzure.MobileServices.TestFramework;
namespace Microsoft.WindowsAzure.MobileServices.Test
{
[Tag("push")]
public class PushUnit : TestBase
{
[TestMethod]
public void InvalidBodyTemplateIfNotXml()
{
try
{
var registration = new TemplateRegistration("uri", "junkBodyTemplate", "testName");
}
catch (ArgumentException e)
{
// PASSES
}
}
[TestMethod]
public void InvalidBodyTemplateIfImproperXml()
{
try
{
var registration = new TemplateRegistration(
"uri",
"<foo><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></foo>",
"testName");
}
catch (ArgumentException e)
{
// PASSES
}
}
}
} | // ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
using System;
using System.Linq;
using Microsoft.WindowsAzure.MobileServices.Test.Functional;
using Microsoft.WindowsAzure.MobileServices.TestFramework;
namespace Microsoft.WindowsAzure.MobileServices.Test
{
[Tag("push")]
public class PushUnit : TestBase
{
[TestMethod]
public void InvalidBodyTemplateIfNotXml()
{
try
{
var registration = new TemplateRegistration("uri", "junkBodyTemplate", "testName");
Assert.Fail("Expected templateBody that is not XML to throw ArgumentException");
}
catch (ArgumentException e)
{
// PASSES
}
}
[TestMethod]
public void InvalidBodyTemplateIfImproperXml()
{
try
{
var registration = new TemplateRegistration(
"uri",
"<foo><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></foo>",
"testName");
Assert.Fail("Expected templateBody with unexpected first XML node to throw ArgumentException");
}
catch (ArgumentException e)
{
// PASSES
}
}
}
} |
Fix fault in context menu | // Copyright (c) 2013 Blue Onion Software - All rights reserved
using System.Windows.Documents;
using System.Windows.Input;
using tweetz5.Model;
namespace tweetz5.Controls
{
public partial class Timeline
{
public TimelineController Controller { get; private set; }
public Timeline()
{
InitializeComponent();
Controller = new TimelineController((Timelines)DataContext);
Controller.StartTimelines();
Unloaded += (sender, args) => Controller.Dispose();
}
private void MoreOnMouseDown(object sender, MouseButtonEventArgs e)
{
var span = sender as Span;
span.ContextMenu.PlacementTarget = this;
span.ContextMenu.DataContext = span.DataContext;
span.ContextMenu.IsOpen = true;
}
}
} | // Copyright (c) 2013 Blue Onion Software - All rights reserved
using System.Windows;
using System.Windows.Input;
using tweetz5.Model;
namespace tweetz5.Controls
{
public partial class Timeline
{
public TimelineController Controller { get; private set; }
public Timeline()
{
InitializeComponent();
Controller = new TimelineController((Timelines)DataContext);
Controller.StartTimelines();
Unloaded += (sender, args) => Controller.Dispose();
}
private void MoreOnMouseDown(object sender, MouseButtonEventArgs e)
{
var frameworkElement = sender as FrameworkElement;
frameworkElement.ContextMenu.PlacementTarget = this;
frameworkElement.ContextMenu.DataContext = frameworkElement.DataContext;
frameworkElement.ContextMenu.IsOpen = true;
}
}
} |
Add the col class. (It move the button to the right a little) | @using AnlabMvc.Controllers
@model AnlabMvc.Controllers.AdminAnalysisController.AnalysisDeleteModel
@{
ViewBag.Title = "Delete Analysis Method";
}
<div>
<hr />
<h3>Are you sure you want to delete this?</h3>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Id)
</dt>
<dd>
@Html.DisplayFor(model => model.AnalysisMethod.Id)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.AnalysisMethod.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Category)
</dt>
<dd>
@Html.DisplayFor(model => model.AnalysisMethod.Category)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Content)
</dt>
<dd>
@Html.Raw(Model.HtmlContent)
</dd>
</dl>
<form asp-action="Delete">
<div class="form-actions no-color col-md-offset-1">
<input type="submit" value="Delete" class="btn btn-default" />
</div>
<a asp-action="Index">Back to List</a>
</form>
</div>
| @using AnlabMvc.Controllers
@model AnlabMvc.Controllers.AdminAnalysisController.AnalysisDeleteModel
@{
ViewBag.Title = "Delete Analysis Method";
}
<div class="col">
<hr />
<h3>Are you sure you want to delete this?</h3>
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Id)
</dt>
<dd>
@Html.DisplayFor(model => model.AnalysisMethod.Id)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.AnalysisMethod.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Category)
</dt>
<dd>
@Html.DisplayFor(model => model.AnalysisMethod.Category)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AnalysisMethod.Content)
</dt>
<dd>
@Html.Raw(Model.HtmlContent)
</dd>
</dl>
<form asp-action="Delete">
<div class="form-actions no-color col-md-offset-1">
<input type="submit" value="Delete" class="btn btn-default" />
</div>
<a asp-action="Index">Back to List</a>
</form>
</div>
|
Remove errant comment on calc type | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Identifies the method to calculate the result
/// </summary>
public enum CalculationType : byte
{
// TODO: We might implement some other calculation methods as needed?
// Percent of Special Earnings: Select to calculate the deduction as a percent of a special accumulator, such as 401(k).
/// <summary>
/// Deduction is taken as a percentage of the gross pay
/// </summary>
[Display(Name = "Percent of Gross Pay")]
PercentOfGrossPay = 1,
/// <summary>
/// Deduction is taken as a percentage of the net pay
/// </summary>
[Display(Name = "Percent of Net Pay")]
PercentOfNetPay = 2,
/// <summary>
/// Deduction is taken as a flat, fixed amount
/// </summary>
[Display(Name = "Fixed Amount")]
FixedAmount = 3,
/// <summary>
/// Deduction is taken as a fixed amount per hour of work
/// </summary>
[Display(Name = "Fixed Hourly Amount")]
FixedHourlyAmount = 4
}
public static class CalculationTypes
{
public static IEnumerable<CalculationType> Values()
{
yield return CalculationType.PercentOfGrossPay;
yield return CalculationType.PercentOfNetPay;
yield return CalculationType.FixedAmount;
yield return CalculationType.FixedHourlyAmount;
}
}
} | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Identifies the method to calculate the result
/// </summary>
public enum CalculationType : byte
{
/// <summary>
/// Deduction is taken as a percentage of the gross pay
/// </summary>
[Display(Name = "Percent of Gross Pay")]
PercentOfGrossPay = 1,
/// <summary>
/// Deduction is taken as a percentage of the net pay
/// </summary>
[Display(Name = "Percent of Net Pay")]
PercentOfNetPay = 2,
/// <summary>
/// Deduction is taken as a flat, fixed amount
/// </summary>
[Display(Name = "Fixed Amount")]
FixedAmount = 3,
/// <summary>
/// Deduction is taken as a fixed amount per hour of work
/// </summary>
[Display(Name = "Fixed Hourly Amount")]
FixedHourlyAmount = 4
}
public static class CalculationTypes
{
public static IEnumerable<CalculationType> Values()
{
yield return CalculationType.PercentOfGrossPay;
yield return CalculationType.PercentOfNetPay;
yield return CalculationType.FixedAmount;
yield return CalculationType.FixedHourlyAmount;
}
}
} |
Format available channels for Limit attribute | using Discord.Commands;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Modix.Utilities
{
public class LimitToChannelsAttribute : PreconditionAttribute
{
public override Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IDependencyMap map)
{
var channelsConfig = Environment.GetEnvironmentVariable($"MODIX_LIMIT_MODULE_CHANNELS_{command.Module.Name.ToUpper()}");
if (channelsConfig == null)
{
return Task.Run(() => PreconditionResult.FromSuccess());
}
var channels = channelsConfig.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
return channels.Any(c => ulong.Parse(c) == context.Channel.Id)
? Task.Run(() => PreconditionResult.FromSuccess())
: Task.Run(() => PreconditionResult.FromError("This command cannot run in this channel"));
}
}
}
| using Discord.Commands;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Modix.Utilities
{
public class LimitToChannelsAttribute : PreconditionAttribute
{
public override Task<PreconditionResult> CheckPermissions(ICommandContext context, CommandInfo command, IDependencyMap map)
{
var channelsConfig = Environment.GetEnvironmentVariable($"MODIX_LIMIT_MODULE_CHANNELS_{command.Module.Name.ToUpper()}");
if (channelsConfig == null)
{
return Task.Run(() => PreconditionResult.FromSuccess());
}
var channels = channelsConfig.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
return channels.Any(c => ulong.Parse(c) == context.Channel.Id)
? Task.Run(() => PreconditionResult.FromSuccess())
: Task.Run(() => PreconditionResult.FromError($"This command cannot run in this channel. Valid channels are: {string.Join(", ", channels.Select(c => $"<#{c}>"))}"));
}
}
}
|
Fix typo that broke the build | 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("Csla.Validation.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Csla.Validation.Test")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("d68c5c90-c346.0.0e-9d6d-837b4419fda7")]
// 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")]
| 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("Csla.Validation.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Csla.Validation.Test")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("d68c5c90-c345-4c0e-9d6d-837b4419fda7")]
// 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")]
|
Hide connect password from logs. | namespace MQTTnet.Packets
{
public class MqttConnectPacket : MqttBasePacket
{
public string ProtocolName { get; set; }
public byte? ProtocolLevel { get; set; }
public string ClientId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public ushort KeepAlivePeriod { get; set; }
// Also called "Clean Start" in MQTTv5.
public bool CleanSession { get; set; }
public MqttApplicationMessage WillMessage { get; set; }
#region Added in MQTTv5.0.0
public MqttConnectPacketProperties Properties { get; set; }
#endregion
public override string ToString()
{
return string.Concat("Connect: [ProtocolLevel=", ProtocolLevel, "] [ClientId=", ClientId, "] [Username=", Username, "] [Password=", Password, "] [KeepAlivePeriod=", KeepAlivePeriod, "] [CleanSession=", CleanSession, "]");
}
}
}
| namespace MQTTnet.Packets
{
public class MqttConnectPacket : MqttBasePacket
{
public string ProtocolName { get; set; }
public byte? ProtocolLevel { get; set; }
public string ClientId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public ushort KeepAlivePeriod { get; set; }
// Also called "Clean Start" in MQTTv5.
public bool CleanSession { get; set; }
public MqttApplicationMessage WillMessage { get; set; }
#region Added in MQTTv5.0.0
public MqttConnectPacketProperties Properties { get; set; }
#endregion
public override string ToString()
{
var password = Password;
if (!string.IsNullOrEmpty(password))
{
password = "****";
}
return string.Concat("Connect: [ProtocolLevel=", ProtocolLevel, "] [ClientId=", ClientId, "] [Username=", Username, "] [Password=", password, "] [KeepAlivePeriod=", KeepAlivePeriod, "] [CleanSession=", CleanSession, "]");
}
}
}
|
Support for IP address URLs | using System;
using System.Collections.Generic;
using System.IO;
namespace MultiMiner.Win.Extensions
{
static class StringExtensions
{
private readonly static Dictionary<string, string> hostDomainNames = new Dictionary<string, string>();
public static string DomainFromHost(this string host)
{
if (String.IsNullOrEmpty(host))
return String.Empty;
if (hostDomainNames.ContainsKey(host))
return hostDomainNames[host];
string domainName;
if (!host.Contains(":"))
host = "http://" + host;
Uri uri = new Uri(host);
domainName = uri.Host;
//remove subdomain if there is one
if (domainName.Split('.').Length > 2)
{
int index = domainName.IndexOf(".") + 1;
domainName = domainName.Substring(index, domainName.Length - index);
}
//remove TLD
domainName = Path.GetFileNameWithoutExtension(domainName);
hostDomainNames[host] = domainName;
return domainName;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
namespace MultiMiner.Win.Extensions
{
static class StringExtensions
{
private readonly static Dictionary<string, string> hostDomainNames = new Dictionary<string, string>();
public static string DomainFromHost(this string host)
{
if (String.IsNullOrEmpty(host))
return String.Empty;
if (hostDomainNames.ContainsKey(host))
return hostDomainNames[host];
string domainName;
if (!host.Contains(":"))
host = "http://" + host;
Uri uri = new Uri(host);
domainName = uri.Host;
if (uri.HostNameType == UriHostNameType.Dns)
{
//remove subdomain if there is one
if (domainName.Split('.').Length > 2)
{
int index = domainName.IndexOf(".") + 1;
domainName = domainName.Substring(index, domainName.Length - index);
}
//remove TLD
domainName = Path.GetFileNameWithoutExtension(domainName);
}
hostDomainNames[host] = domainName;
return domainName;
}
}
}
|
Clean commented code and a tiny optimization to return false if the value is null. | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace ServiceStack.OrmLite
{
public static class Sql
{
//public static bool In<T>(T value, IList<Object> list)
//{
// foreach (Object obj in list)
// {
// if (obj == null || value == null) continue;
// if (obj.ToString() == value.ToString()) return true;
// }
// return false;
//}
public static bool In<T>(T value, params object[] list)
{
foreach (var obj in list)
{
if (obj == null || value == null) continue;
if (obj.ToString() == value.ToString()) return true;
}
return false;
}
public static string Desc<T>(T value) {
return value==null? "": value.ToString() + " DESC";
}
public static string As<T>( T value, object asValue) {
return value==null? "": string.Format("{0} AS {1}", value.ToString(), asValue);
}
public static T Sum<T>( T value) {
return value;
}
public static T Count<T>( T value) {
return value;
}
public static T Min<T>( T value) {
return value;
}
public static T Max<T>( T value) {
return value;
}
public static T Avg<T>( T value) {
return value;
}
}
}
| using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
namespace ServiceStack.OrmLite
{
public static class Sql
{
public static bool In<T>(T value, params object[] list)
{
if(value == null)
return false;
foreach (var obj in list)
{
if (obj == null) continue;
if (obj.ToString() == value.ToString()) return true;
}
return false;
}
public static string Desc<T>(T value) {
return value==null? "": value.ToString() + " DESC";
}
public static string As<T>( T value, object asValue) {
return value==null? "": string.Format("{0} AS {1}", value.ToString(), asValue);
}
public static T Sum<T>( T value) {
return value;
}
public static T Count<T>( T value) {
return value;
}
public static T Min<T>( T value) {
return value;
}
public static T Max<T>( T value) {
return value;
}
public static T Avg<T>( T value) {
return value;
}
}
}
|
Add heardbeat file to server | using Anotar.NLog;
using Ninject;
using Ninject.Extensions.Factory;
using SOVND.Lib;
using System;
using System.Text;
using SOVND.Lib.Handlers;
using SOVND.Lib.Models;
using SOVND.Server.Settings;
using System.Threading;
using System.Linq;
using SOVND.Server.Handlers;
namespace SOVND.Server
{
class Program
{
static void Main(string[] args)
{
try
{
IKernel kernel = new StandardKernel();
// Factories
kernel.Bind<IChannelHandlerFactory>().ToFactory();
kernel.Bind<IChatProviderFactory>().ToFactory();
// Singletons
kernel.Bind<RedisProvider>().ToSelf().InSingletonScope();
// Standard lifetime
kernel.Bind<IPlaylistProvider>().To<SortedPlaylistProvider>();
kernel.Bind<IMQTTSettings>().To<ServerMqttSettings>();
var server = kernel.Get<Server>();
server.Run();
if (args.Any(s => s.Equals("-d", StringComparison.CurrentCultureIgnoreCase)))
{
Thread.Sleep(Timeout.Infinite);
}
}
catch (Exception e)
{
LogTo.FatalException("Unhandled exception", e);
throw;
}
}
}
}
| using Anotar.NLog;
using Ninject;
using Ninject.Extensions.Factory;
using SOVND.Lib;
using System;
using System.Text;
using SOVND.Lib.Handlers;
using SOVND.Lib.Models;
using SOVND.Server.Settings;
using System.Threading;
using System.Linq;
using SOVND.Server.Handlers;
using System.IO;
using SOVND.Lib.Utils;
namespace SOVND.Server
{
class Program
{
static void Main(string[] args)
{
try
{
LogTo.Debug("===========================================================");
IKernel kernel = new StandardKernel();
// Factories
kernel.Bind<IChannelHandlerFactory>().ToFactory();
kernel.Bind<IChatProviderFactory>().ToFactory();
// Singletons
kernel.Bind<RedisProvider>().ToSelf().InSingletonScope();
// Standard lifetime
kernel.Bind<IPlaylistProvider>().To<SortedPlaylistProvider>();
kernel.Bind<IMQTTSettings>().To<ServerMqttSettings>();
var server = kernel.Get<Server>();
server.Run();
var heartbeat = TimeSpan.FromMinutes(3);
while (true)
{
File.WriteAllText("sovndserver.heartbeat", Time.Timestamp().ToString());
Thread.Sleep(heartbeat);
}
}
catch (Exception e)
{
LogTo.FatalException("Unhandled exception", e);
throw;
}
}
}
}
|
Use better formatting for skin display (matching BeatmapMetadata) | // 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 osu.Game.Configuration;
using osu.Game.Database;
namespace osu.Game.Skinning
{
public class SkinInfo : IHasFiles<SkinFileInfo>, IEquatable<SkinInfo>, IHasPrimaryKey, ISoftDelete
{
public int ID { get; set; }
public string Name { get; set; }
public string Hash { get; set; }
public string Creator { get; set; }
public List<SkinFileInfo> Files { get; set; }
public List<DatabasedSetting> Settings { get; set; }
public bool DeletePending { get; set; }
public string FullName => $"\"{Name}\" by {Creator}";
public static SkinInfo Default { get; } = new SkinInfo
{
Name = "osu!lazer",
Creator = "team osu!"
};
public bool Equals(SkinInfo other) => other != null && ID == other.ID;
public override string ToString() => FullName;
}
}
| // 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 osu.Game.Configuration;
using osu.Game.Database;
namespace osu.Game.Skinning
{
public class SkinInfo : IHasFiles<SkinFileInfo>, IEquatable<SkinInfo>, IHasPrimaryKey, ISoftDelete
{
public int ID { get; set; }
public string Name { get; set; }
public string Hash { get; set; }
public string Creator { get; set; }
public List<SkinFileInfo> Files { get; set; }
public List<DatabasedSetting> Settings { get; set; }
public bool DeletePending { get; set; }
public static SkinInfo Default { get; } = new SkinInfo
{
Name = "osu!lazer",
Creator = "team osu!"
};
public bool Equals(SkinInfo other) => other != null && ID == other.ID;
public override string ToString()
{
string author = Creator == null ? string.Empty : $"({Creator})";
return $"{Name} {author}".Trim();
}
}
}
|
Use autofixture for unit tests of the command bus. | using System;
using Microsoft.Practices.ServiceLocation;
using Moq;
using NUnit.Framework;
using Uncas.BuildPipeline.Commands;
using Uncas.BuildPipeline.Repositories;
using Uncas.BuildPipeline.Utilities;
namespace Uncas.BuildPipeline.Tests.Unit
{
[TestFixture]
public class CommandBusTests
{
[Test]
public void Publish_HandlerNotRegisterd_ThrowsInvalidOperationException()
{
var mock = new Mock<IServiceLocator>();
var bus = new CommandBus(mock.Object);
Assert.Throws<InvalidOperationException>(() => bus.Publish(new UpdateGitMirrors()));
}
[Test]
public void Publish_HandlerRegistered_GetsResolvedOnce()
{
var mock = new Mock<IServiceLocator>();
mock.Setup(x => x.GetInstance(typeof (UpdateGitMirrorsHandler))).Returns(
new UpdateGitMirrorsHandler(new GitUtility(), new ProjectReadStore()));
var bus = new CommandBus(mock.Object);
bus.Publish(new UpdateGitMirrors());
mock.Verify(x => x.GetInstance(typeof (UpdateGitMirrorsHandler)), Times.Once());
}
}
} | using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture;
using Uncas.BuildPipeline.Commands;
namespace Uncas.BuildPipeline.Tests.Unit
{
[TestFixture]
public class CommandBusTests : WithFixture<CommandBus>
{
[Test]
public void Publish_HandlerNotRegisterd_ThrowsInvalidOperationException()
{
Fixture.Register<IServiceLocator>(() => new UnityServiceLocator(new UnityContainer()));
Assert.Throws<ActivationException>(() => Sut.Publish(Fixture.Create<UpdateGitMirrors>()));
}
[Test]
public void Publish_HandlerRegistered_GetsResolvedOnce()
{
var mock = new Mock<IServiceLocator>();
mock.Setup(x => x.GetInstance(typeof (UpdateGitMirrorsHandler))).Returns(
Fixture.Create<UpdateGitMirrorsHandler>());
Fixture.Register(() => mock.Object);
Sut.Publish(Fixture.Create<UpdateGitMirrors>());
mock.Verify(x => x.GetInstance(typeof (UpdateGitMirrorsHandler)), Times.Once());
}
}
} |
Add read only props to access RVA and size | using System;
using System.IO;
namespace dot10.PE {
/// <summary>
/// Represents the IMAGE_DATA_DIRECTORY PE section
/// </summary>
public class ImageDataDirectory : FileSection {
RVA virtualAddress;
uint dataSize;
/// <summary>
/// Default constructor
/// </summary>
public ImageDataDirectory() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">PE file reader pointing to the start of this section</param>
/// <param name="verify">Verify section</param>
/// <exception cref="BadImageFormatException">Thrown if verification fails</exception>
public ImageDataDirectory(BinaryReader reader, bool verify) {
SetStartOffset(reader);
this.virtualAddress = new RVA(reader.ReadUInt32());
this.dataSize = reader.ReadUInt32();
SetEndoffset(reader);
}
}
}
| using System;
using System.IO;
namespace dot10.PE {
/// <summary>
/// Represents the IMAGE_DATA_DIRECTORY PE section
/// </summary>
public class ImageDataDirectory : FileSection {
RVA virtualAddress;
uint dataSize;
/// <summary>
/// Returns the IMAGE_DATA_DIRECTORY.VirtualAddress field
/// </summary>
public RVA VirtualAddress {
get { return virtualAddress; }
}
/// <summary>
/// Returns the IMAGE_DATA_DIRECTORY.Size field
/// </summary>
public uint Size {
get { return dataSize; }
}
/// <summary>
/// Default constructor
/// </summary>
public ImageDataDirectory() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">PE file reader pointing to the start of this section</param>
/// <param name="verify">Verify section</param>
/// <exception cref="BadImageFormatException">Thrown if verification fails</exception>
public ImageDataDirectory(BinaryReader reader, bool verify) {
SetStartOffset(reader);
this.virtualAddress = new RVA(reader.ReadUInt32());
this.dataSize = reader.ReadUInt32();
SetEndoffset(reader);
}
}
}
|
Improve the way Booleans are shown if they are not within the maximum allowable limit | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NeuralNet.Configuration;
namespace NeuralNetTypes
{
class NeuralNetBooleanFormatter : NetInputOutputFormatter
{
private const double high = 0.9, low = 0.1, maxError = 0.1;
public sealed override string InputToString(double input)
{
return HighOrLow(input);
}
public override bool TryParse(string s, out double result)
{
if (s.Trim().ToUpper() == "H")
{
result = high;
return true;
}
if (s.Trim().ToUpper() == "L")
{
result = low;
return true;
}
return base.TryParse(s, out result);
}
public sealed override string OutputToString(double output)
{
return $"{base.OutputToString(output)} [{HighOrLow(output)}]";
}
private string HighOrLow(double number)
{
if (Math.Abs(number - high) <= maxError)
return "H";
if (Math.Abs(number - low) <= maxError)
return "L";
return "?";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NeuralNet.Configuration;
namespace NeuralNetTypes
{
class NeuralNetBooleanFormatter : NetInputOutputFormatter
{
private const double high = 0.9, low = 0.1, maxError = 0.1;
public sealed override string InputToString(double input)
{
return HighOrLow(input);
}
public override bool TryParse(string s, out double result)
{
if (s.Trim().ToUpper() == "H")
{
result = high;
return true;
}
if (s.Trim().ToUpper() == "L")
{
result = low;
return true;
}
return base.TryParse(s, out result);
}
public sealed override string OutputToString(double output)
{
return $"{base.OutputToString(output)} [{HighOrLow(output)}]";
}
private string HighOrLow(double number)
{
// Check if the number is within the maximum error
// If it is, return a capital H or L
if (Math.Abs(number - high) <= maxError)
return "H";
if (Math.Abs(number - low) <= maxError)
return "L";
// Otherwise, return a lower case letter
return (number >= 0.5 ? "h" : "l");
}
}
}
|
Fix null ref error if bfgminer returns no Status w / the devs API | namespace MultiMiner.Xgminer.Api
{
public class DeviceInformation
{
public string Kind { get; set; }
public int Index { get; set; }
public bool Enabled { get; set; }
public string Status { get; set; }
public double Temperature { get; set; }
public int FanSpeed { get; set; }
public int FanPercent { get; set; }
public int GpuClock { get; set; }
public int MemoryClock { get; set; }
public double GpuVoltage { get; set; }
public int GpuActivity { get; set; }
public int PowerTune { get; set; }
public double AverageHashrate { get; set; }
public double CurrentHashrate { get; set; }
public int AcceptedShares { get; set; }
public int RejectedShares { get; set; }
public int HardwareErrors { get; set; }
public double Utility { get; set; }
public string Intensity { get; set; } //string, might be D
public int PoolIndex { get; set; }
}
}
| using System;
namespace MultiMiner.Xgminer.Api
{
public class DeviceInformation
{
public DeviceInformation()
{
Status = String.Empty;
}
public string Kind { get; set; }
public int Index { get; set; }
public bool Enabled { get; set; }
public string Status { get; set; }
public double Temperature { get; set; }
public int FanSpeed { get; set; }
public int FanPercent { get; set; }
public int GpuClock { get; set; }
public int MemoryClock { get; set; }
public double GpuVoltage { get; set; }
public int GpuActivity { get; set; }
public int PowerTune { get; set; }
public double AverageHashrate { get; set; }
public double CurrentHashrate { get; set; }
public int AcceptedShares { get; set; }
public int RejectedShares { get; set; }
public int HardwareErrors { get; set; }
public double Utility { get; set; }
public string Intensity { get; set; } //string, might be D
public int PoolIndex { get; set; }
}
}
|
Remove overload by using default value | using System.Collections.Generic;
namespace DiffPlex.DiffBuilder.Model
{
public enum ChangeType
{
Unchanged,
Deleted,
Inserted,
Imaginary,
Modified
}
public class DiffPiece
{
public ChangeType Type { get; set; }
public int? Position { get; set; }
public string Text { get; set; }
public List<DiffPiece> SubPieces { get; set; }
public DiffPiece(string text, ChangeType type, int? position)
{
Text = text;
Position = position;
Type = type;
SubPieces = new List<DiffPiece>();
}
public DiffPiece(string text, ChangeType type)
: this(text, type, null)
{
}
public DiffPiece()
: this(null, ChangeType.Imaginary)
{
}
}
} | using System.Collections.Generic;
namespace DiffPlex.DiffBuilder.Model
{
public enum ChangeType
{
Unchanged,
Deleted,
Inserted,
Imaginary,
Modified
}
public class DiffPiece
{
public ChangeType Type { get; set; }
public int? Position { get; set; }
public string Text { get; set; }
public List<DiffPiece> SubPieces { get; set; }
public DiffPiece(string text, ChangeType type, int? position = null)
{
Text = text;
Position = position;
Type = type;
SubPieces = new List<DiffPiece>();
}
public DiffPiece()
: this(null, ChangeType.Imaginary)
{
}
}
} |
Add more detail in documentation comment. | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rock
{
/// <summary>
/// An implementation of <see cref="IApplicationInfo"/> that uses a config
/// file's appSettings section.
/// </summary>
public class AppSettingsApplicationInfo : IApplicationInfo
{
private const string DefaultApplicationIdKey = "Rock.ApplicationId.Current";
private readonly string _applicationIdKey;
/// <summary>
/// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class.
/// </summary>
public AppSettingsApplicationInfo()
: this(DefaultApplicationIdKey)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class.
/// </summary>
/// <param name="applicationIdKey">The key of the application ID setting.</param>
public AppSettingsApplicationInfo(string applicationIdKey)
{
_applicationIdKey = applicationIdKey;
}
/// <summary>
/// Gets the ID of the current application.
/// </summary>
public string ApplicationId
{
get { return ConfigurationManager.AppSettings[_applicationIdKey]; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rock
{
/// <summary>
/// An implementation of <see cref="IApplicationInfo"/> that uses a config
/// file's appSettings section.
/// </summary>
public class AppSettingsApplicationInfo : IApplicationInfo
{
private const string DefaultApplicationIdKey = "Rock.ApplicationId.Current";
private readonly string _applicationIdKey;
/// <summary>
/// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class.
/// The key of the application ID setting will be "Rock.ApplicationId.Current".
/// </summary>
public AppSettingsApplicationInfo()
: this(DefaultApplicationIdKey)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class.
/// </summary>
/// <param name="applicationIdKey">The key of the application ID setting.</param>
public AppSettingsApplicationInfo(string applicationIdKey)
{
_applicationIdKey = applicationIdKey;
}
/// <summary>
/// Gets the ID of the current application.
/// </summary>
public string ApplicationId
{
get { return ConfigurationManager.AppSettings[_applicationIdKey]; }
}
}
}
|
Check if we're in debug and set IncludeErrorPolicy accordingly | using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Umbraco.Web.WebApi
{
/// <summary>
/// Ensures controllers have detailed error messages even when debug mode is off
/// </summary>
public class EnableDetailedErrorsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.ControllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
}
| using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace Umbraco.Web.WebApi
{
/// <summary>
/// Ensures controllers have detailed error messages even when debug mode is off
/// </summary>
public class EnableDetailedErrorsAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.ControllerContext.Configuration.IncludeErrorDetailPolicy = HttpContext.Current.IsDebuggingEnabled ? IncludeErrorDetailPolicy.Always : IncludeErrorDetailPolicy.Default;
}
}
}
|
Change the HttpUtility.UrlEncode to Uri.EscapeDataString method. | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace Exceptionless.Core.Extensions {
public static class UriExtensions {
public static string ToQueryString(this NameValueCollection collection) {
return collection.AsKeyValuePairs().ToQueryString();
}
public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) {
return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={System.Web.HttpUtility.UrlEncode(pair.Value)}", "&");
}
/// <summary>
/// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) {
return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key)));
}
public static string GetBaseUrl(this Uri uri) {
return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace Exceptionless.Core.Extensions {
public static class UriExtensions {
public static string ToQueryString(this NameValueCollection collection) {
return collection.AsKeyValuePairs().ToQueryString();
}
public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) {
return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={Uri.EscapeDataString(pair.Value)}", "&");
}
/// <summary>
/// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence.
/// </summary>
private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) {
return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key)));
}
public static string GetBaseUrl(this Uri uri) {
return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath;
}
}
} |
Fix issue with API header binding when running under a subdirectory | using System;
using System.Web.Mvc;
namespace NuGetGallery
{
public class HttpHeaderValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
var request = controllerContext.RequestContext.HttpContext.Request;
// Use this value provider only if a route is located under "API"
if (request.Path.TrimStart('/').StartsWith("api", StringComparison.OrdinalIgnoreCase))
return new HttpHeaderValueProvider(request, "ApiKey");
return null;
}
}
} | using System;
using System.Web.Mvc;
namespace NuGetGallery
{
public class HttpHeaderValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
var request = controllerContext.RequestContext.HttpContext.Request;
// Use this value provider only if a route is located under "API"
if (request.Path.Contains("/api/"))
return new HttpHeaderValueProvider(request, "ApiKey");
return null;
}
}
} |
Make necrophage require Look faculty | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NecrophageBehavior : AgentBehavior
{
// "pursue" nearest corpse
public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits)
{
Action newMoveAction;
Action newLookAction;
Agent tempAgent;
bool found = findNearestAgent(percepts, AgentPercept.LivingState.DEAD, out tempAgent);
if(found && !myself.getMoveInUse())
{
newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS);
newMoveAction.setTargetPoint(tempAgent.getLocation());
newLookAction = new Action(Action.ActionType.TURN_TOWARDS);
newLookAction.setTargetPoint(tempAgent.getLocation());
currentPlans.Clear();
this.currentPlans.Add(newMoveAction);
this.currentPlans.Add(newLookAction);
return true;
}
return false;
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NecrophageBehavior : AgentBehavior
{
// "pursue" nearest corpse
public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits)
{
Action newMoveAction;
Action newLookAction;
Agent tempAgent;
bool found = findNearestAgent(percepts, AgentPercept.LivingState.DEAD, out tempAgent);
if(found && !myself.getMoveInUse() && !myself.getLookInUse())
{
newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS);
newMoveAction.setTargetPoint(tempAgent.getLocation());
newLookAction = new Action(Action.ActionType.TURN_TOWARDS);
newLookAction.setTargetPoint(tempAgent.getLocation());
currentPlans.Clear();
this.currentPlans.Add(newMoveAction);
this.currentPlans.Add(newLookAction);
return true;
}
return false;
}
}
|
Add check for microgames when forced in Practice | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicrogameStage : Stage
{
public static string microgameId;
[SerializeField]
private string forceMicrogame;
public override Microgame getMicrogame(int num)
{
Microgame microgame = new Microgame(microgameId);
microgame.microgameId = !string.IsNullOrEmpty(forceMicrogame) ? forceMicrogame : microgameId;
return microgame;
}
public override int getMicrogameDifficulty(Microgame microgame, int num)
{
return (num % 3) + 1;
}
public override Interruption[] getInterruptions(int num)
{
if (num == 0 || num % 3 > 0)
return new Interruption[0];
return new Interruption[0].add(new Interruption(Interruption.SpeedChange.SpeedUp));
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MicrogameStage : Stage
{
public static string microgameId;
[SerializeField]
private string forceMicrogame;
public override void onStageStart()
{
//Update collection if microgame is forced, in case it's in the project but hasn't been added to the collection
if (!string.IsNullOrEmpty(forceMicrogame))
GameController.instance.microgameCollection.updateMicrogames();
}
public override Microgame getMicrogame(int num)
{
Microgame microgame = new Microgame(microgameId);
microgame.microgameId = !string.IsNullOrEmpty(forceMicrogame) ? forceMicrogame : microgameId;
return microgame;
}
public override int getMicrogameDifficulty(Microgame microgame, int num)
{
return (num % 3) + 1;
}
public override Interruption[] getInterruptions(int num)
{
if (num == 0 || num % 3 > 0)
return new Interruption[0];
return new Interruption[0].add(new Interruption(Interruption.SpeedChange.SpeedUp));
}
}
|
Refactor the Venue level cost centre to inherit from the Account level cost centre to allow sharing of data structures. | using Newtonsoft.Json;
namespace Ivvy.API.Venue
{
public class CostCenter
{
public enum DefaultTypes
{
Other = 1,
VenueFood = 2,
VenueBeverage = 3,
VenueAudioVisual = 4,
VenueRoomHire = 5,
VenueAccommodation = 6,
}
[JsonProperty("id")]
public int? Id
{
get; set;
}
[JsonProperty("name")]
public string Name
{
get; set;
}
[JsonProperty("code")]
public string Code
{
get; set;
}
[JsonProperty("description")]
public string Description
{
get; set;
}
[JsonProperty("defaultType")]
public DefaultTypes? DefaultType
{
get; set;
}
[JsonProperty("parentId")]
public int? ParentId
{
get; set;
}
}
} | using Newtonsoft.Json;
namespace Ivvy.API.Venue
{
public class CostCenter : Account.CostCenter
{
[JsonProperty("parentId")]
public int? ParentId
{
get; set;
}
}
} |
Add Maximum/Average aggregate functions for amplitudes | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
namespace osu.Framework.Audio.Track
{
public struct TrackAmplitudes
{
public float LeftChannel;
public float RightChannel;
}
} | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
namespace osu.Framework.Audio.Track
{
public struct TrackAmplitudes
{
public float LeftChannel;
public float RightChannel;
public float Maximum => Math.Max(LeftChannel, RightChannel);
public float Average => (LeftChannel + RightChannel) / 2;
}
} |
Add source documentation for configuration class. | namespace TraktApiSharp.Core
{
using System.Net.Http;
public class TraktConfiguration
{
internal TraktConfiguration()
{
ApiVersion = 2;
UseStagingUrl = false;
}
internal static HttpClient HTTP_CLIENT = null;
public int ApiVersion { get; set; }
public bool UseStagingUrl { get; set; }
public string BaseUrl => UseStagingUrl ? "https://api-staging.trakt.tv/" : $"https://api-v{ApiVersion}launch.trakt.tv/";
}
}
| namespace TraktApiSharp.Core
{
using System.Net.Http;
/// <summary>Provides global client settings.</summary>
public class TraktConfiguration
{
internal TraktConfiguration()
{
ApiVersion = 2;
UseStagingUrl = false;
}
internal static HttpClient HTTP_CLIENT = null;
/// <summary>
/// Gets or sets the Trakt API version.
/// <para>
/// See <a href="http://docs.trakt.apiary.io/#introduction/api-url">"Trakt API Doc - API URL"</a> for more information.
/// </para>
/// </summary>
public int ApiVersion { get; set; }
/// <summary>
/// Gets or sets, whether the Trakt API staging environment should be used. By default disabled.
/// <para>
/// See <a href="http://docs.trakt.apiary.io/#introduction/api-url">"Trakt API Doc - API URL"</a> for more information.
/// </para>
/// </summary>
public bool UseStagingUrl { get; set; }
/// <summary>Returns the Trakt API base URL based on, whether <see cref="UseStagingUrl" /> is false or true.</summary>
public string BaseUrl => UseStagingUrl ? "https://api-staging.trakt.tv/" : $"https://api-v{ApiVersion}launch.trakt.tv/";
}
}
|
Add info to addin description about uninstalling old addin | using Mono.Addins;
[assembly:Addin ("Dnx",
Namespace = "MonoDevelop",
Version = "0.5",
Category = "IDE extensions")]
[assembly:AddinName ("DNX")]
[assembly:AddinDescription ("Adds .NET Core and ASP.NET Core support.")]
[assembly:AddinDependency ("Core", "6.0")]
[assembly:AddinDependency ("Ide", "6.0")]
[assembly:AddinDependency ("DesignerSupport", "6.0")]
[assembly:AddinDependency ("Debugger", "6.0")]
[assembly:AddinDependency ("Debugger.Soft", "6.0")]
[assembly:AddinDependency ("SourceEditor2", "6.0")]
[assembly:AddinDependency ("UnitTesting", "6.0")]
| using Mono.Addins;
[assembly:Addin ("Dnx",
Namespace = "MonoDevelop",
Version = "0.5",
Category = "IDE extensions")]
[assembly:AddinName ("DNX")]
[assembly:AddinDescription ("Adds .NET Core and ASP.NET Core support.\n\nPlease uninstall any older version of the addin and restart the application before installing this new version.")]
[assembly:AddinDependency ("Core", "6.0")]
[assembly:AddinDependency ("Ide", "6.0")]
[assembly:AddinDependency ("DesignerSupport", "6.0")]
[assembly:AddinDependency ("Debugger", "6.0")]
[assembly:AddinDependency ("Debugger.Soft", "6.0")]
[assembly:AddinDependency ("SourceEditor2", "6.0")]
[assembly:AddinDependency ("UnitTesting", "6.0")]
|
Add more shell unit test | using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LiteDB.Tests.Engine
{
[TestClass]
public class Shell_Tests
{
[TestMethod]
public void Shell_Commands()
{
using (var db = new LiteEngine(new MemoryStream()))
{
db.Run("db.col1.insert {a: 1}");
db.Run("db.col1.insert {a: 2}");
db.Run("db.col1.insert {a: 3}");
db.Run("db.col1.ensureIndex a");
Assert.AreEqual(1, db.Run("db.col1.find a = 1").First().AsDocument["a"].AsInt32);
db.Run("db.col1.update a = $.a + 10, b = 2 where a = 1");
Assert.AreEqual(11, db.Run("db.col1.find a = 11").First().AsDocument["a"].AsInt32);
Assert.AreEqual(3, db.Count("col1"));
}
}
}
} | using System.IO;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LiteDB.Tests.Engine
{
[TestClass]
public class Shell_Tests
{
[TestMethod]
public void Shell_Commands()
{
using (var db = new LiteEngine(new MemoryStream()))
{
db.Run("db.col1.insert {a: 1}");
db.Run("db.col1.insert {a: 2}");
db.Run("db.col1.insert {a: 3}");
db.Run("db.col1.ensureIndex a");
Assert.AreEqual(1, db.Run("db.col1.find a = 1").First().AsDocument["a"].AsInt32);
db.Run("db.col1.update a = $.a + 10, b = 2 where a = 1");
Assert.AreEqual(11, db.Run("db.col1.find a = 11").First().AsDocument["a"].AsInt32);
Assert.AreEqual(3, db.Count("col1"));
// insert new data
db.Run("db.data.insert {Text: \"Anything\", Number: 10} id:int");
db.Run("db.data.ensureIndex Text");
var doc = db.Run("db.data.find Text like \"A\"").First() as BsonDocument;
Assert.AreEqual(1, doc["_id"].AsInt32);
Assert.AreEqual("Anything", doc["Text"].AsString);
Assert.AreEqual(10, doc["Number"].AsInt32);
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.