commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
c0062d84fc51ba07392e9146e2dabc115e0aa8e1 | Add "There are no commands". | jden123/JustCli | src/core/JustCli/Commands/CommandLineHelpCommand.cs | src/core/JustCli/Commands/CommandLineHelpCommand.cs | namespace JustCli.Commands
{
public class CommandLineHelpCommand : ICommand
{
public ICommandRepository CommandRepository { get; set; }
public IOutput Output { get; set; }
public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
{
CommandRepository = commandRepository;
Output = output;
}
public bool Execute()
{
var commandsInfo = CommandRepository.GetCommandsInfo();
if (commandsInfo.Count == 0)
{
Output.WriteInfo("There are no commands.");
return true;
}
Output.WriteInfo("Command list:");
foreach (var commandInfo in commandsInfo)
{
Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
}
return true;
}
}
} | namespace JustCli.Commands
{
public class CommandLineHelpCommand : ICommand
{
public ICommandRepository CommandRepository { get; set; }
public IOutput Output { get; set; }
public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
{
CommandRepository = commandRepository;
Output = output;
}
public bool Execute()
{
var commandsInfo = CommandRepository.GetCommandsInfo();
Output.WriteInfo("Command list:");
foreach (var commandInfo in commandsInfo)
{
Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
}
return true;
}
}
} | mit | C# |
8333148d86c645c60d818edc6a441bd00b3c7194 | Update MultibaseCorrelationServiceOptions.cs | tiksn/TIKSN-Framework | TIKSN.Core/Integration/Correlation/MultibaseCorrelationServiceOptions.cs | TIKSN.Core/Integration/Correlation/MultibaseCorrelationServiceOptions.cs | using Multiformats.Base;
namespace TIKSN.Integration.Correlation
{
public class MultibaseCorrelationServiceOptions
{
public MultibaseCorrelationServiceOptions()
{
this.ByteLength = 16;
this.Encoding = MultibaseEncoding.Base64;
}
public int ByteLength { get; set; }
public MultibaseEncoding Encoding { get; internal set; }
}
}
| using Multiformats.Base;
namespace TIKSN.Integration.Correlation
{
public class MultibaseCorrelationServiceOptions
{
public MultibaseCorrelationServiceOptions()
{
ByteLength = 16;
Encoding = MultibaseEncoding.Base64;
}
public int ByteLength { get; set; }
public MultibaseEncoding Encoding { get; internal set; }
}
} | mit | C# |
d0c4c362138bd4bb60cdc0d317236bcf2d54ded5 | Update Program.DependencyInjection.cs | fluentmigrator/fluentmigrator,stsrki/fluentmigrator,stsrki/fluentmigrator,fluentmigrator/fluentmigrator | samples/FluentMigrator.Example.Migrator/Program.DependencyInjection.cs | samples/FluentMigrator.Example.Migrator/Program.DependencyInjection.cs | #region License
// Copyright (c) 2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using FluentMigrator.Example.Migrations;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Processors;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FluentMigrator.Example.Migrator
{
internal static partial class Program
{
private static void RunWithServices(DatabaseConfiguration dbConfig)
{
// Initialize the services
var serviceProvider = new ServiceCollection()
.AddLogging(lb => lb.AddDebug().AddFluentMigratorConsole())
.AddFluentMigratorCore()
.ConfigureRunner(
builder => builder
#if NETFRAMEWORK
.AddJet()
#endif
.AddSQLite()
.WithGlobalConnectionString(dbConfig.ConnectionString)
// NOTE: For now, recommend using For.All() instead of .For.Migrations() if using Maintenance Migrations
// https://github.com/fluentmigrator/fluentmigrator/issues/1062#issuecomment-616598419
.ScanIn(typeof(AddGTDTables).Assembly).For.All())
.Configure<SelectingProcessorAccessorOptions>(
opt => opt.ProcessorId = dbConfig.ProcessorId)
.BuildServiceProvider();
// Instantiate the runner
var runner = serviceProvider.GetRequiredService<IMigrationRunner>();
// Run the migrations
runner.MigrateUp();
}
}
}
| #region License
// Copyright (c) 2018, FluentMigrator Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using FluentMigrator.Example.Migrations;
using FluentMigrator.Runner;
using FluentMigrator.Runner.Processors;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace FluentMigrator.Example.Migrator
{
internal static partial class Program
{
private static void RunWithServices(DatabaseConfiguration dbConfig)
{
// Initialize the services
var serviceProvider = new ServiceCollection()
.AddLogging(lb => lb.AddDebug().AddFluentMigratorConsole())
.AddFluentMigratorCore()
.ConfigureRunner(
builder => builder
#if NETFRAMEWORK
.AddJet()
#endif
.AddSQLite()
.WithGlobalConnectionString(dbConfig.ConnectionString)
.ScanIn(typeof(AddGTDTables).Assembly).For.Migrations())
.Configure<SelectingProcessorAccessorOptions>(
opt => opt.ProcessorId = dbConfig.ProcessorId)
.BuildServiceProvider();
// Instantiate the runner
var runner = serviceProvider.GetRequiredService<IMigrationRunner>();
// Run the migrations
runner.MigrateUp();
}
}
}
| apache-2.0 | C# |
4c4cff8bc70b01e17688f922da97b3409698fea7 | Add missing context. | danielwertheim/mycouch,danielwertheim/mycouch | source/tests/MyCouch.IntegrationTests.Net45/CoreTests/DatabaseTests.cs | source/tests/MyCouch.IntegrationTests.Net45/CoreTests/DatabaseTests.cs | using System.Net.Http;
using MyCouch.Testing;
using MyCouch.Testing.TestData;
namespace MyCouch.IntegrationTests.CoreTests
{
public class DatabaseTests : IntegrationTestsOf<IDatabase>
{
public DatabaseTests()
{
SUT = DbClient.Database;
SUT.PutAsync().Wait();
}
[MyFact(TestScenarios.DatabaseContext)]
public void When_Head_of_existing_db_The_response_should_be_200()
{
var response = SUT.HeadAsync().Result;
response.Should().Be(HttpMethod.Head);
}
[MyFact(TestScenarios.DatabaseContext)]
public void When_Get_of_existing_db_with_insert_update_and_delete_ops_The_response_should_be_200()
{
var a1 = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;
var a1Updated = DbClient.Documents.PutAsync(a1.Id, a1.Rev, ClientTestData.Artists.Artist1Json).Result;
var a2 = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist2Json).Result;
var a2Deleted = DbClient.Documents.DeleteAsync(a2.Id, a2.Rev).Result;
var response = SUT.GetAsync().Result;
if (Environment.IsAgainstCloudant())
response.Should().BeSuccessfulCloudant(DbClient.Connection.DbName);
else
response.Should().BeSuccessful(DbClient.Connection.DbName);
}
[MyFact(TestScenarios.DatabaseContext, TestScenarios.CompactDbs)]
public void When_Compact_of_existing_db_The_response_should_be_202()
{
var response = SUT.CompactAsync().Result;
response.Should().BeAcceptedPost(DbClient.Connection.DbName);
}
[MyFact(TestScenarios.DatabaseContext, TestScenarios.ViewCleanUp)]
public void When_ViewCleanup_and_db_exists_The_response_be()
{
var response = SUT.ViewCleanupAsync().Result;
response.Should().BeAcceptedPost(DbClient.Connection.DbName);
}
}
} | using System.Net.Http;
using MyCouch.Testing;
using MyCouch.Testing.TestData;
namespace MyCouch.IntegrationTests.CoreTests
{
public class DatabaseTests : IntegrationTestsOf<IDatabase>
{
public DatabaseTests()
{
SUT = DbClient.Database;
SUT.PutAsync().Wait();
}
[MyFact(TestScenarios.DatabaseContext)]
public void When_Head_of_existing_db_The_response_should_be_200()
{
var response = SUT.HeadAsync().Result;
response.Should().Be(HttpMethod.Head);
}
[MyFact(TestScenarios.DatabaseContext)]
public void When_Get_of_existing_db_with_insert_update_and_delete_ops_The_response_should_be_200()
{
var a1 = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist1Json).Result;
var a1Updated = DbClient.Documents.PutAsync(a1.Id, a1.Rev, ClientTestData.Artists.Artist1Json).Result;
var a2 = DbClient.Documents.PostAsync(ClientTestData.Artists.Artist2Json).Result;
var a2Deleted = DbClient.Documents.DeleteAsync(a2.Id, a2.Rev).Result;
var response = SUT.GetAsync().Result;
if (Environment.IsAgainstCloudant())
response.Should().BeSuccessfulCloudant(DbClient.Connection.DbName);
else
response.Should().BeSuccessful(DbClient.Connection.DbName);
}
[MyFact(TestScenarios.DatabaseContext, TestScenarios.CompactDbs)]
public void When_Compact_of_existing_db_The_response_should_be_202()
{
var response = SUT.CompactAsync().Result;
response.Should().BeAcceptedPost(DbClient.Connection.DbName);
}
[MyFact(TestScenarios.DatabaseContext)]
public void When_ViewCleanup_and_db_exists_The_response_be()
{
var response = SUT.ViewCleanupAsync().Result;
response.Should().BeAcceptedPost(DbClient.Connection.DbName);
}
}
} | mit | C# |
a5f9202d5a95d9f1a1766948a68682dd8897b459 | Fix - Included some missing cases for JSON string types. | jdevillard/JmesPath.Net | src/jmespath.net/Utils/JTokens.cs | src/jmespath.net/Utils/JTokens.cs | using System;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Utils
{
public static class JTokens
{
public static JToken Null = JToken.Parse("null");
public static JToken True = JToken.Parse("true");
public static JToken False = JToken.Parse("false");
public static bool IsFalse(JToken token)
{
// A false value corresponds to any of the following conditions:
// Empty list: ``[]``
// Empty object: ``{}``
// Empty string: ``""``
// False boolean: ``false``
// Null value: ``null``
var array = token as JArray;
if (array != null && array.Count == 0)
return true;
var @object = token as JObject;
if (@object != null && @object.Count == 0)
return true;
var value = token as JValue;
if (value != null)
{
switch (token.Type)
{
case JTokenType.Bytes:
case JTokenType.Date:
case JTokenType.Guid:
case JTokenType.String:
case JTokenType.TimeSpan:
case JTokenType.Uri:
return token.Value<String>() == "";
case JTokenType.Boolean:
return token.Value<Boolean>() == false;
case JTokenType.Null:
return true;
}
}
return false;
}
}
} | using System;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Utils
{
public static class JTokens
{
public static JToken Null = JToken.Parse("null");
public static JToken True = JToken.Parse("true");
public static JToken False = JToken.Parse("false");
public static bool IsFalse(JToken token)
{
// A false value corresponds to any of the following conditions:
// Empty list: ``[]``
// Empty object: ``{}``
// Empty string: ``""``
// False boolean: ``false``
// Null value: ``null``
var array = token as JArray;
if (array != null && array.Count == 0)
return true;
var @object = token as JObject;
if (@object != null && @object.Count == 0)
return true;
var value = token as JValue;
if (value != null)
{
switch (token.Type)
{
case JTokenType.Bytes:
case JTokenType.Date:
case JTokenType.Guid:
case JTokenType.String:
return token.Value<String>() == "";
case JTokenType.Boolean:
return token.Value<Boolean>() == false;
case JTokenType.Null:
return true;
}
}
return false;
}
}
} | apache-2.0 | C# |
4f40d740e8015c1f656c0755fcb00ae5c05e1ab1 | Fix console log exporter extension method summary (#2912) | open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet,open-telemetry/opentelemetry-dotnet | src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs | src/OpenTelemetry.Exporter.Console/ConsoleExporterLoggingExtensions.cs | // <copyright file="ConsoleExporterLoggingExtensions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using OpenTelemetry.Exporter;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Logs
{
public static class ConsoleExporterLoggingExtensions
{
/// <summary>
/// Adds Console exporter with OpenTelemetryLoggerOptions.
/// </summary>
/// <param name="loggerOptions"><see cref="OpenTelemetryLoggerOptions"/> options to use.</param>
/// <param name="configure">Exporter configuration options.</param>
/// <returns>The instance of <see cref="OpenTelemetryLoggerOptions"/> to chain the calls.</returns>
public static OpenTelemetryLoggerOptions AddConsoleExporter(this OpenTelemetryLoggerOptions loggerOptions, Action<ConsoleExporterOptions> configure = null)
{
Guard.ThrowIfNull(loggerOptions);
var options = new ConsoleExporterOptions();
configure?.Invoke(options);
return loggerOptions.AddProcessor(new SimpleLogRecordExportProcessor(new ConsoleLogRecordExporter(options)));
}
}
}
| // <copyright file="ConsoleExporterLoggingExtensions.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using OpenTelemetry.Exporter;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Logs
{
public static class ConsoleExporterLoggingExtensions
{
/// <summary>
/// Adds Console Exporter as a configuration to the OpenTelemetry ILoggingBuilder.
/// </summary>
/// <param name="loggerOptions"><see cref="OpenTelemetryLoggerOptions"/> options to use.</param>
/// <param name="configure">Exporter configuration options.</param>
/// <returns>The instance of <see cref="OpenTelemetryLoggerOptions"/> to chain the calls.</returns>
public static OpenTelemetryLoggerOptions AddConsoleExporter(this OpenTelemetryLoggerOptions loggerOptions, Action<ConsoleExporterOptions> configure = null)
{
Guard.ThrowIfNull(loggerOptions);
var options = new ConsoleExporterOptions();
configure?.Invoke(options);
return loggerOptions.AddProcessor(new SimpleLogRecordExportProcessor(new ConsoleLogRecordExporter(options)));
}
}
}
| apache-2.0 | C# |
7d190a1befe14eb848db18dfbbea797c56d3d45a | Return simple object representing the torrent. | yonglehou/hadouken,vktr/hadouken,Robo210/hadouken,vktr/hadouken,yonglehou/hadouken,Robo210/hadouken,vktr/hadouken,Robo210/hadouken,vktr/hadouken,yonglehou/hadouken,Robo210/hadouken | src/Plugins/Torrents/Hadouken.Plugins.Torrents/Rpc/TorrentsServices.cs | src/Plugins/Torrents/Hadouken.Plugins.Torrents/Rpc/TorrentsServices.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;
namespace Hadouken.Plugins.Torrents.Rpc
{
public class TorrentsServices : IJsonRpcService
{
private readonly IBitTorrentEngine _torrentEngine;
public TorrentsServices(IBitTorrentEngine torrentEngine)
{
_torrentEngine = torrentEngine;
}
[JsonRpcMethod("torrents.start")]
public bool Start(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Start();
return true;
}
[JsonRpcMethod("torrents.stop")]
public bool Stop(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Stop();
return true;
}
[JsonRpcMethod("torrents.list")]
public object List()
{
var torrents = _torrentEngine.TorrentManagers;
return (from t in torrents
select new
{
t.Torrent.Name,
t.Torrent.Size
}).ToList();
}
[JsonRpcMethod("torrents.addFile")]
public object AddFile(byte[] data, string savePath, string label)
{
var manager = _torrentEngine.Add(data, savePath, label);
return new
{
manager.Torrent.Name,
manager.Torrent.Size
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;
namespace Hadouken.Plugins.Torrents.Rpc
{
public class TorrentsServices : IJsonRpcService
{
private readonly IBitTorrentEngine _torrentEngine;
public TorrentsServices(IBitTorrentEngine torrentEngine)
{
_torrentEngine = torrentEngine;
}
[JsonRpcMethod("torrents.start")]
public bool Start(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Start();
return true;
}
[JsonRpcMethod("torrents.stop")]
public bool Stop(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Stop();
return true;
}
[JsonRpcMethod("torrents.list")]
public object List()
{
var torrents = _torrentEngine.TorrentManagers;
return (from t in torrents
select new
{
t.Torrent.Name,
t.Torrent.Size
}).ToList();
}
[JsonRpcMethod("torrents.addFile")]
public object AddFile(byte[] data, string savePath, string label)
{
var torrent = _torrentEngine.Add(data, savePath, label);
return torrent;
}
}
}
| mit | C# |
36ca5b0cb4772d8991e71251533f4f57dcc48ea7 | Remove platforms code | bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity | build.cake | build.cake | #tool "nuget:?package=NUnit.ConsoleRunner"
var target = Argument("target", "Default");
var solution = File("./Bugsnag.Unity.sln");
var configuration = Argument("configuration", "Release");
var outputPath = Argument<string>("output", null);
Task("Restore-NuGet-Packages")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
MSBuild(solution, settings =>
settings
.SetVerbosity(Verbosity.Minimal)
.SetConfiguration(configuration));
});
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll");
NUnit3(assemblies);
});
Task("CopyToUnity")
.WithCriteria(() => outputPath != null)
.IsDependentOn("Build")
.Does(() => {
CopyFileToDirectory($"./src/Bugsnag.Unity/bin/{configuration}/net35/Bugsnag.Unity.dll", $"{outputPath}/Assets/Plugins");
CopyFileToDirectory($"./src/Assets/Standard Assets/Bugsnag/Bugsnag.cs", $"{outputPath}/Assets/Standard Assets/Bugsnag");
});
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("CopyToUnity");
RunTarget(target);
| #tool "nuget:?package=NUnit.ConsoleRunner"
var target = Argument("target", "Default");
var solution = File("./Bugsnag.Unity.sln");
var configuration = Argument("configuration", "Release");
var outputPath = Argument<string>("output", null);
var nativePlatforms = new string[] { "Android" };
Task("Restore-NuGet-Packages")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
MSBuild(solution, settings =>
settings
.SetVerbosity(Verbosity.Minimal)
.SetConfiguration(configuration));
foreach (var platform in nativePlatforms) {
MSBuild(solution, settings =>
settings
.WithProperty("UnityNativePlatform", platform)
.SetVerbosity(Verbosity.Minimal)
.SetConfiguration(configuration));
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll");
NUnit3(assemblies);
});
Task("CopyToUnity")
.WithCriteria(() => outputPath != null)
.IsDependentOn("Build")
.Does(() => {
CopyFileToDirectory($"./src/Bugsnag.Unity/bin/{configuration}/net35/Bugsnag.Unity.dll", $"{outputPath}/Assets/Plugins");
foreach (var platform in nativePlatforms) {
CopyFileToDirectory($"./src/Bugsnag.Unity/bin/{configuration}/{platform}/net35/Bugsnag.Unity.dll", $"{outputPath}/Assets/Plugins/{platform}");
}
CopyFileToDirectory($"./src/Assets/Standard Assets/Bugsnag/Bugsnag.cs", $"{outputPath}/Assets/Standard Assets/Bugsnag");
});
Task("Default")
.IsDependentOn("Test")
.IsDependentOn("CopyToUnity");
RunTarget(target);
| mit | C# |
ec8d81952aad725fab65e126a0c92a25a08a9679 | fix for running tests on linux | mrahhal/MR.Augmenter,mrahhal/MR.Augmenter | build.cake | build.cake | #addin "nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1"
#load "./build/index.cake"
var target = Argument("target", "Default");
var build = BuildParameters.Create(Context);
var util = new Util(Context, build);
Task("Clean")
.Does(() =>
{
if (DirectoryExists("./artifacts"))
{
DeleteDirectory("./artifacts", true);
}
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
DotNetCoreRestore();
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
var settings = new DotNetCoreBuildSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix
};
foreach (var project in build.ProjectFiles)
{
DotNetCoreBuild(project.FullPath, settings);
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
foreach (var project in build.TestProjectFiles)
{
if (IsRunningOnWindows())
{
DotNetCoreTest(project.FullPath);
}
else
{
var name = project.GetFilenameWithoutExtension();
var dirPath = project.GetDirectory().FullPath;
var config = build.Configuration;
var xunit = GetFiles(dirPath + "/bin/" + config + "/net451/*/dotnet-test-xunit.exe").First().FullPath;
var testfile = GetFiles(dirPath + "/bin/" + config + "/net451/*/" + name + ".dll").First().FullPath;
using(var process = StartAndReturnProcess("mono", new ProcessSettings{ Arguments = xunit + " " + testfile }))
{
process.WaitForExit();
if (process.GetExitCode() != 0)
{
throw new Exception("Mono tests failed!");
}
}
}
}
});
Task("Pack")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix,
OutputDirectory = "./artifacts/packages"
};
foreach (var project in build.ProjectFiles)
{
DotNetCorePack(project.FullPath, settings);
}
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Test")
.IsDependentOn("Pack")
.Does(() =>
{
util.PrintInfo();
});
Task("Version")
.Does(() =>
{
Information(build.FullVersion());
});
Task("Print")
.Does(() =>
{
util.PrintInfo();
});
Task("Patch")
.Does(() =>
{
util.PatchProjectFileVersions();
});
RunTarget(target);
| #addin "nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1"
#load "./build/index.cake"
var target = Argument("target", "Default");
var build = BuildParameters.Create(Context);
var util = new Util(Context, build);
Task("Clean")
.Does(() =>
{
if (DirectoryExists("./artifacts"))
{
DeleteDirectory("./artifacts", true);
}
});
Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
DotNetCoreRestore();
});
Task("Build")
.IsDependentOn("Restore")
.Does(() =>
{
var settings = new DotNetCoreBuildSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix
};
foreach (var project in build.ProjectFiles)
{
DotNetCoreBuild(project.FullPath, settings);
}
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
foreach (var testProject in build.TestProjectFiles)
{
DotNetCoreTest(testProject.FullPath);
}
});
Task("Pack")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = build.Configuration,
VersionSuffix = build.Version.Suffix,
OutputDirectory = "./artifacts/packages"
};
foreach (var project in build.ProjectFiles)
{
DotNetCorePack(project.FullPath, settings);
}
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("Test")
.IsDependentOn("Pack")
.Does(() =>
{
util.PrintInfo();
});
Task("Version")
.Does(() =>
{
Information(build.FullVersion());
});
Task("Print")
.Does(() =>
{
util.PrintInfo();
});
Task("Patch")
.Does(() =>
{
util.PatchProjectFileVersions();
});
RunTarget(target);
| mit | C# |
ff956e4e56a73b1012252cd41447b00676ae9ec5 | Remove unused method | pythonnet/pythonnet,QuantConnect/pythonnet,AlexCatarino/pythonnet,AlexCatarino/pythonnet,pythonnet/pythonnet,AlexCatarino/pythonnet,QuantConnect/pythonnet,QuantConnect/pythonnet,pythonnet/pythonnet,AlexCatarino/pythonnet | src/runtime/BorrowedReference.cs | src/runtime/BorrowedReference.cs | namespace Python.Runtime
{
using System;
/// <summary>
/// Represents a reference to a Python object, that is being lent, and
/// can only be safely used until execution returns to the caller.
/// </summary>
readonly ref struct BorrowedReference
{
readonly IntPtr pointer;
public bool IsNull => this.pointer == IntPtr.Zero;
/// <summary>Gets a raw pointer to the Python object</summary>
public IntPtr DangerousGetAddress()
=> this.IsNull ? throw new NullReferenceException() : this.pointer;
/// <summary>
/// Creates new instance of <see cref="BorrowedReference"/> from raw pointer. Unsafe.
/// </summary>
public BorrowedReference(IntPtr pointer)
{
this.pointer = pointer;
}
}
}
| namespace Python.Runtime
{
using System;
/// <summary>
/// Represents a reference to a Python object, that is being lent, and
/// can only be safely used until execution returns to the caller.
/// </summary>
readonly ref struct BorrowedReference
{
readonly IntPtr pointer;
public bool IsNull => this.pointer == IntPtr.Zero;
/// <summary>Gets a raw pointer to the Python object</summary>
public IntPtr DangerousGetAddress()
=> this.IsNull ? throw new NullReferenceException() : this.pointer;
/// <summary>
/// Gets a raw pointer to the Python object. Does not throw an exception
/// if the pointer is null
/// </summary>
public IntPtr DangerousGetAddressUnchecked() => this.pointer;
/// <summary>
/// Creates new instance of <see cref="BorrowedReference"/> from raw pointer. Unsafe.
/// </summary>
public BorrowedReference(IntPtr pointer)
{
this.pointer = pointer;
}
}
}
| mit | C# |
bbe10d1a40db4f1535770a4b8385a3208cea294a | remove extra spaces before the icons. | blogifierdotnet/Blogifier.Core,murst/Blogifier.Core,murst/Blogifier.Core,murst/Blogifier.Core,blogifierdotnet/Blogifier.Core | samples/WebApp/Views/Blogifier/Admin/Custom/_Layout/_Settings.cshtml | samples/WebApp/Views/Blogifier/Admin/Custom/_Layout/_Settings.cshtml | @using Blogifier.Core.Common
<!DOCTYPE html>
<html lang="en">
<head>
@Html.Partial("~/Views/Blogifier/Admin/Custom/_Shared/_Head.cshtml")
</head>
<body>
@Html.Partial("~/Views/Blogifier/Admin/Custom/_Shared/_Header.cshtml")
<div class="admin-content admin-content-settings container d-md-flex flex-md-column">
<div class="admin-settings row no-gutters rounded">
<ul class="admin-settings-sidebar col-md-3">
<li class="profile"><a href="~/admin/settings/profile"><span>Edit Profile</span><i class="fa fa-user"></i></a></li>
@if (!ApplicationSettings.SingleBlog)
{
<li class="personal"><a href="~/admin/settings/personal"><span>Personal Settings</span><i class="fa fa-sliders"></i></a></li>
}
<li class="import"><a href="~/admin/settings/import"><span>Import Rss</span><i class="fa fa-rss"></i></a></li>
<li class="custom"><a href="~/admin/settings/custom"><span>Custom Fields</span><i class="fa fa-window-maximize"></i></a></li>
@if (Model.Profile != null && Model.Profile.IsAdmin)
{
<li class="application"><a href="~/admin/settings/application"><span>Application Settings</span><i class="fa fa-cog"></i></a></li>
}
</ul>
<div class="admin-settings-content col-md-9">
@RenderBody()
</div>
</div>
</div>
@Html.Partial("~/Views/Blogifier/Admin/Custom/_Shared/_Footer.cshtml")
@RenderSection("Scripts", false)
</body>
</html>
| @using Blogifier.Core.Common
<!DOCTYPE html>
<html lang="en">
<head>
@Html.Partial("~/Views/Blogifier/Admin/Custom/_Shared/_Head.cshtml")
</head>
<body>
@Html.Partial("~/Views/Blogifier/Admin/Custom/_Shared/_Header.cshtml")
<div class="admin-content admin-content-settings container d-md-flex flex-md-column">
<div class="admin-settings row no-gutters rounded">
<ul class="admin-settings-sidebar col-md-3">
<li class="profile"><a href="~/admin/settings/profile"><span>Edit Profile</span> <i class="fa fa-user"></i></a></li>
@if (!ApplicationSettings.SingleBlog)
{
<li class="personal"><a href="~/admin/settings/personal"><span>Personal Settings</span> <i class="fa fa-sliders"></i></a></li>
}
<li class="import"><a href="~/admin/settings/import"><span>Import Rss</span> <i class="fa fa-rss"></i></a></li>
<li class="custom"><a href="~/admin/settings/custom"><span>Custom Fields</span> <i class="fa fa-window-maximize"></i></a></li>
@if (Model.Profile != null && Model.Profile.IsAdmin)
{
<li class="application"><a href="~/admin/settings/application"><span>Application Settings</span> <i class="fa fa-cog"></i></a></li>
}
</ul>
<div class="admin-settings-content col-md-9">
@RenderBody()
</div>
</div>
</div>
@Html.Partial("~/Views/Blogifier/Admin/Custom/_Shared/_Footer.cshtml")
@RenderSection("Scripts", false)
</body>
</html>
| mit | C# |
27e8f3af0e653e36af7441ee5ad934b39b215ac8 | Add more endpoints to csp header | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Views/stockportgov/Shared/SecurityHeaders.cshtml | src/StockportWebapp/Views/stockportgov/Shared/SecurityHeaders.cshtml | @using System.Threading.Tasks
@using StockportWebapp.FeatureToggling
@inject FeatureToggles FeatureToggles
@{
var host = Context.Request.Host.Host;
}
@if (FeatureToggles.SecurityHeaders && (host.StartsWith("www") || host.StartsWith("int-") || host.StartsWith("qa-") || host.StartsWith("stage-")))
{
<meta http-equiv="Content-Security-Policy" content="default-src https:; font-src 'self' font.googleapis.com maxcdn.bootstrapcdn.com/font-awesome/ fonts.gstatic.com/; img-src 'self' images.contentful.com/ s3-eu-west-1.amazonaws.com/share.typeform.com/ s3-eu-west-1.amazonaws.com/live-iag-static-assets/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ customer.cludo.com/img/ uk1.siteimprove.com/ stockportb.logo-net.co.uk/ *.cloudfront.net/butotv/; style-src 'self' 'unsafe-inline' *.cludo.com/css/ s3-eu-west-1.amazonaws.com/share.typeform.com/ maxcdn.bootstrapcdn.com/font-awesome/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ *.cloudfront.net/butotv/; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/ m.addthisedge.com/live/boost/ www.google-analytics.com/analytics.js api.cludo.com/scripts/ customer.cludo.com/scripts/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ s3-eu-west-1.amazonaws.com/share.typeform.com/ js.buto.tv/video/ s7.addthis.com/js/300/addthis_widget.js m.addthis.com/live/ siteimproveanalytics.com/js/ *.logo-net.co.uk/Delivery/; connect-src 'self' https://api.cludo.com/ buto-ping-middleman.buto.tv/ m.addthis.com/live/; media-src 'self' https://www.youtube.com/ *.cloudfront.net/butotv/live/videos/; object-src 'self' https://www.youtube.com http://www.youtube.com" >
} | @using System.Threading.Tasks
@using StockportWebapp.FeatureToggling
@inject FeatureToggles FeatureToggles
@{
var host = Context.Request.Host.Host;
}
@if (FeatureToggles.SecurityHeaders && (host.StartsWith("www") || host.StartsWith("int-") || host.StartsWith("qa-") || host.StartsWith("stage-")))
{
<meta http-equiv="Content-Security-Policy" content="default-src https:; font-src 'self' font.googleapis.com maxcdn.bootstrapcdn.com/font-awesome/ fonts.gstatic.com/; img-src 'self' images.contentful.com/ s3-eu-west-1.amazonaws.com/live-iag-static-assets/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ customer.cludo.com/img/ uk1.siteimprove.com/ stockportb.logo-net.co.uk/ *.cloudfront.net/butotv/; style-src 'self' 'unsafe-inline' *.cludo.com/css/ maxcdn.bootstrapcdn.com/font-awesome/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ *.cloudfront.net/butotv/; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/ api.cludo.com/scripts/ customer.cludo.com/scripts/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ s3-eu-west-1.amazonaws.com/share.typeform.com/ js.buto.tv/video/ s7.addthis.com/js/300/addthis_widget.js m.addthis.com/live/ siteimproveanalytics.com/js/ *.logo-net.co.uk/Delivery/; connect-src 'self' https://api.cludo.com/ buto-ping-middleman.buto.tv/ m.addthis.com/live/; media-src 'self' https://www.youtube.com/ *.cloudfront.net/butotv/live/videos/; object-src 'self' https://www.youtube.com http://www.youtube.com" >
} | mit | C# |
676f4ff5f240a7a3ff017b6cbae0271039f5effb | Check resource type to parse the resource value | takenet/blip-sdk-csharp | src/Take.Blip.Builder/Actions/ProcessCommand/ProcessCommandAction.cs | src/Take.Blip.Builder/Actions/ProcessCommand/ProcessCommandAction.cs | using Lime.Protocol;
using Lime.Protocol.Serialization;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
using System.Threading.Tasks;
using Take.Blip.Client;
namespace Take.Blip.Builder.Actions.ProcessCommand
{
public class ProcessCommandAction : IAction
{
private readonly ISender _sender;
private readonly IEnvelopeSerializer _envelopeSerializer;
private const string RESOURCE_KEY = "resource";
private const string RESOURCE_TYPE_KEY = "type";
private const string SERIALIZABLE_TYPE = "json";
public ProcessCommandAction(ISender sender, IEnvelopeSerializer envelopeSerializer)
{
_sender = sender;
_envelopeSerializer = envelopeSerializer;
}
public string Type => nameof(ProcessCommand);
public async Task ExecuteAsync(IContext context, JObject settings, CancellationToken cancellationToken)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (settings == null) throw new ArgumentNullException(nameof(settings), $"The settings are required for '{nameof(ProcessCommandAction)}' action");
string variable = null;
if (settings.TryGetValue(nameof(variable), out var variableToken))
{
variable = variableToken.ToString().Trim('"');
}
var command = ConvertToCommand(settings);
command.Id = EnvelopeId.NewId();
var resultCommand = await _sender.ProcessCommandAsync(command, cancellationToken);
if (string.IsNullOrWhiteSpace(variable)) return;
var resultCommandJson = _envelopeSerializer.Serialize(resultCommand);
await context.SetVariableAsync(variable, resultCommandJson, cancellationToken);
}
private Command ConvertToCommand(JObject settings)
{
if (settings.TryGetValue(RESOURCE_TYPE_KEY, out var type)
&& type.ToString().Contains(SERIALIZABLE_TYPE, StringComparison.OrdinalIgnoreCase)
&& settings.TryGetValue(RESOURCE_KEY, out var resource))
{
settings.Property(RESOURCE_KEY).Value = JObject.Parse(resource.ToString());
}
return settings.ToObject<Command>(LimeSerializerContainer.Serializer);
}
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Lime.Protocol.Serialization;
using Newtonsoft.Json.Linq;
using Take.Blip.Client;
namespace Take.Blip.Builder.Actions.ProcessCommand
{
public class ProcessCommandAction : IAction
{
private readonly ISender _sender;
private readonly IEnvelopeSerializer _envelopeSerializer;
public ProcessCommandAction(ISender sender, IEnvelopeSerializer envelopeSerializer)
{
_sender = sender;
_envelopeSerializer = envelopeSerializer;
}
public string Type => nameof(ProcessCommand);
public async Task ExecuteAsync(IContext context, JObject settings, CancellationToken cancellationToken)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (settings == null) throw new ArgumentNullException(nameof(settings), $"The settings are required for '{nameof(ProcessCommandAction)}' action");
string variable = null;
if (settings.TryGetValue(nameof(variable), out var variableToken))
{
variable = variableToken.ToString().Trim('"');
}
var command = settings.ToObject<Command>(LimeSerializerContainer.Serializer);
command.Id = EnvelopeId.NewId();
var resultCommand = await _sender.ProcessCommandAsync(command, cancellationToken);
if (string.IsNullOrWhiteSpace(variable)) return;
var resultCommandJson = _envelopeSerializer.Serialize(resultCommand);
await context.SetVariableAsync(variable, resultCommandJson, cancellationToken);
}
}
} | apache-2.0 | C# |
433697a4862c818ad538c48628920da45bc4d1c5 | Change some NetTcp unit tests to check PlatformNotSupportedException | MattGal/wcf,ericstj/wcf,iamjasonp/wcf,ElJerry/wcf,mconnew/wcf,hongdai/wcf,KKhurin/wcf,iamjasonp/wcf,StephenBonikowsky/wcf,imcarolwang/wcf,zhenlan/wcf,ElJerry/wcf,KKhurin/wcf,shmao/wcf,dotnet/wcf,hongdai/wcf,dotnet/wcf,mconnew/wcf,dotnet/wcf,ericstj/wcf,zhenlan/wcf,imcarolwang/wcf,StephenBonikowsky/wcf,mconnew/wcf,imcarolwang/wcf,shmao/wcf,MattGal/wcf | src/System.ServiceModel.NetTcp/tests/ServiceModel/MessageSecurityOverTcpTest.cs | src/System.ServiceModel.NetTcp/tests/ServiceModel/MessageSecurityOverTcpTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.ServiceModel;
using Xunit;
using Infrastructure.Common;
public static class MessageSecurityOverTcpTest
{
#if FULLXUNIT_NOTSUPPORTED
[Fact]
#endif
[WcfFact]
public static void Ctor_Default_Properties()
{
MessageSecurityOverTcp msot = new MessageSecurityOverTcp();
Assert.True(msot != null, "MessageSecurityOverTcp default ctor failed");
}
#if FULLXUNIT_NOTSUPPORTED
[Fact]
#endif
[WcfFact]
public static void Ctor_Default_Properties_Not_Supported()
{
MessageSecurityOverTcp msot = new MessageSecurityOverTcp();
Assert.Throws <PlatformNotSupportedException>(() =>
{
MessageCredentialType unused = msot.ClientCredentialType;
});
}
#if FULLXUNIT_NOTSUPPORTED
[Theory]
#endif
[WcfTheory]
[InlineData(MessageCredentialType.Certificate)]
[InlineData(MessageCredentialType.IssuedToken)]
[InlineData(MessageCredentialType.UserName)]
[InlineData(MessageCredentialType.Windows)]
public static void ClientCredentialType_Property_Values_Not_Supported(MessageCredentialType credentialType)
{
MessageSecurityOverTcp msot = new MessageSecurityOverTcp();
Assert.Throws<PlatformNotSupportedException>(() =>
{
msot.ClientCredentialType = credentialType;
});
}
#if FULLXUNIT_NOTSUPPORTED
[Theory]
#endif
[WcfTheory]
[InlineData(MessageCredentialType.None)]
public static void ClientCredentialType_Property_Values_Supported(MessageCredentialType credentialType)
{
MessageSecurityOverTcp msot = new MessageSecurityOverTcp();
msot.ClientCredentialType = credentialType;
MessageCredentialType actual = msot.ClientCredentialType;
Assert.True(actual == credentialType,
string.Format("ClientCredentialType returned '{0}' but expected '{1}'", credentialType, actual));
}
}
| // 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.ServiceModel;
using Xunit;
using Infrastructure.Common;
public static class MessageSecurityOverTcpTest
{
#if FULLXUNIT_NOTSUPPORTED
[Fact]
#endif
[WcfFact]
public static void Ctor_Default_Properties()
{
MessageSecurityOverTcp msot = new MessageSecurityOverTcp();
Assert.True(msot != null, "MessageSecurityOverTcp default ctor failed");
}
#if FULLXUNIT_NOTSUPPORTED
[Theory]
#endif
[WcfTheory]
[InlineData(MessageCredentialType.Certificate)]
[InlineData(MessageCredentialType.IssuedToken)]
[InlineData(MessageCredentialType.UserName)]
[InlineData(MessageCredentialType.Windows)]
[Issue(1434, Framework = FrameworkID.NetCore | FrameworkID.NetNative)]
public static void ClientCredentialType_Property(MessageCredentialType credentialType)
{
MessageSecurityOverTcp msot = new MessageSecurityOverTcp();
msot.ClientCredentialType = credentialType;
MessageCredentialType actual = msot.ClientCredentialType;
Assert.True(actual == credentialType,
string.Format("ClientCredentialType returned {0} but expected {1}", credentialType, actual));
}
}
| mit | C# |
1f58d1afc8dd0b03efbf92bbe4329abdb6ca9ed5 | Change WorkbookProtection code to remove warnings about obsolete methods | ClosedXML/ClosedXML,igitur/ClosedXML | ClosedXML.Examples/Misc/WorkbookProtection.cs | ClosedXML.Examples/Misc/WorkbookProtection.cs | using ClosedXML.Excel;
using System;
namespace ClosedXML.Examples.Misc
{
public class WorkbookProtection : IXLExample
{
#region Methods
// Public
public void Create(String filePath)
{
using var wb = new XLWorkbook();
wb.Worksheets.Add("Workbook Protection");
wb.Protect("Abc@123");
wb.SaveAs(filePath);
}
#endregion Methods
}
}
| using System;
using ClosedXML.Excel;
namespace ClosedXML.Examples.Misc
{
public class WorkbookProtection : IXLExample
{
#region Methods
// Public
public void Create(String filePath)
{
using (var wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add("Workbook Protection");
wb.Protect(true, false, "Abc@123");
wb.SaveAs(filePath);
}
}
#endregion
}
}
| mit | C# |
8cb169164d5725b87d14ad246417454f5b394416 | Remove unused usings | appharbor/ConsolR,appharbor/ConsolR | CodeConsole.Web/Controllers/UserController.cs | CodeConsole.Web/Controllers/UserController.cs | using System.Web.Mvc;
using Foo.Core.Model;
using Foo.Core.Persistence;
namespace ConsolR.Web.Controllers
{
public class UserController : Controller
{
private readonly Context _context = new Context();
public ActionResult Index()
{
return View(_context.Users);
}
public ActionResult Create(User user)
{
_context.Users.Add(user);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Foo.Core.Persistence;
using Foo.Core.Model;
namespace ConsolR.Web.Controllers
{
public class UserController : Controller
{
private readonly Context _context = new Context();
public ActionResult Index()
{
return View(_context.Users);
}
public ActionResult Create(User user)
{
_context.Users.Add(user);
_context.SaveChanges();
return RedirectToAction("Index");
}
}
}
| mit | C# |
c2e0a2fb64d7e004c83655e57b8a112833003c44 | test if newline is problem of failed tests | ignatandrei/Exporter,ignatandrei/Exporter,ignatandrei/Exporter | Exporter/ExporterTests/HtmlTestConstructor.cs | Exporter/ExporterTests/HtmlTestConstructor.cs | using System;
using System.Configuration;
using ExportImplementation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ExporterTests
{
public partial class HtmlTests
{
[TestClass]
public class TestConstructor
{
[TestMethod]
public void TestConstructorHeaderWithPerson()
{
var t = new Person {Name = "andrei", WebSite = "http://msprogrammer.serviciipeweb.ro/"};
var export = new ExportHtml<Person>();
Assert.AreEqual(@"<tr>
<th>Name</th>
<th>WebSite</th>
<th>CV</th>
</tr>", export.ExportHeader);
}
[TestMethod]
public void TestConstructorItemWithPerson()
{
var t = new Person {Name = "andrei", WebSite = "http://msprogrammer.serviciipeweb.ro/"};
var export = new ExportHtml<Person>();
Assert.AreEqual(@"<tr>
<td>@System.Security.SecurityElement.Escape((((object)Model.Name) ?? """").ToString())</td>
<td>@System.Security.SecurityElement.Escape((((object)Model.WebSite) ?? """").ToString())</td>
<td>@System.Security.SecurityElement.Escape((((object)Model.CV) ?? """").ToString())</td>
</tr>".Replace("\r","").Replace("\n", ""), export.ExportItem.Replace("\r", "").Replace("\n", ""));
}
}
}
}
| using System;
using System.Configuration;
using ExportImplementation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ExporterTests
{
public partial class HtmlTests
{
[TestClass]
public class TestConstructor
{
[TestMethod]
public void TestConstructorHeaderWithPerson()
{
var t = new Person {Name = "andrei", WebSite = "http://msprogrammer.serviciipeweb.ro/"};
var export = new ExportHtml<Person>();
Assert.AreEqual(@"<tr>
<th>Name</th>
<th>WebSite</th>
<th>CV</th>
</tr>", export.ExportHeader);
}
[TestMethod]
public void TestConstructorItemWithPerson()
{
var t = new Person {Name = "andrei", WebSite = "http://msprogrammer.serviciipeweb.ro/"};
var export = new ExportHtml<Person>();
Assert.AreEqual(@"<tr>
<td>@System.Security.SecurityElement.Escape((((object)Model.Name) ?? """").ToString())</td>
<td>@System.Security.SecurityElement.Escape((((object)Model.WebSite) ?? """").ToString())</td>
<td>@System.Security.SecurityElement.Escape((((object)Model.CV) ?? """").ToString())</td>
</tr>", export.ExportItem);
}
}
}
}
| apache-2.0 | C# |
a751a08ac06097e5eb393d92ebae207879eacfee | Change warning collection to be a hashset. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Core/Output/OutputSink.cs | source/Nuke.Core/Output/OutputSink.cs | // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Linq;
using Nuke.Core.Execution;
namespace Nuke.Core.Output
{
public interface IOutputSink
{
void Trace (string text);
void Info (string text);
void Warn (string text, string details = null);
void Fail (string text, string details = null);
IDisposable WriteBlock (string text);
void WriteSummary (IReadOnlyCollection<TargetDefinition> executionList);
}
internal static class OutputSink
{
private static readonly HashSet<string> s_warnings = new HashSet<string>();
public static IOutputSink Instance =>
TeamCityOutputSink.Instance
?? BitriseOutputSink.Instance
?? ConsoleOutputSink.Instance;
public static void Trace (string text)
{
if (Build.Instance?.LogLevel > LogLevel.Trace)
return;
Instance.Trace(text);
}
public static void Info (string text)
{
if (Build.Instance?.LogLevel > LogLevel.Information)
return;
Instance.Info(text);
}
public static void Warn (string text, string details = null)
{
if (Build.Instance?.LogLevel > LogLevel.Warning)
return;
s_warnings.Add(text);
Instance.Warn(text, details);
}
public static void Fail (string text, string details = null)
{
Instance.Fail(text, details);
}
public static IDisposable WriteBlock (string text)
{
return Instance.WriteBlock(text);
}
public static void WriteSummary (IReadOnlyCollection<TargetDefinition> executionList)
{
s_warnings.ToList().ForEach(x => Instance.Warn(x));
Instance.WriteSummary(executionList);
}
}
}
| // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Linq;
using Nuke.Core.Execution;
namespace Nuke.Core.Output
{
public interface IOutputSink
{
void Trace (string text);
void Info (string text);
void Warn (string text, string details = null);
void Fail (string text, string details = null);
IDisposable WriteBlock (string text);
void WriteSummary (IReadOnlyCollection<TargetDefinition> executionList);
}
internal static class OutputSink
{
private static readonly List<string> s_warnings = new List<string>();
public static IOutputSink Instance =>
TeamCityOutputSink.Instance
?? BitriseOutputSink.Instance
?? ConsoleOutputSink.Instance;
public static void Trace (string text)
{
if (Build.Instance?.LogLevel > LogLevel.Trace)
return;
Instance.Trace(text);
}
public static void Info (string text)
{
if (Build.Instance?.LogLevel > LogLevel.Information)
return;
Instance.Info(text);
}
public static void Warn (string text, string details = null)
{
if (Build.Instance?.LogLevel > LogLevel.Warning)
return;
s_warnings.Add(text);
Instance.Warn(text, details);
}
public static void Fail (string text, string details = null)
{
Instance.Fail(text, details);
}
public static IDisposable WriteBlock (string text)
{
return Instance.WriteBlock(text);
}
public static void WriteSummary (IReadOnlyCollection<TargetDefinition> executionList)
{
s_warnings.ForEach(x => Instance.Warn(x));
Instance.WriteSummary(executionList);
}
}
}
| mit | C# |
c209ec004ffce7233601e176eed216234e5ed5c2 | fix CallSite.FullName | ttRevan/cecil,saynomoo/cecil,fnajera-rac-de/cecil,furesoft/cecil,jbevain/cecil,kzu/cecil,joj/cecil,gluck/cecil,mono/cecil,SiliconStudio/Mono.Cecil,sailro/cecil,cgourlay/cecil,xen2/cecil | Mono.Cecil/CallSite.cs | Mono.Cecil/CallSite.cs | //
// CallSite.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
namespace Mono.Cecil {
public sealed class CallSite : MethodReference {
public override string FullName {
get {
var signature = new StringBuilder ();
signature.Append (ReturnType.FullName);
this.MethodSignatureFullName (signature);
return signature.ToString ();
}
}
}
}
| //
// CallSite.cs
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
namespace Mono.Cecil {
public sealed class CallSite : MethodReference {
public override string ToString ()
{
var signature = new StringBuilder ();
signature.Append (ReturnType.FullName);
this.MethodSignatureFullName (signature);
return signature.ToString ();
}
}
}
| mit | C# |
4dc0030887ea05283f35b57c323f8a0ad067906f | make navigable map inherit sorted map, as a navigable map must be a sorted map. | yanggujun/commonsfornet,yanggujun/commonsfornet | src/Commons.Collections/Map/INavigableMap.cs | src/Commons.Collections/Map/INavigableMap.cs | // Copyright CommonsForNET.
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
namespace Commons.Collections.Map
{
public interface INavigableMap<K, V> : ISortedMap<K, V>, IDictionary<K, V>
{
KeyValuePair<K, V> Lower(K key);
KeyValuePair<K, V> Higher(K key);
KeyValuePair<K, V> Ceiling(K key);
KeyValuePair<K, V> Floor(K key);
}
}
| // Copyright CommonsForNET.
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
namespace Commons.Collections.Map
{
public interface INavigableMap<K, V> : IDictionary<K, V>
{
KeyValuePair<K, V> Lower(K key);
KeyValuePair<K, V> Higher(K key);
KeyValuePair<K, V> Ceiling(K key);
KeyValuePair<K, V> Floor(K key);
}
}
| apache-2.0 | C# |
793ac211fe2ebed542f570718cc75c89bb7a0c1a | add id to details | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/TestItems/Details.cshtml | Anlab.Mvc/Views/TestItems/Details.cshtml | @model Anlab.Core.Domain.TestItem
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
</head>
<body>
<div>
<h4>TestItem</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Id)
</dt>
<dd>
@Html.DisplayFor(model => model.Id)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Analysis)
</dt>
<dd>
@Html.DisplayFor(model => model.Analysis)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Category)
</dt>
<dd>
@Html.DisplayFor(model => model.Category)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Group)
</dt>
<dd>
@Html.DisplayFor(model => model.Group)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Public)
</dt>
<dd>
@Html.DisplayFor(model => model.Public)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Notes)
</dt>
<dd>
@Html.DisplayFor(model => model.Notes)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
</body>
</html>
| @model Anlab.Core.Domain.TestItem
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Details</title>
</head>
<body>
<div>
<h4>TestItem</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Analysis)
</dt>
<dd>
@Html.DisplayFor(model => model.Analysis)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Category)
</dt>
<dd>
@Html.DisplayFor(model => model.Category)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Group)
</dt>
<dd>
@Html.DisplayFor(model => model.Group)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Public)
</dt>
<dd>
@Html.DisplayFor(model => model.Public)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Notes)
</dt>
<dd>
@Html.DisplayFor(model => model.Notes)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>
</body>
</html>
| mit | C# |
1713f29e6004d44c2d614e6479a5a5b1fc627652 | Update IPathShape.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D | src/Core2D/Model/Shapes/IPathShape.cs | src/Core2D/Model/Shapes/IPathShape.cs | using Core2D.Path;
namespace Core2D.Shapes
{
/// <summary>
/// Defines path shape contract.
/// </summary>
public interface IPathShape : IBaseShape, IStringExporter
{
/// <summary>
/// Gets or sets path geometry used to draw shape.
/// </summary>
/// <remarks>
/// Path geometry is based on path markup syntax:
/// - Xaml abbreviated geometry https://msdn.microsoft.com/en-us/library/ms752293(v=vs.110).aspx
/// - Svg path specification http://www.w3.org/TR/SVG11/paths.html
/// </remarks>
IPathGeometry Geometry { get; set; }
}
}
| using Core2D.Path;
namespace Core2D.Shapes
{
/// <summary>
/// Defines path shape contract.
/// </summary>
public interface IPathShape : IBaseShape
{
/// <summary>
/// Gets or sets path geometry used to draw shape.
/// </summary>
/// <remarks>
/// Path geometry is based on path markup syntax:
/// - Xaml abbreviated geometry https://msdn.microsoft.com/en-us/library/ms752293(v=vs.110).aspx
/// - Svg path specification http://www.w3.org/TR/SVG11/paths.html
/// </remarks>
IPathGeometry Geometry { get; set; }
}
}
| mit | C# |
6da55c910eb966fadc92362736de190a62840491 | Update Program.cs | Longfld/ASPNETcoreAngularJWT,Longfld/ASPNETcoreAngularJWT,Longfld/ASPNETcoreAngularJWT,Longfld/ASPNETcoreAngularJWT | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ASPNETCoreAngularJWT
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ASPNETCoreAngularJWT
{
public class Program
{
public static void Main(string[] args)
{
var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
Log.Logger = new LoggerConfiguration().MinimumLevel.Error().WriteTo.RollingFile(Path.Combine(env.ContentRootPath,"logs/{Date}.txt")).CreateLogger();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddSerilog(dispose: true);
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>()
.Build();
webHost.Run();
}
}
}
| mit | C# |
5f25f99f856c8338c724b89c05722380fa6d8b9d | update to use the admin flag in roles | ucdavis/Purchasing,ucdavis/Purchasing,ucdavis/Purchasing | Purchasing.Web/Models/WorkgroupDetailModel.cs | Purchasing.Web/Models/WorkgroupDetailModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Purchasing.Core.Domain;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Core.Utils;
namespace Purchasing.Web.Models
{
public class WorkgroupDetailModel
{
public Workgroup Workgroup { get; set; }
public List<UserRoles> UserRoles { get; set; }
public static WorkgroupDetailModel Create(IRepository<WorkgroupPermission> workgroupPermissionRepository, Workgroup workgroup)
{
Check.Require(workgroupPermissionRepository != null);
Check.Require(workgroup != null);
var viewModel = new WorkgroupDetailModel
{
Workgroup = workgroup,
UserRoles = new List<UserRoles>()
};
var workgroupPermissions = workgroupPermissionRepository.Queryable.Where(a => a.Workgroup == workgroup && a.User.IsActive && !a.Role.IsAdmin);
foreach (var workgroupPermission in workgroupPermissions)
{
if (workgroupPermissions.Any(a => a.User.Id == workgroupPermission.User.Id))
{
if (viewModel.UserRoles.Any(a => a.User.Id == workgroupPermission.User.Id))
{
viewModel.UserRoles.Single(a => a.User.Id == workgroupPermission.User.Id).Roles.Add(workgroupPermission.Role);
}
else
{
viewModel.UserRoles.Add(new UserRoles(workgroupPermission));
}
}
}
return viewModel;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Purchasing.Core.Domain;
using UCDArch.Core.PersistanceSupport;
using UCDArch.Core.Utils;
namespace Purchasing.Web.Models
{
public class WorkgroupDetailModel
{
public Workgroup Workgroup { get; set; }
public List<UserRoles> UserRoles { get; set; }
public static WorkgroupDetailModel Create(IRepository<WorkgroupPermission> workgroupPermissionRepository, Workgroup workgroup)
{
Check.Require(workgroupPermissionRepository != null);
Check.Require(workgroup != null);
var viewModel = new WorkgroupDetailModel
{
Workgroup = workgroup,
UserRoles = new List<UserRoles>()
};
var workgroupPermissions = workgroupPermissionRepository.Queryable.Where(a => a.Workgroup == workgroup && a.User.IsActive && a.Role.Level >= 1 && a.Role.Level <= 4);
foreach (var workgroupPermission in workgroupPermissions)
{
if (workgroupPermissions.Where(a => a.User.Id == workgroupPermission.User.Id).Any())
{
if (viewModel.UserRoles.Where(a => a.User.Id == workgroupPermission.User.Id).Any())
{
viewModel.UserRoles.Where(a => a.User.Id == workgroupPermission.User.Id).Single().Roles.Add(workgroupPermission.Role);
}
else
{
viewModel.UserRoles.Add(new UserRoles(workgroupPermission));
}
}
}
return viewModel;
}
}
} | mit | C# |
03e012a8360c84a71708436e502018b18808fb01 | add summary comment. | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP/IConsumerClient.cs | src/DotNetCore.CAP/IConsumerClient.cs | using System;
using System.Collections.Generic;
using System.Threading;
namespace DotNetCore.CAP
{
/// <inheritdoc />
/// <summary>
/// Message queue consumer client
/// </summary>
public interface IConsumerClient : IDisposable
{
/// <summary>
/// Subscribe to a set of topics to the message queue
/// </summary>
/// <param name="topics"></param>
void Subscribe(IEnumerable<string> topics);
/// <summary>
/// Start listening
/// </summary>
void Listening(TimeSpan timeout, CancellationToken cancellationToken);
/// <summary>
/// Manual submit message offset when the message consumption is complete
/// </summary>
void Commit();
/// <summary>
/// Reject message and resumption
/// </summary>
void Reject();
event EventHandler<MessageContext> OnMessageReceived;
event EventHandler<string> OnError;
}
} | using System;
using System.Collections.Generic;
using System.Threading;
namespace DotNetCore.CAP
{
/// <inheritdoc />
/// <summary>
/// Message queue consumer client
/// </summary>
public interface IConsumerClient : IDisposable
{
void Subscribe(IEnumerable<string> topics);
void Listening(TimeSpan timeout, CancellationToken cancellationToken);
void Commit();
void Reject();
event EventHandler<MessageContext> OnMessageReceived;
event EventHandler<string> OnError;
}
} | mit | C# |
52127b123c745bb50239809ab61f2128e052ddc5 | Make PowerShellScripts class static per review. | mdavid/nuget,mdavid/nuget | src/VisualStudio/PowershellScripts.cs | src/VisualStudio/PowershellScripts.cs | namespace NuGet.VisualStudio {
public static class PowerShellScripts {
public static readonly string Install = "install.ps1";
public static readonly string Uninstall = "uninstall.ps1";
public static readonly string Init = "init.ps1";
}
}
| namespace NuGet.VisualStudio {
public class PowerShellScripts {
public static readonly string Install = "install.ps1";
public static readonly string Uninstall = "uninstall.ps1";
public static readonly string Init = "init.ps1";
}
}
| apache-2.0 | C# |
31dddea9277f1f5ba7f61ab2ba6aa630d140b2ec | Add GetType | simplicbe/Simplic.Dlr,simplicbe/Simplic.Dlr | src/Simplic.Dlr/Import/IDlrImportResolver.cs | src/Simplic.Dlr/Import/IDlrImportResolver.cs | using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Simplic.Dlr
{
/// <summary>
/// Resolve path
/// </summary>
public enum ResolvedType
{
/// <summary>
/// Could not detect/find script
/// </summary>
None = 0,
/// <summary>
/// Package resolved
/// </summary>
Package = 1,
/// <summary>
/// Module resolved
/// </summary>
Module = 2
}
/// <summary>
/// Resolver for importing scripts and modules
/// </summary>
public interface IDlrImportResolver
{
/// <summary>
/// Import path
/// </summary>
/// <param name="path">Returns the script-source</param>
/// <returns></returns>
string GetScriptSource(string path);
/// <summary>
/// Detect the type of the script. Returns None-Type if not found
/// </summary>
/// <param name="path">Module name, package path or script path (ends with .py)</param>
/// <returns>Type of the script</returns>
ResolvedType GetType(string path);
/// <summary>
/// Unique resolver name
/// </summary>
Guid UniqueResolverId
{
get;
}
}
}
| using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Simplic.Dlr
{
/// <summary>
/// Resolver for importing scripts and modules
/// </summary>
public interface IDlrImportResolver
{
/// <summary>
/// Import path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
string GetScriptSource(string path);
/// <summary>
/// Unique resolver name
/// </summary>
Guid UniqueResolverId
{
get;
}
}
}
| mit | C# |
6f0e45a2a3d031befcde78c2efdc8fde6bb43338 | Update SettingWidthOfAllColumnsInWorksheet.cs | asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/RowsColumns/HeightAndWidth/SettingWidthOfAllColumnsInWorksheet.cs | Examples/CSharp/RowsColumns/HeightAndWidth/SettingWidthOfAllColumnsInWorksheet.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingWidthOfAllColumnsInWorksheet
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the width of all columns in the worksheet to 20.5
worksheet.Cells.StandardWidth = 20.5;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.HeightAndWidth
{
public class SettingWidthOfAllColumnsInWorksheet
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Setting the width of all columns in the worksheet to 20.5
worksheet.Cells.StandardWidth = 20.5;
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
} | mit | C# |
43269b702ceed03a65bb3422d1d1dcbbccbbe3d6 | remove unused fields | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Core/Parsing/Messages/S_BOSS_GAGE_INFO.cs | TCC.Core/Parsing/Messages/S_BOSS_GAGE_INFO.cs | using Tera.Game;
using Tera.Game.Messages;
namespace TCC.Parsing.Messages
{
public class S_BOSS_GAGE_INFO : ParsedMessage
{
ulong id, targetId;
int templateId, huntingZoneId;//, unk1;
float /*hpDiff,*/ currHp, maxHp;
byte enrage/*, unk3*/;
public ulong EntityId { get => id; }
public int TemplateId { get => templateId; }
public int HuntingZoneId { get => huntingZoneId; }
public float CurrentHP { get => currHp; }
public float MaxHP { get => maxHp; }
public ulong Target { get => targetId; }
public S_BOSS_GAGE_INFO(TeraMessageReader reader) : base(reader)
{
id = reader.ReadUInt64();
huntingZoneId = reader.ReadInt32();
templateId = reader.ReadInt32();
targetId = reader.ReadUInt64();
reader.Skip(4); //unk1 = reader.ReadInt32();
//if (reader.Version < 321550 || reader.Version > 321600)
//{
enrage = reader.ReadByte();
currHp = reader.ReadInt64();
maxHp = reader.ReadInt64();
//}
//else
//{
// hpDiff = reader.ReadSingle();
// enrage = reader.ReadByte();
// currHp = reader.ReadSingle();
// maxHp = reader.ReadSingle();
//}
//System.Console.WriteLine("[S_BOSS_GAGE_INFO] id:{0} name:{1}", EntityId, MonsterDatabase.GetName((uint)npc, (uint)type));
//unk3 = reader.ReadByte();
}
}
} | using Tera.Game;
using Tera.Game.Messages;
namespace TCC.Parsing.Messages
{
public class S_BOSS_GAGE_INFO : ParsedMessage
{
ulong id, targetId;
int templateId, huntingZoneId, unk1;
float hpDiff, currHp, maxHp;
byte enrage, unk3;
public ulong EntityId { get => id; }
public int TemplateId { get => templateId; }
public int HuntingZoneId { get => huntingZoneId; }
public float CurrentHP { get => currHp; }
public float MaxHP { get => maxHp; }
public ulong Target { get => targetId; }
public S_BOSS_GAGE_INFO(TeraMessageReader reader) : base(reader)
{
id = reader.ReadUInt64();
huntingZoneId = reader.ReadInt32();
templateId = reader.ReadInt32();
targetId = reader.ReadUInt64();
reader.Skip(4); //unk1 = reader.ReadInt32();
//if (reader.Version < 321550 || reader.Version > 321600)
//{
enrage = reader.ReadByte();
currHp = reader.ReadInt64();
maxHp = reader.ReadInt64();
//}
//else
//{
// hpDiff = reader.ReadSingle();
// enrage = reader.ReadByte();
// currHp = reader.ReadSingle();
// maxHp = reader.ReadSingle();
//}
//System.Console.WriteLine("[S_BOSS_GAGE_INFO] id:{0} name:{1}", EntityId, MonsterDatabase.GetName((uint)npc, (uint)type));
//unk3 = reader.ReadByte();
}
}
} | mit | C# |
9c18d822e5c2f35617d1f84f6a5f9ae6bdf50957 | update ancient assembly info | AerysBat/slimCat,WreckedAvent/slimCat | slimCat/Properties/AssemblyInfo.cs | slimCat/Properties/AssemblyInfo.cs | #region Copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright (c) 2013, Justin Kadrovach, All rights reserved.
//
// This source is subject to the Simplified BSD License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#endregion
#region Usings
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("slimCat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("slimCat Client")]
[assembly: AssemblyCopyright("Copyright © 2012 - 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:
ThemeInfo(ResourceDictionaryLocation.SourceAssembly, // where theme specific resource dictionaries are located
// (used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly // where the generic resource dictionary is located
// (used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
// Major Version
// Minor Version
// Build Number
// Revision
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.0.0")]
[assembly: AssemblyFileVersion("4.0.0")] | #region Copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs">
// Copyright (c) 2013, Justin Kadrovach, All rights reserved.
//
// This source is subject to the Simplified BSD License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
#endregion
#region Usings
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("slimCat")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("slimCat Client")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly:
ThemeInfo(ResourceDictionaryLocation.SourceAssembly, // where theme specific resource dictionaries are located
// (used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly // where the generic resource dictionary is located
// (used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
// Major Version
// Minor Version
// Build Number
// Revision
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")] | bsd-2-clause | C# |
10e474a8e1533325a8be42735d946cb063a5d5f5 | Update IRenderer.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D | Test/Core/IRenderer.cs | Test/Core/IRenderer.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.Core
{
public interface IRenderer
{
bool DrawPoints { get; set; }
void ClearCache();
void Render(object dc, ILayer layer);
void Draw(object dc, XLine line, double dx, double dy);
void Draw(object dc, XRectangle rectangle, double dx, double dy);
void Draw(object dc, XEllipse ellipse, double dx, double dy);
void Draw(object dc, XBezier bezier, double dx, double dy);
void Draw(object dc, XQBezier qbezier, double dx, double dy);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test.Core
{
public interface IRenderer
{
bool DrawPoints { get; set; }
void ClearCache();
void Render(object dc, ILayer layer);
void Draw(object dc, XLine line, double dx, double dy);
void Draw(object dc, XRectangle rectangle, double dx, double dy);
void Draw(object dc, XEllipse ellipse, double dx, double dy);
void Draw(object dc, XBezier bezier, double dx, double dy);
void Draw(object dc, XQBezier qbezier, double dx, double dy);
}
}
| mit | C# |
46cad13e4bb6a126c33fa58956c043e4361dae34 | Tweak the validation error message slightly. | alastairs/cgowebsite,alastairs/cgowebsite | src/CGO.Web/Views/Concerts/Create.cshtml | src/CGO.Web/Views/Concerts/Create.cshtml | @using CGO.Web.Helpers
@model CGO.Web.ViewModels.ConcertViewModel
@{
ViewBag.Title = "Create new Concert";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="page-header">
<h1>Create new Concert</h1>
</div>
@{ Html.EnableClientValidation(); }
@using (Html.BeginForm("Create", "Concerts", FormMethod.Post, new { id = "CreateConcert" }))
{
@Html.ValidationSummary(false, "Oh dear, the violas made a boo-boo. Please go back and fix the following mistakes:")
<fieldset>
<legend>Concert details</legend>
<h2>Basic Details</h2>
<p></p>
<p>@Html.TextBoxFor(c => c.Title, new { placeholder = "Enter title" }) @Html.ValidationMessageFor(c => c.Title)</p>
<p>
@Html.DateFor(c => c.Date, new { @class = "datetime" }) @Html.TimeFor(c => c.StartTime, new { @class = "datetime", placeholder = "Enter start time" })
@Html.ValidationMessageFor(c => c.Date) @Html.ValidationMessageFor(c => c.StartTime)
</p>
<p>@Html.TextBoxFor(c => c.Location, new { placeholder = "Enter venue " }) @Html.ValidationMessageFor(c => c.Location)</p>
<script type="text/javascript">
$("#Location").typeahead()
</script>
<h2>Marketing details</h2>
<p></p>
<p>
@Html.TextAreaFor(c => c.Description, new { @class = "description", placeholder = "Provide a description of the concert, including things like the pieces being played, the composers, the soloists for the concert, etc." })<br />
<span style="font-size: x-small">Markdown is supported for rich formatting. <a href="#" id="markdown-help">What is this?</a></span>
</p>
<p>
<label for="PosterImage" style="display: inline">Upload poster image: </label><input type="file" name="PosterImage" id="PosterImage" />
</p>
<p> </p>
<p>
@Html.HiddenFor(c => c.Published)
<input type="submit" value="Publish Concert" class="btn btn-primary" onclick="$('#Published').val(true);$('#CreateConcert').submit();" />
<input type="submit" value="Save for later" class="btn" onclick="$('#Published').val(false);$('#CreateConcert').submit();" />
<input type="reset" value="Discard" class="btn" />
</p>
</fieldset>
} | @using CGO.Web.Helpers
@model CGO.Web.ViewModels.ConcertViewModel
@{
ViewBag.Title = "Create new Concert";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="page-header">
<h1>Create new Concert</h1>
</div>
@{ Html.EnableClientValidation(); }
@using (Html.BeginForm("Create", "Concerts", FormMethod.Post, new { id = "CreateConcert" }))
{
@Html.ValidationSummary(false, "Oh dear, the violas made a boo-boo. Please go back and fix the following errors:")
<fieldset>
<legend>Concert details</legend>
<h2>Basic Details</h2>
<p></p>
<p>@Html.TextBoxFor(c => c.Title, new { placeholder = "Enter title" }) @Html.ValidationMessageFor(c => c.Title)</p>
<p>
@Html.DateFor(c => c.Date, new { @class = "datetime" }) @Html.TimeFor(c => c.StartTime, new { @class = "datetime", placeholder = "Enter start time" })
@Html.ValidationMessageFor(c => c.Date) @Html.ValidationMessageFor(c => c.StartTime)
</p>
<p>@Html.TextBoxFor(c => c.Location, new { placeholder = "Enter venue " }) @Html.ValidationMessageFor(c => c.Location)</p>
<script type="text/javascript">
$("#Location").typeahead()
</script>
<h2>Marketing details</h2>
<p></p>
<p>
@Html.TextAreaFor(c => c.Description, new { @class = "description", placeholder = "Provide a description of the concert, including things like the pieces being played, the composers, the soloists for the concert, etc." })<br />
<span style="font-size: x-small">Markdown is supported for rich formatting. <a href="#" id="markdown-help">What is this?</a></span>
</p>
<p>
<label for="PosterImage" style="display: inline">Upload poster image: </label><input type="file" name="PosterImage" id="PosterImage" />
</p>
<p> </p>
<p>
@Html.HiddenFor(c => c.Published)
<input type="submit" value="Publish Concert" class="btn btn-primary" onclick="$('#Published').val(true);$('#CreateConcert').submit();" />
<input type="submit" value="Save for later" class="btn" onclick="$('#Published').val(false);$('#CreateConcert').submit();" />
<input type="reset" value="Discard" class="btn" />
</p>
</fieldset>
} | mit | C# |
e7471bcc9e8d1e69a13ee51be180241358f11e7f | Add a regionTag for document inclusion. | GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet,GoogleCloudPlatform/getting-started-dotnet | 1-hello-world/Startup.cs | 1-hello-world/Startup.cs | // Copyright(c) 2015 Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START sample]
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
namespace GoogleCloudSamples
{
public class Startup
{
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
// [END sample] | // Copyright(c) 2015 Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
namespace GoogleCloudSamples
{
public class Startup
{
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
| apache-2.0 | C# |
c0710efc8d2d112ed66994882dc6b964503a2838 | Fix xmldoc reference | peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework | osu.Framework/Development/DebugUtils.cs | osu.Framework/Development/DebugUtils.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using osu.Framework.Configuration;
namespace osu.Framework.Development
{
public static class DebugUtils
{
internal static Assembly HostAssembly { get; set; }
public static bool IsNUnitRunning => is_nunit_running.Value;
private static readonly Lazy<bool> is_nunit_running = new Lazy<bool>(() =>
{
var entry = Assembly.GetEntryAssembly();
// when running under nunit + netcore, entry assembly becomes nunit itself (testhost, Version=15.0.0.0), which isn't what we want.
return entry == null || entry.Location.Contains("testhost");
}
);
public static bool IsDebugBuild => is_debug_build.Value;
private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() =>
isDebugAssembly(typeof(DebugUtils).Assembly) || isDebugAssembly(GetEntryAssembly())
);
/// <summary>
/// Whether the framework is currently logging performance issues via <see cref="DebugSetting.PerformanceLogging"/>.
/// This should be used only when a configuration is not available via DI or otherwise (ie. in a static context).
/// </summary>
public static bool LogPerformanceIssues { get; internal set; }
// https://stackoverflow.com/a/2186634
private static bool isDebugAssembly(Assembly assembly) => assembly?.GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled) ?? false;
/// <summary>
/// Get the entry assembly, even when running under nUnit.
/// Will fall back to calling assembly if there is no Entry assembly.
/// </summary>
/// <returns>The entry assembly (usually obtained via <see cref="Assembly.GetEntryAssembly()"/>.</returns>
public static Assembly GetEntryAssembly()
{
if (IsNUnitRunning && HostAssembly != null)
return HostAssembly;
return Assembly.GetEntryAssembly() ?? HostAssembly ?? Assembly.GetCallingAssembly();
}
/// <summary>
/// Get the entry path, even when running under nUnit.
/// </summary>
/// <returns>The entry assembly (usually obtained via the entry assembly's <see cref="Assembly.Location"/>.</returns>
public static string GetEntryPath() =>
IsNUnitRunning ? TestContext.CurrentContext.TestDirectory : Path.GetDirectoryName(GetEntryAssembly().Location);
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using osu.Framework.Configuration;
namespace osu.Framework.Development
{
public static class DebugUtils
{
internal static Assembly HostAssembly { get; set; }
public static bool IsNUnitRunning => is_nunit_running.Value;
private static readonly Lazy<bool> is_nunit_running = new Lazy<bool>(() =>
{
var entry = Assembly.GetEntryAssembly();
// when running under nunit + netcore, entry assembly becomes nunit itself (testhost, Version=15.0.0.0), which isn't what we want.
return entry == null || entry.Location.Contains("testhost");
}
);
public static bool IsDebugBuild => is_debug_build.Value;
private static readonly Lazy<bool> is_debug_build = new Lazy<bool>(() =>
isDebugAssembly(typeof(DebugUtils).Assembly) || isDebugAssembly(GetEntryAssembly())
);
/// <summary>
/// Whether the framework is currently logging performance issues via <see cref="FrameworkSetting.PerformanceLogging"/>.
/// This should be used only when a configuration is not available via DI or otherwise (ie. in a static context).
/// </summary>
public static bool LogPerformanceIssues { get; internal set; }
// https://stackoverflow.com/a/2186634
private static bool isDebugAssembly(Assembly assembly) => assembly?.GetCustomAttributes(false).OfType<DebuggableAttribute>().Any(da => da.IsJITTrackingEnabled) ?? false;
/// <summary>
/// Get the entry assembly, even when running under nUnit.
/// Will fall back to calling assembly if there is no Entry assembly.
/// </summary>
/// <returns>The entry assembly (usually obtained via <see cref="Assembly.GetEntryAssembly()"/>.</returns>
public static Assembly GetEntryAssembly()
{
if (IsNUnitRunning && HostAssembly != null)
return HostAssembly;
return Assembly.GetEntryAssembly() ?? HostAssembly ?? Assembly.GetCallingAssembly();
}
/// <summary>
/// Get the entry path, even when running under nUnit.
/// </summary>
/// <returns>The entry assembly (usually obtained via the entry assembly's <see cref="Assembly.Location"/>.</returns>
public static string GetEntryPath() =>
IsNUnitRunning ? TestContext.CurrentContext.TestDirectory : Path.GetDirectoryName(GetEntryAssembly().Location);
}
}
| mit | C# |
6387a96eeae67b10be517eb1721d2f7ec8bd23cc | Rename CallVisionAPI to CallEmotionAPI | lindydonna/CoderCards,lindydonna/CoderCards,lindydonna/CoderCards | CardGenerator/run.csx | CardGenerator/run.csx | #load "image-lib.csx"
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public static async Task Run(byte[] image, string filename, Stream outputBlob, TraceWriter log)
{
string result = await CallEmotionAPI(image);
log.Info(result);
if (String.IsNullOrEmpty(result)) {
return;
}
var personInfo = GetNameAndTitle(filename);
var imageData = JsonConvert.DeserializeObject<Face[]>(result);
var faceData = imageData[0]; // assume exactly one face
double score = 0;
var card = GetCardImageAndScores(faceData.Scores, out score);
MergeCardImage(card, image, personInfo, score);
SaveAsJpeg(card, outputBlob);
}
static Image GetCardImageAndScores(Scores scores, out double score)
{
NormalizeScores(scores);
var cardBack = "neutral.png";
score = scores.Neutral;
const int angerBoost = 2, happyBoost = 4;
if (scores.Surprise > 10) {
cardBack = "surprised.png";
score = scores.Surprise;
}
else if (scores.Anger > 10) {
cardBack = "angry.png";
score = scores.Anger * angerBoost;
}
else if (scores.Happiness > 50) {
cardBack = "happy.png";
score = scores.Happiness * happyBoost;
}
return Image.FromFile(GetFullImagePath(cardBack));
}
static async Task<string> CallEmotionAPI(byte[] image)
{
var client = new HttpClient();
var content = new StreamContent(new MemoryStream(image));
var url = "https://api.projectoxford.ai/emotion/v1.0/recognize";
var key = Environment.GetEnvironmentVariable("EmotionAPIKey");
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var httpResponse = await client.PostAsync(url, content);
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
return await httpResponse.Content.ReadAsStringAsync();
}
return null;
} | #load "image-lib.csx"
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public static async Task Run(byte[] image, string filename, Stream outputBlob, TraceWriter log)
{
string result = await CallVisionAPI(image);
log.Info(result);
if (String.IsNullOrEmpty(result)) {
return;
}
var personInfo = GetNameAndTitle(filename);
var imageData = JsonConvert.DeserializeObject<Face[]>(result);
var faceData = imageData[0]; // assume exactly one face
double score = 0;
var card = GetCardImageAndScores(faceData.Scores, out score);
MergeCardImage(card, image, personInfo, score);
SaveAsJpeg(card, outputBlob);
}
static Image GetCardImageAndScores(Scores scores, out double score)
{
NormalizeScores(scores);
var cardBack = "neutral.png";
score = scores.Neutral;
const int angerBoost = 2, happyBoost = 4;
if (scores.Surprise > 10) {
cardBack = "surprised.png";
score = scores.Surprise;
}
else if (scores.Anger > 10) {
cardBack = "angry.png";
score = scores.Anger * angerBoost;
}
else if (scores.Happiness > 50) {
cardBack = "happy.png";
score = scores.Happiness * happyBoost;
}
return Image.FromFile(GetFullImagePath(cardBack));
}
static async Task<string> CallVisionAPI(byte[] image)
{
var client = new HttpClient();
var content = new StreamContent(new MemoryStream(image));
var url = "https://api.projectoxford.ai/emotion/v1.0/recognize";
var key = Environment.GetEnvironmentVariable("EmotionAPIKey");
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var httpResponse = await client.PostAsync(url, content);
if (httpResponse.StatusCode == HttpStatusCode.OK)
{
return await httpResponse.Content.ReadAsStringAsync();
}
return null;
} | mit | C# |
a39871ba33cb951a4b54352b96da8eb40403ce7e | Fix mod parser getting loaded | Piotrekol/StreamCompanion,Piotrekol/StreamCompanion | plugins/ModsHandler/ModParser.cs | plugins/ModsHandler/ModParser.cs | using StreamCompanionTypes;
using StreamCompanionTypes.Interfaces;
namespace ModsHandler
{
public class ModParser : CollectionManager.Modules.ModParser.ModParser, IModule, IModParser, ISettingsProvider
{
private readonly SettingNames _names = SettingNames.Instance;
private ISettingsHandler _settings;
private ModParserSettings _modParserSettings;
public bool Started { get; set; }
public string SettingGroup { get; } = "Map matching";
public void Start(ILogger logger)
{
Started = true;
}
private void UpdateNoModText()
{
string noneText = _settings?.Get<string>(_names.NoModsDisplayText) ?? "None";
if (LongNoModText != noneText)
LongNoModText = noneText;
if (ShortNoModText != noneText)
ShortNoModText = noneText;
}
public string GetModsFromEnum(int modsEnum)
{
UpdateNoModText();
var shortMod = !_settings?.Get<bool>(_names.UseLongMods) ?? true;
return GetModsFromEnum(modsEnum, shortMod);
}
public void SetSettingsHandle(ISettingsHandler settings)
{
_settings = settings;
}
public void Free()
{
_modParserSettings.Dispose();
}
public System.Windows.Forms.UserControl GetUiSettings()
{
if (_modParserSettings == null || _modParserSettings.IsDisposed)
{
_modParserSettings = new ModParserSettings(_settings);
}
return _modParserSettings;
}
}
}
| using StreamCompanionTypes;
using StreamCompanionTypes.Interfaces;
namespace ModsHandler
{
public class ModParser : CollectionManager.Modules.ModParser.ModParser, IPlugin, IModParser, ISettingsProvider
{
private readonly SettingNames _names = SettingNames.Instance;
private ISettingsHandler _settings;
private ModParserSettings _modParserSettings;
public bool Started { get; set; }
public string SettingGroup { get; } = "Map matching";
public string Description { get; } = "";
public string Name { get; } = nameof(ModParser);
public string Author { get; } = "Piotrekol";
public string Url { get; } = "";
public string UpdateUrl { get; } = "";
public void Start(ILogger logger)
{
Started = true;
}
private void UpdateNoModText()
{
string noneText = _settings?.Get<string>(_names.NoModsDisplayText) ?? "None";
if (LongNoModText != noneText)
LongNoModText = noneText;
if (ShortNoModText != noneText)
ShortNoModText = noneText;
}
public string GetModsFromEnum(int modsEnum)
{
UpdateNoModText();
var shortMod = !_settings?.Get<bool>(_names.UseLongMods) ?? true;
return GetModsFromEnum(modsEnum, shortMod);
}
public void SetSettingsHandle(ISettingsHandler settings)
{
_settings = settings;
}
public void Free()
{
_modParserSettings.Dispose();
}
public System.Windows.Forms.UserControl GetUiSettings()
{
if (_modParserSettings == null || _modParserSettings.IsDisposed)
{
_modParserSettings = new ModParserSettings(_settings);
}
return _modParserSettings;
}
}
}
| mit | C# |
89b7c16df2dd97875a988d8ab41e2d48769b00d5 | Make namning convention props virtual | pardahlman/RawRabbit,northspb/RawRabbit | src/RawRabbit/Common/NamingConvetions.cs | src/RawRabbit/Common/NamingConvetions.cs | using System;
namespace RawRabbit.Common
{
public interface INamingConvetions
{
Func<Type, string> ExchangeNamingConvention { get; set; }
Func<Type, string> QueueNamingConvention { get; set; }
Func<Type, Type, string> RpcExchangeNamingConvention { get; set; }
Func<string> ErrorExchangeNamingConvention { get; set; }
Func<string> ErrorQueueNamingConvention { get; set; }
Func<string> DeadLetterExchangeNamingConvention { get; set; }
}
public class NamingConvetions : INamingConvetions
{
public virtual Func<Type, string> ExchangeNamingConvention { get; set; }
public virtual Func<Type, string> QueueNamingConvention { get; set; }
public virtual Func<Type, Type, string> RpcExchangeNamingConvention { get; set; }
public virtual Func<string> ErrorExchangeNamingConvention { get; set; }
public virtual Func<string> ErrorQueueNamingConvention { get; set; }
public virtual Func<string> DeadLetterExchangeNamingConvention { get; set; }
public NamingConvetions()
{
ExchangeNamingConvention = type => type?.Namespace?.ToLower();
RpcExchangeNamingConvention = (request, response) => request?.Namespace?.ToLower() ?? "default_rpc_exchange";
QueueNamingConvention = type => CreateShortAfqn(type);
ErrorQueueNamingConvention = () => "default_error_queue";
ErrorExchangeNamingConvention = () => "default_error_exchange";
DeadLetterExchangeNamingConvention = () => "default_dead_letter_exchange";
}
private static string CreateShortAfqn(Type type, string path = "", string delimeter = ".")
{
var t = $"{path}{(string.IsNullOrEmpty(path) ? string.Empty : delimeter)}{GetNonGenericTypeName(type)}";
if (type.IsGenericType)
{
t += "[";
foreach (var argument in type.GenericTypeArguments)
{
t = CreateShortAfqn(argument, t, t.EndsWith("[") ? string.Empty : ",");
}
t += "]";
}
return (t.Length > 254
? string.Concat("...", t.Substring(t.Length - 250))
: t).ToLowerInvariant();
}
public static string GetNonGenericTypeName(Type type)
{
var name = !type.IsGenericType
? new[] { type.Name }
: type.Name.Split('`');
return name[0];
}
}
} | using System;
namespace RawRabbit.Common
{
public interface INamingConvetions
{
Func<Type, string> ExchangeNamingConvention { get; set; }
Func<Type, string> QueueNamingConvention { get; set; }
Func<Type, Type, string> RpcExchangeNamingConvention { get; set; }
Func<string> ErrorExchangeNamingConvention { get; set; }
Func<string> ErrorQueueNamingConvention { get; set; }
Func<string> DeadLetterExchangeNamingConvention { get; set; }
}
public class NamingConvetions : INamingConvetions
{
public Func<Type, string> ExchangeNamingConvention { get; set; }
public Func<Type, string> QueueNamingConvention { get; set; }
public Func<Type, Type, string> RpcExchangeNamingConvention { get; set; }
public Func<string> ErrorExchangeNamingConvention { get; set; }
public Func<string> ErrorQueueNamingConvention { get; set; }
public Func<string> DeadLetterExchangeNamingConvention { get; set; }
public NamingConvetions()
{
ExchangeNamingConvention = type => type?.Namespace?.ToLower();
RpcExchangeNamingConvention = (request, response) => request?.Namespace?.ToLower() ?? "default_rpc_exchange";
QueueNamingConvention = type => CreateShortAfqn(type);
ErrorQueueNamingConvention = () => "default_error_queue";
ErrorExchangeNamingConvention = () => "default_error_exchange";
DeadLetterExchangeNamingConvention = () => "default_dead_letter_exchange";
}
private static string CreateShortAfqn(Type type, string path = "", string delimeter = ".")
{
var t = $"{path}{(string.IsNullOrEmpty(path) ? string.Empty : delimeter)}{GetNonGenericTypeName(type)}";
if (type.IsGenericType)
{
t += "[";
foreach (var argument in type.GenericTypeArguments)
{
t = CreateShortAfqn(argument, t, t.EndsWith("[") ? string.Empty : ",");
}
t += "]";
}
return (t.Length > 254
? string.Concat("...", t.Substring(t.Length - 250))
: t).ToLowerInvariant();
}
public static string GetNonGenericTypeName(Type type)
{
var name = !type.IsGenericType
? new[] { type.Name }
: type.Name.Split('`');
return name[0];
}
}
} | mit | C# |
16287c1d65711f516d81d403bf516ddc66cdd87b | Update version number for nuGet v2.1 release | Zeugma440/atldotnet | ATL/Properties/AssemblyInfo.cs | ATL/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("ATL")]
[assembly: AssemblyDescription("Audio Tools Library .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ATL")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("1597be31-1d62-45a6-8abb-380c406238e9")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("ATL")]
[assembly: AssemblyDescription("Audio Tools Library .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ATL")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("1597be31-1d62-45a6-8abb-380c406238e9")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
| mit | C# |
bd2d5f068f565f45840bdd655ba5070bd58bcd7f | Bump to version 0.5.0 | mgrosperrin/commandlineparser | src/CommonFiles/VersionAssemblyInfo.cs | src/CommonFiles/VersionAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("0.5.0")]
[assembly: AssemblyFileVersion("0.5.0")]
[assembly:AssemblyInformationalVersion("0.5.0.")] | using System.Reflection;
[assembly: AssemblyVersion("0.5.0.0")]
[assembly: AssemblyFileVersion("0.5.0.0")]
[assembly:AssemblyInformationalVersion("0.5.0.0-beta1")] | mit | C# |
0b43545ae0f4dd71ecfd8c270512bc47634f47d5 | Update ReplyAsync Task to return the sent message. | RogueException/Discord.Net,Confruggy/Discord.Net,AntiTcb/Discord.Net,LassieME/Discord.Net | src/Discord.Net.Commands/ModuleBase.cs | src/Discord.Net.Commands/ModuleBase.cs | using System.Threading.Tasks;
namespace Discord.Commands
{
public abstract class ModuleBase
{
public CommandContext Context { get; internal set; }
protected virtual async Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
{
return await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
}
}
}
| using System.Threading.Tasks;
namespace Discord.Commands
{
public abstract class ModuleBase
{
public CommandContext Context { get; internal set; }
protected virtual async Task ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
{
await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
}
}
}
| mit | C# |
7a7309b48b8f929eb5e2e321c01c1515879d041c | Update the level selector input at the bottom of the leaderboard | DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17 | Proto/Assets/Scripts/UI/SceneSelector.cs | Proto/Assets/Scripts/UI/SceneSelector.cs | using System;
using UnityEngine;
using UnityEngine.UI;
public class SceneSelector : MonoBehaviour
{
[SerializeField] private Text _levelName;
[SerializeField] private string[] _levels;
[SerializeField] private Button _leftArrow;
[SerializeField] private Button _rightArrow;
private int pos = 0;
private LeaderboardUI _leaderboardUI;
private void Start()
{
_leaderboardUI = FindObjectOfType<LeaderboardUI>();
var levelShown = FindObjectOfType<LevelToLoad>().GetLevelToLoad();
pos = GetPosOfLevelShown(levelShown);
_levelName.text = _levels[pos];
UpdateArrows();
}
private int GetPosOfLevelShown(string levelShown)
{
for (var i = 0; i < _levels.Length; ++i)
{
var level = _levels[i];
if (level.IndexOf(levelShown, StringComparison.InvariantCultureIgnoreCase) > -1)
return i;
}
//Defaults at loading the first entry if nothing found
return 0;
}
public void LeftArrowClick()
{
_levelName.text = _levels[--pos];
_leaderboardUI.LoadScene(_levels[pos]);
UpdateArrows();
}
public void RightArrowClick()
{
_levelName.text = _levels[++pos];
_leaderboardUI.LoadScene(_levels[pos]);
UpdateArrows();
}
private void UpdateArrows()
{
_leftArrow.gameObject.SetActive(true);
_rightArrow.gameObject.SetActive(true);
if (pos == 0) _leftArrow.gameObject.SetActive(false);
if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
}
}
| using UnityEngine;
using UnityEngine.UI;
public class SceneSelector : MonoBehaviour
{
[SerializeField] private Text _levelName;
[SerializeField] private string[] _levels;
[SerializeField] private Button _leftArrow;
[SerializeField] private Button _rightArrow;
private int pos = 0;
private LeaderboardUI _leaderboardUI;
private void Start()
{
_leaderboardUI = FindObjectOfType<LeaderboardUI>();
_levelName.text = _levels[pos];
_leftArrow.gameObject.SetActive(false);
if (_levels.Length <= 1) _rightArrow.gameObject.SetActive(false);
}
public void LeftArrowClick()
{
_levelName.text = _levels[--pos];
if (pos == 0) _leftArrow.gameObject.SetActive(false);
if (_levels.Length > 1) _rightArrow.gameObject.SetActive(true);
_leaderboardUI.LoadScene(_levels[pos]);
}
public void RightArrowClick()
{
_levelName.text = _levels[++pos];
if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
_leftArrow.gameObject.SetActive(true);
_leaderboardUI.LoadScene(_levels[pos]);
}
}
| mit | C# |
2af5f29bc5afc09c7b763aa4e2c487d7772f2119 | Update WebClientMessenger.cs | jonasbutt/ReactiveWebApp,jonasbutt/ReactiveWebApp | ReactiveWebApp/Web/WebClientMessenger.cs | ReactiveWebApp/Web/WebClientMessenger.cs | using System.Linq;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Reactive.ActorModel;
namespace Reactive.Web
{
public class WebClientMessenger : IWebClientMessenger
{
private readonly IHubContext messageHubContext;
public WebClientMessenger()
{
messageHubContext = GlobalHost.ConnectionManager.GetHubContext<WebClientMessagingHub>();
}
public void SendMessageToAllWebClients<TMessage>(TMessage message)
{
SendMessage<TMessage>(message, messageHubContext.Clients.All);
}
private void SendMessage<TMessage>(TMessage message, IClientProxy messageHub)
{
var messageType = typeof(TMessage);
var methodName = messageType.Name;
var methodNameLowercased = methodName.First().ToString().ToLowerInvariant() + methodName.Substring(1);
messageHub.Invoke(methodNameLowercased, message);
}
}
}
| using System.Linq;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Reactive.ActorModel;
namespace Reactive.Web
{
public class WebClientMessenger : IWebClientMessenger
{
private readonly IHubContext messageHubContext;
public WebClientMessenger()
{
messageHubContext = GlobalHost.ConnectionManager.GetHubContext<WebClientMessagingHub>();
}
public void SendMessageToAllWebClients<TMessage>(TMessage message)
{
SendMessage<TMessage>(message, messageHubContext.Clients.All);
}
private void SendMessage<TMessage>(TMessage message, IClientProxy messageHub)
{
var messageType = typeof(TMessage);
var methodName = messageType.Name;
var methodNameLowercased = methodName.First().ToString().ToLowerInvariant() + methodName.Substring(1);
messageHub.Invoke(methodNameLowercased, message);
//var type = messageHub.GetType();
//var method = type.GetMethod(methodNameLowercased);
//method.Invoke(messageHub, new object[] { message });
}
}
} | apache-2.0 | C# |
7ef157d303a3cc44afb4b8f7b9eb66bb66d2a09b | Update version info. | maraf/Money,maraf/Money,maraf/Money | src/Money.UI.Blazor/Pages/About.cshtml | src/Money.UI.Blazor/Pages/About.cshtml | @page "/about"
<h1>Money</h1>
<h4>Neptuo</h4>
<p class="gray">
v1.2.1
</p>
<p>
<a target="_blank" href="http://github.com/maraf/Money">Documentation</a>
</p>
<p>
<a target="_blank" href="https://github.com/maraf/Money/issues/new">Report an issue</a>
</p> | @page "/about"
<h1>Money</h1>
<h4>Neptuo</h4>
<p class="gray">
v1.2.0
</p>
<p>
<a target="_blank" href="http://github.com/maraf/Money">Documentation</a>
</p>
<p>
<a target="_blank" href="https://github.com/maraf/Money/issues/new">Report an issue</a>
</p> | apache-2.0 | C# |
5989a7717458af7f9dd42e31e7f31fc38be3522f | Update DragDropExtensions.cs | punker76/gong-wpf-dragdrop | src/GongSolutions.WPF.DragDrop.Shared/Utilities/DragDropExtensions.cs | src/GongSolutions.WPF.DragDrop.Shared/Utilities/DragDropExtensions.cs | using System.Windows;
using System.Windows.Media;
namespace GongSolutions.Wpf.DragDrop.Utilities
{
public static class DragDropExtensions
{
/// <summary>
/// Determines whether the given element is ignored on drag start (<see cref="DragDrop.DragSourceIgnore"/>).
/// </summary>
/// <param name="element">The given element.</param>
/// <returns>Element is ignored or not.</returns>
public static bool IsDragSourceIgnored(this UIElement element)
{
return element != null && DragDrop.GetDragSourceIgnore(element);
}
/// <summary>
/// Determines whether the given element is ignored on drop action (<see cref="DragDrop.IsDragSource"/>).
/// </summary>
/// <param name="element">The given element.</param>
/// <returns>Element is ignored or not.</returns>
public static bool IsDragSource(this UIElement element)
{
return element != null && DragDrop.GetIsDragSource(element);
}
/// <summary>
/// Determines whether the given element is ignored on drop action (<see cref="DragDrop.IsDropTarget"/>).
/// </summary>
/// <param name="element">The given element.</param>
/// <returns>Element is ignored or not.</returns>
public static bool IsDropTarget(this UIElement element)
{
return element != null && DragDrop.GetIsDropTarget(element);
}
/// <summary>
/// Gets if drop position is directly over element
/// </summary>
/// <param name="dropPosition">Drop position</param>
/// <param name="element">element to check whether or not the drop position is directly over or not</param>
/// <param name="relativeToElement">element to which the drop position is related</param>
/// <returns>drop position is directly over element or not</returns>
public static bool DirectlyOverElement(this Point dropPosition, UIElement element, UIElement relativeToElement)
{
if (element == null)
return false;
var relativeItemPosition = element.TranslatePoint(new Point(0, 0), relativeToElement);
var relativeDropPosition = new Point(dropPosition.X - relativeItemPosition.X, dropPosition.Y - relativeItemPosition.Y);
return VisualTreeHelper.GetDescendantBounds(element).Contains(relativeDropPosition);
}
}
}
| using System.Windows;
namespace GongSolutions.Wpf.DragDrop.Utilities
{
public static class DragDropExtensions
{
/// <summary>
/// Determines whether the given element is ignored on drag start (<see cref="DragDrop.DragSourceIgnore"/>).
/// </summary>
/// <param name="element">The given element.</param>
/// <returns>Element is ignored or not.</returns>
public static bool IsDragSourceIgnored(this UIElement element)
{
return element != null && DragDrop.GetDragSourceIgnore(element);
}
/// <summary>
/// Determines whether the given element is ignored on drop action (<see cref="DragDrop.IsDragSource"/>).
/// </summary>
/// <param name="element">The given element.</param>
/// <returns>Element is ignored or not.</returns>
public static bool IsDragSource(this UIElement element)
{
return element != null && DragDrop.GetIsDragSource(element);
}
/// <summary>
/// Determines whether the given element is ignored on drop action (<see cref="DragDrop.IsDropTarget"/>).
/// </summary>
/// <param name="element">The given element.</param>
/// <returns>Element is ignored or not.</returns>
public static bool IsDropTarget(this UIElement element)
{
return element != null && DragDrop.GetIsDropTarget(element);
}
/// <summary>
/// Gets if drop position is directly over element
/// </summary>
/// <param name="dropPosition">Drop position</param>
/// <param name="element">element to check whether or not the drop position is directly over or not</param>
/// <param name="relativeToElement">element to which the drop position is related</param>
/// <returns>drop position is directly over element or not</returns>
public static bool DirectlyOverElement(this Point dropPosition, UIElement element, UIElement relativeToElement)
{
if (element == null)
return false;
var relativeItemPosition = element.TranslatePoint(new Point(0, 0), relativeToElement);
var relativeDropPosition = new Point(dropPosition.X - relativeItemPosition.X, dropPosition.Y - relativeItemPosition.Y);
return VisualTreeHelper.GetDescendantBounds(element).Contains(relativeDropPosition);
}
}
}
| bsd-3-clause | C# |
41ff97c3b899b428b648a0be226e7829a0c6dc66 | Fix AssociationContracts.BiDirOneToMany and AssociationContracts.BiDirManyToOne. | peopleware/net-ppwcode-vernacular-nhibernate | src/PPWCode.Vernacular.NHibernate.I/Semantics/AssociationContracts.cs | src/PPWCode.Vernacular.NHibernate.I/Semantics/AssociationContracts.cs | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using Iesi.Collections.Generic;
using NHibernate;
namespace PPWCode.Vernacular.NHibernate.I.Semantics
{
public static class AssociationContracts
{
public static bool BiDirOneToMany<O, M>(O one, ISet<M> many, Func<M, O> toOne)
where M : class
where O : class
{
return many != null && (!NHibernateUtil.IsInitialized(many) || many.All(x => x != null && toOne(x) == one));
}
public static bool BiDirParentToChild<O, M>(O one, ISet<M> many, Func<M, O> toOne)
where M : class
where O : class
{
return BiDirOneToMany(one, many, toOne);
}
public static bool BiDirManyToOne<O, M>(M many, O one, Func<O, ISet<M>> toMany)
where M : class
where O : class
{
return one == null || !NHibernateUtil.IsInitialized(one) || toMany(one).Any(x => x == many);
}
public static bool BiDirChildToParent<O, M>(M many, O one, Func<O, ISet<M>> toMany)
where M : class
where O : class
{
return BiDirManyToOne(many, one, toMany);
}
}
} | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using Iesi.Collections.Generic;
using NHibernate;
namespace PPWCode.Vernacular.NHibernate.I.Semantics
{
public static class AssociationContracts
{
public static bool BiDirOneToMany<O, M>(O one, ISet<M> many, Func<M, O> toOne)
where M : class
where O : class
{
return many != null
&& NHibernateUtil.IsInitialized(many)
&& many.All(x => x != null && toOne(x) == one);
}
public static bool BiDirManyToOne<O, M>(M many, O one, Func<O, ISet<M>> toMany)
where M : class
where O : class
{
return one != null
&& NHibernateUtil.IsInitialized(one)
&& toMany(one).Any(x => x == many);
}
}
} | apache-2.0 | C# |
0eea6ffc39cbe42a21b102a29986ceffc0570dc8 | Fix broken 3.5 build | amironov73/ManagedIrbis,amironov73/ManagedIrbis,amironov73/ManagedIrbis,amironov73/ManagedIrbis,amironov73/ManagedIrbis | Sources/AM.Core/AM/ExceptionEventArgs.cs | Sources/AM.Core/AM/ExceptionEventArgs.cs | /* ExceptionEventArgs.cs -- information about exception
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Diagnostics;
using CodeJam;
using JetBrains.Annotations;
#endregion
namespace AM
{
/// <summary>
/// Information about exception.
/// </summary>
[PublicAPI]
[DebuggerDisplay("{Exception} {Handled}")]
public sealed class ExceptionEventArgs<T>
: EventArgs
where T: Exception
{
#region Properties
/// <summary>
/// Exception.
/// </summary>
[NotNull]
public T Exception { get; private set; }
/// <summary>
/// Handled?
/// </summary>
public bool Handled { get; set; }
#endregion
#region Construction
/// <summary>
/// Constructor.
/// </summary>
public ExceptionEventArgs
(
[NotNull] T exception
)
{
Code.NotNull(exception, "exception");
Exception = exception;
}
#endregion
}
}
| /* ExceptionEventArgs.cs -- information about exception
* Ars Magna project, http://arsmagna.ru
* -------------------------------------------------------
* Status: poor
*/
#region Using directives
using System;
using System.Diagnostics;
using CodeJam;
using JetBrains.Annotations;
#endregion
namespace AM
{
/// <summary>
/// Information about exception.
/// </summary>
[PublicAPI]
[DebuggerDisplay("{Exception} {Handled}")]
public sealed class ExceptionEventArgs<T>
where T: Exception
{
#region Properties
/// <summary>
/// Exception.
/// </summary>
[NotNull]
public T Exception { get; private set; }
/// <summary>
/// Handled?
/// </summary>
public bool Handled { get; set; }
#endregion
#region Construction
/// <summary>
/// Constructor.
/// </summary>
public ExceptionEventArgs
(
[NotNull] T exception
)
{
Code.NotNull(exception, "exception");
Exception = exception;
}
#endregion
}
}
| mit | C# |
81e420e5b6e0f7c82949ebcf3caddab4099a53aa | Update SetUpFixture | atata-framework/atata-bootstrap,atata-framework/atata-bootstrap | src/Atata.Bootstrap.Tests/SetUpFixture.cs | src/Atata.Bootstrap.Tests/SetUpFixture.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using NUnit.Framework;
namespace Atata.Bootstrap.Tests
{
[SetUpFixture]
public class SetUpFixture
{
private Process coreRunProcess;
[OneTimeSetUp]
public void GlobalSetUp()
{
try
{
PingTestApp();
}
catch
{
RunTestApp();
}
}
private static WebResponse PingTestApp() =>
WebRequest.CreateHttp(UITestFixture.BaseUrl).GetResponse();
private void RunTestApp()
{
coreRunProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c dotnet run",
WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\..\\Atata.Bootstrap.TestApp")
}
};
coreRunProcess.Start();
Thread.Sleep(5000);
var testAppWait = new SafeWait<SetUpFixture>(this)
{
Timeout = TimeSpan.FromSeconds(40),
PollingInterval = TimeSpan.FromSeconds(1)
};
testAppWait.IgnoreExceptionTypes(typeof(WebException));
testAppWait.Until(x => PingTestApp());
}
[OneTimeTearDown]
public void GlobalTearDown()
{
if (coreRunProcess != null)
{
coreRunProcess.Kill(true);
coreRunProcess.Dispose();
}
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using NUnit.Framework;
namespace Atata.Bootstrap.Tests
{
[SetUpFixture]
public class SetUpFixture
{
private Process coreRunProcess;
[OneTimeSetUp]
public void GlobalSetUp()
{
try
{
PingTestApp();
}
catch
{
RunTestApp();
}
}
private static WebResponse PingTestApp() =>
WebRequest.CreateHttp(UITestFixture.BaseUrl).GetResponse();
private void RunTestApp()
{
coreRunProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "/c dotnet run",
WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\..\\Atata.Bootstrap.TestApp")
}
};
coreRunProcess.Start();
Thread.Sleep(5000);
var testAppWait = new SafeWait<SetUpFixture>(this)
{
Timeout = TimeSpan.FromSeconds(40),
PollingInterval = TimeSpan.FromSeconds(1)
};
testAppWait.IgnoreExceptionTypes(typeof(WebException));
testAppWait.Until(x => PingTestApp());
}
[OneTimeTearDown]
public void GlobalTearDown()
{
coreRunProcess?.CloseMainWindow();
coreRunProcess?.Dispose();
}
}
}
| apache-2.0 | C# |
bb0469b163626291a0e4eba880323bb0760ffb84 | Update ListRequest with new base class contructor. | DotNetDevs/Synology,DotNetDevs/Synology | Synology.FileStation/List/ListRequest.cs | Synology.FileStation/List/ListRequest.cs | using System;
using Synology.Classes;
using Synology.Attributes;
using Synology.FileStation.List.Parameters;
using Synology.FileStation.List.Results;
namespace Synology.FileStation.List
{
[Request("List")]
public class ListRequest : FileStationRequest
{
public ListRequest(SynologyApi api) : base(api)
{
}
/// <summary>
/// Enumerate files in a given folder
/// </summary>
[RequestMethod("list_share")]
public ResultData<ListSharesResult> ListShares(ListSharesParameters parameters)
{
return GetData<ListSharesResult>(new Synology.Parameters.SynologyRequestParameters
{
Version = 2,
Additional = parameters,
});
}
/// <summary>
/// Enumerate files in a given folder
/// </summary>
[RequestMethod("list")]
public ResultData ListFiles()
{
throw new NotImplementedException();
}
[RequestMethod("getinfo")]
public ResultData GetFileInfo()
{
throw new NotImplementedException();
}
}
}
| using System;
using Synology.Classes;
using Synology.Attributes;
using Synology.FileStation.List.Parameters;
using Synology.FileStation.List.Results;
namespace Synology.FileStation.List
{
[Request("List")]
public class ListRequest : FileStationRequest
{
public ListRequest(SynologyApi api) : base(api, "List")
{
}
/// <summary>
/// Enumerate files in a given folder
/// </summary>
[RequestMethod("list_share")]
public ResultData<ListSharesResult> ListShares(ListSharesParameters parameters)
{
return GetData<ListSharesResult>(new Synology.Parameters.SynologyRequestParameters
{
Version = 2,
Additional = parameters,
});
}
/// <summary>
/// Enumerate files in a given folder
/// </summary>
[RequestMethod("list")]
public ResultData ListFiles()
{
throw new NotImplementedException();
}
[RequestMethod("getinfo")]
public ResultData GetFileInfo()
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# |
ce5698ef61f57467eeed180662e45ea92e526dde | Update AssemblyInfo.cs to consider compilation agsinst NETSTANDARD1_3 as a friend assembly | aaubry/YamlDotNet,aaubry/YamlDotNet,aaubry/YamlDotNet | YamlDotNet/Properties/AssemblyInfo.cs | YamlDotNet/Properties/AssemblyInfo.cs | // This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// 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.
#if !UNITY
using System.Reflection;
using System.Runtime.InteropServices;
using System;
using System.Runtime.CompilerServices;
// 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("YamlDotNet")]
[assembly: AssemblyDescription("The YamlDotNet library.")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet")]
[assembly: AssemblyCopyright("Copyright (c) Antoine Aubry and contributors 2008, 2009, 2010, 2011, 2012, 2013, 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.0.1")]
[assembly: AssemblyFileVersion("0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0")]
[assembly: CLSCompliant(true)]
#if !SIGNED
#if NETSTANDARD1_3 || !PORTABLE
[assembly: InternalsVisibleTo("YamlDotNet.Test")]
#else
[assembly: InternalsVisibleTo("YamlDotNet.Test.Portable")]
#endif
#endif
#endif | // This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
// 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.
#if !UNITY
using System.Reflection;
using System.Runtime.InteropServices;
using System;
using System.Runtime.CompilerServices;
// 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("YamlDotNet")]
[assembly: AssemblyDescription("The YamlDotNet library.")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet")]
[assembly: AssemblyCopyright("Copyright (c) Antoine Aubry and contributors 2008, 2009, 2010, 2011, 2012, 2013, 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("0.0.1")]
[assembly: AssemblyFileVersion("0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0")]
[assembly: CLSCompliant(true)]
#if !SIGNED
#if PORTABLE
[assembly: InternalsVisibleTo("YamlDotNet.Test.Portable")]
#else
[assembly: InternalsVisibleTo("YamlDotNet.Test")]
#endif
#endif
#endif | mit | C# |
7e7d6b14a6331db71e9e574f480342eb391a10ad | Use official namespace (better for fallback) | FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp | AngleSharp/Foundation/TaskEx.cs | AngleSharp/Foundation/TaskEx.cs | namespace System.Threading.Tasks
{
using System.Collections.Generic;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
| namespace AngleSharp
{
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
| mit | C# |
ff4be93293956ce9a0705ede35fe41f7d46d880d | Switch default SubMenu back to splash | NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Scripts/Menu/GameMenu.cs | Assets/Scripts/Menu/GameMenu.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach to every menu animator
public class GameMenu : MonoBehaviour
{
public static SubMenu subMenu = SubMenu.Splash;
//public static SubMenu subMenu = SubMenu.Title; //Debug purposes
public static bool shifting;
public static SubMenu shiftingFrom;
private static GameMenu shiftOrigin;
public enum SubMenu
{
Splash = 0,
Title = 1,
Settings = 2,
Gamemode = 3,
Practice = 4,
PracticeSelect = 5,
Credits = 6,
Quit = 7
}
void Awake()
{
Cursor.visible = true;
shifting = (subMenu == SubMenu.Splash);
correctSubMenu();
setSubMenu((int)subMenu);
MenuAnimationUpdater updater = GetComponent<MenuAnimationUpdater>();
if (updater != null)
updater.updateAnimatorValues();
}
void correctSubMenu()
{
if (subMenu == SubMenu.PracticeSelect)
subMenu = SubMenu.Practice;
}
public void shift(int subMenu)
{
if (shiftOrigin == null)
shiftOrigin = this;
shiftingFrom = GameMenu.subMenu;
setSubMenu(subMenu);
shifting = true;
}
public void endShift()
{
if (shiftOrigin != this) //Shift cannot be ended by the same menu that starts it, this prevents early endShifts in reversible shift animations
{
shifting = false;
shiftOrigin = null;
}
}
void setSubMenu(int subMenu)
{
GameMenu.subMenu = (SubMenu)subMenu;
}
void setShifting(bool shifting)
{
GameMenu.shifting = shifting;
}
private void OnDestroy()
{
shifting = false;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Attach to every menu animator
public class GameMenu : MonoBehaviour
{
//public static SubMenu subMenu = SubMenu.Splash;
public static SubMenu subMenu = SubMenu.Title; //Debug purposes
public static bool shifting;
public static SubMenu shiftingFrom;
private static GameMenu shiftOrigin;
public enum SubMenu
{
Splash = 0,
Title = 1,
Settings = 2,
Gamemode = 3,
Practice = 4,
PracticeSelect = 5,
Credits = 6,
Quit = 7
}
void Awake()
{
Cursor.visible = true;
shifting = (subMenu == SubMenu.Splash);
correctSubMenu();
setSubMenu((int)subMenu);
MenuAnimationUpdater updater = GetComponent<MenuAnimationUpdater>();
if (updater != null)
updater.updateAnimatorValues();
}
void correctSubMenu()
{
if (subMenu == SubMenu.PracticeSelect)
subMenu = SubMenu.Practice;
}
public void shift(int subMenu)
{
if (shiftOrigin == null)
shiftOrigin = this;
shiftingFrom = GameMenu.subMenu;
setSubMenu(subMenu);
shifting = true;
}
public void endShift()
{
if (shiftOrigin != this) //Shift cannot be ended by the same menu that starts it, this prevents early endShifts in reversible shift animations
{
shifting = false;
shiftOrigin = null;
}
}
void setSubMenu(int subMenu)
{
GameMenu.subMenu = (SubMenu)subMenu;
}
void setShifting(bool shifting)
{
GameMenu.shifting = shifting;
}
private void OnDestroy()
{
shifting = false;
}
}
| mit | C# |
f4c279a59aea128e1e9ee3d277bddb8a3bd769a9 | Remove incorrect test case | charvey/CasinoStrats | src/CasinoStrats.Core.Tests/PlayerTest.cs | src/CasinoStrats.Core.Tests/PlayerTest.cs | using System;
using Xunit;
namespace CasinoStrats.Core.Tests
{
public class PlayerTest
{
[Theory]
[InlineData(0)]
[InlineData(2.5)]
[InlineData(5)]
public void TryDeduct_EnoughMoney(decimal amount)
{
var player = new Player(5);
var result = player.TryDeduct(amount);
Assert.True(result);
}
[Fact]
public void TryDeduct_NotEnoughMoney()
{
var player = new Player(5);
var result = player.TryDeduct(5.01m);
Assert.False(result);
}
[Theory]
[InlineData(-2.5)]
[InlineData(-5)]
public void TryDeduct_InvalidDeduction(decimal amount)
{
var player = new Player(5);
Assert.Throws<ArgumentException>(() => player.TryDeduct(amount));
}
}
}
| using Xunit;
namespace CasinoStrats.Core.Tests
{
public class PlayerTest
{
[Theory]
[InlineData(0)]
[InlineData(2.5)]
[InlineData(5)]
public void TryDeduct_EnoughMoney(decimal amount)
{
var player = new Player(5);
var result = player.TryDeduct(amount);
Assert.True(result);
}
[Fact]
public void TryDeduct_NotEnoughMoney()
{
var player = new Player(5);
var result = player.TryDeduct(5.01m);
Assert.False(result);
}
[Theory]
[InlineData(-0)]
[InlineData(-2.5)]
[InlineData(-5)]
public void TryDeduct_InvalidDeduction(decimal amount)
{
var player = new Player(5);
var result = player.TryDeduct(amount);
Assert.True(result);
}
}
}
| mit | C# |
24c22f8408ad407065dc09c560a7b5fd9b81a733 | Update FrancisSetash.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/FrancisSetash.cs | src/Firehose.Web/Authors/FrancisSetash.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class FrancisSetash : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Francis";
public string LastName => "Setash";
public string ShortBioOrTagLine => "Infrastructure and DevOps Engineer. Lots of working with Chef, and PowerShell DSC";
public string StateOrRegion => "Arnold, MD";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "";
public string GravatarHash => "0959b63fb022ccbc7eb47ad472ed5dad";
public Uri WebSite => new Uri("https://i-py.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://i-py.com/feed.xml"); }
}
public string GitHubHandle => "walked";
public bool Filter(SyndicationItem item)
{
return item.Title.Text.ToLowerInvariant().Contains("powershell");
}
public string FeedLanguageCode => "en";
public GeoPosition Position => new GeoPosition(39.0589050,-76.49100906);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class FrancisSetash : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Francis";
public string LastName => "Setash";
public string ShortBioOrTagLine => "Infrastructure and DevOps Engineer. Lots of working with Chef, and PowerShell DSC";
public string StateOrRegion => "Arnold, MD";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "";
public string GravatarHash => "";
public Uri WebSite => new Uri("https://i-py.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://i-py.com/feed.xml"); }
}
public string GitHubHandle => "walked";
public bool Filter(SyndicationItem item)
{
return item.Title.Text.ToLowerInvariant().Contains("powershell");
}
public string FeedLanguageCode => "en";
public GeoPosition Position => new GeoPosition(39.0589050,-76.49100906);
}
}
| mit | C# |
5b453daa4583924d6420aea35b7ccf974255f861 | Use record for PluginFormModel | nikeee/HolzShots | src/HolzShots.Windows/Forms/PluginForm.cs | src/HolzShots.Windows/Forms/PluginForm.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using HolzShots.Composition;
using HolzShots.IO;
using HolzShots.Windows.Forms.Controls;
namespace HolzShots.Windows.Forms
{
public partial class PluginForm : Form
{
private readonly PluginFormModel _model;
public PluginForm(PluginFormModel model)
{
InitializeComponent();
Debug.Assert(model != null);
SuspendLayout();
_model = model;
InitializeModel();
ResumeLayout(true);
}
private void InitializeModel()
{
var items = _model.Plugins.Select(p => new PluginItem(p)).ToArray();
PluginPanel.Controls.AddRange(items);
}
private void CloseButton_Click(object sender, EventArgs e) => Close();
private void OpenPluginsDirectoryLabel_LinkClicked(object sender, EventArgs e)
{
HolzShotsPaths.OpenFolderInExplorer(_model.PluginDirectory);
}
}
public record PluginFormModel(IReadOnlyList<IPluginMetadata> Plugins, string PluginDirectory);
}
| using System.Diagnostics;
using HolzShots.Composition;
using HolzShots.IO;
using HolzShots.Windows.Forms.Controls;
namespace HolzShots.Windows.Forms
{
public partial class PluginForm : Form
{
private readonly PluginFormModel _model;
public PluginForm(PluginFormModel model)
{
InitializeComponent();
Debug.Assert(model != null);
SuspendLayout();
_model = model;
InitializeModel();
ResumeLayout(true);
}
private void InitializeModel()
{
var items = _model.Plugins.Select(p => new PluginItem(p)).ToArray();
PluginPanel.Controls.AddRange(items);
}
private void CloseButton_Click(object sender, EventArgs e) => Close();
private void OpenPluginsDirectoryLabel_LinkClicked(object sender, EventArgs e)
{
HolzShotsPaths.OpenFolderInExplorer(_model.PluginDirectory);
}
}
public class PluginFormModel
{
public IReadOnlyList<IPluginMetadata> Plugins { get; }
public string PluginDirectory { get; }
public PluginFormModel(IReadOnlyList<IPluginMetadata> plugins, string pluginDirectory)
{
Plugins = plugins ?? throw new ArgumentNullException(nameof(plugins));
PluginDirectory = pluginDirectory ?? throw new ArgumentNullException(nameof(pluginDirectory));
}
}
}
| agpl-3.0 | C# |
3e650595fb511cc81b1a5fe3dc1234196bcee85a | fix system dynamic library reference | Eskat0n/linqtowindows | src/LinqToWindows/Windows/Types/Window.cs | src/LinqToWindows/Windows/Types/Window.cs | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Muyou.LinqToWindows.Extensions;
using Muyou.LinqToWindows.Input.Keyboard;
using Muyou.LinqToWindows.Menus;
using Muyou.LinqToWindows.Windows.NativeTypes;
namespace Muyou.LinqToWindows.Windows.Types
{
public class Window
{
private readonly DefaultCommandCreator _commandCreator = new DefaultCommandCreator();
protected readonly IntPtr Handle;
public IEnumerable<Window> ChildWindows { get; private set; }
public Menu Menu { get; private set; }
public string ClassName { get; private set; }
public string Text { get; protected set; }
public Window(IntPtr handle, string className, string text, IEnumerable<Window> childWindows = null, Menu menu = null)
{
Handle = handle;
ClassName = className;
Text = text;
ChildWindows = childWindows;
Menu = menu;
}
public bool SetFocus()
{
return SetFocus(Handle) != IntPtr.Zero;
}
public void SetActive()
{
if (GetActiveWindow() != Handle)
SetActiveWindow(Handle);
}
public void SetForeground()
{
if (GetForegroundWindow() != Handle)
SetForegroundWindow(Handle);
}
public void SetText(string text)
{
SendMessage(Handle, WindowMessages.SetText, IntPtr.Zero, text);
Text = text;
}
public void Close()
{
SendMessage(Handle, WindowMessages.Close, IntPtr.Zero, IntPtr.Zero);
}
public void PressKey(string sequence)
{
SetForeground();
_commandCreator.Create(sequence).ForEach(x => x.Execute());
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint messageCode, IntPtr wParam, string lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint messageCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetFocus();
[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetActiveWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
}
} | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Muyou.LinqToWindows.Extensions;
using Muyou.LinqToWindows.Input.Keyboard;
using Muyou.LinqToWindows.Menus;
using Muyou.LinqToWindows.Windows.NativeTypes;
namespace Muyou.LinqToWindows.Windows.Types
{
public class Window
{
private readonly DefaultCommandCreator _commandCreator = new DefaultCommandCreator();
protected readonly IntPtr Handle;
public IEnumerable<Window> ChildWindows { get; private set; }
public Menu Menu { get; private set; }
public string ClassName { get; private set; }
public string Text { get; protected set; }
public Window(IntPtr handle, string className, string text, IEnumerable<Window> childWindows = null, Menu menu = null)
{
Handle = handle;
ClassName = className;
Text = text;
ChildWindows = childWindows;
Menu = menu;
}
public bool SetFocus()
{
return SetFocus(Handle) != IntPtr.Zero;
}
public void SetActive()
{
if (GetActiveWindow() != Handle)
SetActiveWindow(Handle);
}
public void SetForeground()
{
if (GetForegroundWindow() != Handle)
SetForegroundWindow(Handle);
}
public void SetText(string text)
{
SendMessage(Handle, WindowMessages.SetText, IntPtr.Zero, text);
Text = text;
}
public void Close()
{
SendMessage(Handle, WindowMessages.Close, IntPtr.Zero, IntPtr.Zero);
}
public void PressKey(string sequence)
{
SetForeground();
_commandCreator.Create(sequence).ForEach(x => x.Execute());
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint messageCode, IntPtr wParam, string lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint messageCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr GetFocus();
[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr GetActiveWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
}
} | mit | C# |
9e3ae540480b4b13ad8d252c3974687d3b79e21c | support doublequotes within generated values. | nortal/AssemblyVersioning | AssemblyVersioning/AssemblyInfoFileCreator.cs | AssemblyVersioning/AssemblyInfoFileCreator.cs | /*
Copyright 2013 Imre Pühvel, AS Nortal
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.
This file is from project https://github.com/NortalLTD/AssemblyVersioning, Nortal.Utilities.AssemblyVersioning, file 'AssemblyInfoFileCreator.cs'.
*/
using System;
namespace Nortal.Utilities.AssemblyVersioning
{
public static class AssemblyInfoFileCreator
{
internal static String GetHeader(VersionGenerationContext context)
{
return GetNamespaceSection() + Environment.NewLine
+ GetHeaderComments(context) + Environment.NewLine;
}
private static String GetNamespaceSection()
{
return "using System.Reflection;";
}
private static String GetHeaderComments(VersionGenerationContext context)
{
return @"
// NB! this file is automatically generated. All manual changes will be lost on build.
// Check ~/_tools/Nortal.Utilities.AssemblyVersioning.props file for other available algorithms and supported attributes.
// Generated based on assembly version: " + context.BaseVersion;
}
public static String GenerateAttributeRow<TAttribute>(IVersionGenerator generator, VersionGenerationContext context)
where TAttribute : Attribute
{
if (generator == null) { throw new ArgumentNullException("generator"); }
String version = generator.GenerateVersionInfoFrom(context);
return GenerateAttributeRow<TAttribute>(generator.GetType().Name, version);
}
public static String GenerateAttributeRow<TAttribute>(String generator, String version)
where TAttribute : Attribute
{
if (version == null) { return null; }
const String pattern = @"[assembly: {0}(@""{1}"")] // algorithm: {2}
";
String attributeName = typeof(TAttribute).Name
.Replace(typeof(Attribute).Name, ""); //without Attribute at end.
return String.Format(pattern,
attributeName,
version.Replace(@"""", @""""""), // support version content with double-quotes.
generator);
}
}
}
| /*
Copyright 2013 Imre Pühvel, AS Nortal
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.
This file is from project https://github.com/NortalLTD/AssemblyVersioning, Nortal.Utilities.AssemblyVersioning, file 'AssemblyInfoFileCreator.cs'.
*/
using System;
namespace Nortal.Utilities.AssemblyVersioning
{
public static class AssemblyInfoFileCreator
{
internal static String GetHeader(VersionGenerationContext context)
{
return GetNamespaceSection() + Environment.NewLine
+ GetHeaderComments(context) + Environment.NewLine;
}
private static String GetNamespaceSection()
{
return "using System.Reflection;";
}
private static String GetHeaderComments(VersionGenerationContext context)
{
return @"
// NB! this file is automatically generated. All manual changes will be lost on build.
// Check ~/_tools/Nortal.Utilities.AssemblyVersioning.props file for other available algorithms and supported attributes.
// Generated based on assembly version: " + context.BaseVersion;
}
public static String GenerateAttributeRow<TAttribute>(IVersionGenerator generator, VersionGenerationContext context)
where TAttribute : Attribute
{
if (generator == null) { throw new ArgumentNullException("generator"); }
String version = generator.GenerateVersionInfoFrom(context);
return GenerateAttributeRow<TAttribute>(generator.GetType().Name, version);
}
public static String GenerateAttributeRow<TAttribute>(String generator, String version)
where TAttribute : Attribute
{
if (version == null) { return null; }
const String pattern = @"[assembly: {0}(""{1}"")] // algorithm: {2}
";
String attributeName = typeof(TAttribute).Name
.Replace(typeof(Attribute).Name, ""); //without Attribute at end.
return String.Format(pattern,
attributeName,
version,
generator);
}
}
}
| apache-2.0 | C# |
6ab86212e3150cfed1ae1b1a6ffef027ff0c3b09 | Remove unit service reference to ignore for reporting | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Services/UnitService.cs | Battery-Commander.Web/Services/UnitService.cs | using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class UnitService
{
public static async Task<Unit> Get(Database db, int unitId)
{
return (await List(db)).Single(unit => unit.Id == unitId);
}
public static async Task<IEnumerable<Unit>> List(Database db)
{
return
await db
.Units
.Include(unit => unit.Vehicles)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.ABCPs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.APFTs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.SSDSnapshots)
.OrderBy(unit => unit.Name)
.ToListAsync();
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class UnitService
{
public static async Task<Unit> Get(Database db, int unitId)
{
return (await List(db, includeIgnored: true)).Single(unit => unit.Id == unitId);
}
public static async Task<IEnumerable<Unit>> List(Database db, Boolean includeIgnored = false)
{
return
await db
.Units
.Include(unit => unit.Vehicles)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.ABCPs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.APFTs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.SSDSnapshots)
.Where(unit => includeIgnored || !unit.IgnoreForReports)
.OrderBy(unit => unit.Name)
.ToListAsync();
}
}
} | mit | C# |
3836d446f7c112777f2b6a0c24f52463ed3b8f35 | remove the un-used collection within Topic | eklavyamirani/DTML.EduBot,eklavyamirani/DTML.EduBot | DTML.EduBot/LessonPlan/Topic.cs | DTML.EduBot/LessonPlan/Topic.cs | namespace DTML.EduBot.LessonPlan
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
[Serializable]
public class Topic
{
private ICollection<string> answerOptions = new List<string>();
[JsonProperty("question", Required = Required.Always)]
public string Question { get; set; }
[JsonProperty("image_url", Required = Required.Always)]
public string ImageUrl { get; set; }
[JsonProperty("answer_options", Required = Required.Always)]
public ICollection<string> AnswerOptions
{
get { return this.answerOptions; }
}
[JsonProperty("correct_answer", Required = Required.Always)]
public string CorrectAnswer { get; set; }
[DefaultValue("Correct! Now, can you type the word?")]
[JsonProperty("correct_answer_bot_response", DefaultValueHandling = DefaultValueHandling.Populate)]
public string CorrectAnswerBotResponse { get; set; }
[DefaultValue("Sorry, incorrect, try again")]
[JsonProperty("wrong_answer_bot_response", DefaultValueHandling = DefaultValueHandling.Populate)]
public string WrongAnswerBotResponse { get; set; }
[DefaultValue("Good work! Here is how you say it, Repeat after me.")]
[JsonProperty("pronounciation_phrase", DefaultValueHandling = DefaultValueHandling.Populate)]
public string PronounciationPhrase { get; set; }
[DefaultValue("I got it")]
[JsonProperty("next_topic_phrase", DefaultValueHandling = DefaultValueHandling.Populate)]
public string NextTopicPhrase { get; set; }
[DefaultValue("Say it again")]
[JsonProperty("stay_on_current_topic_phrase", DefaultValueHandling = DefaultValueHandling.Populate)]
public string StayOnCurrentTopicPhrase { get; set; }
}
} | namespace DTML.EduBot.LessonPlan
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
[Serializable]
public class Topic
{
private ICollection<string> answerOptions = new List<string>();
private ICollection<string> wrapUpPhrases = new List<string>();
[JsonProperty("question", Required = Required.Always)]
public string Question { get; set; }
[JsonProperty("image_url", Required = Required.Always)]
public string ImageUrl { get; set; }
[JsonProperty("answer_options", Required = Required.Always)]
public ICollection<string> AnswerOptions
{
get { return this.answerOptions; }
}
[JsonProperty("correct_answer", Required = Required.Always)]
public string CorrectAnswer { get; set; }
[DefaultValue("Correct! Now, can you type the word?")]
[JsonProperty("correct_answer_bot_response", DefaultValueHandling = DefaultValueHandling.Populate)]
public string CorrectAnswerBotResponse { get; set; }
[DefaultValue("Sorry, incorrect, try again")]
[JsonProperty("wrong_answer_bot_response", DefaultValueHandling = DefaultValueHandling.Populate)]
public string WrongAnswerBotResponse { get; set; }
[DefaultValue("Good work! Here is how you say it, Repeat after me.")]
[JsonProperty("pronounciation_phrase", DefaultValueHandling = DefaultValueHandling.Populate)]
public string PronounciationPhrase { get; set; }
[DefaultValue("I got it")]
[JsonProperty("next_topic_phrase", DefaultValueHandling = DefaultValueHandling.Populate)]
public string NextTopicPhrase { get; set; }
[DefaultValue("Say it again")]
[JsonProperty("stay_on_current_topic_phrase", DefaultValueHandling = DefaultValueHandling.Populate)]
public string StayOnCurrentTopicPhrase { get; set; }
}
} | mit | C# |
fcaeb25d7efbdd512264fe0287753b473f98c68c | remove redundant using | bau-build/bau-nuget,modulexcite/bau-nuget,bau-build/bau-nuget,modulexcite/bau-nuget | src/Bau.NuGet/Plugin.cs | src/Bau.NuGet/Plugin.cs | // <copyright file="Plugin.cs" company="Bau contributors">
// Copyright (c) Bau contributors. ([email protected])
// </copyright>
namespace BauNuGet
{
using BauCore;
public static class Plugin
{
public static ITaskBuilder<Restore> NuGetRestore(this ITaskBuilder builder, string name = null)
{
return new TaskBuilder<Restore>(builder, name);
}
public static ITaskBuilder<Pack> NuGetPack(this ITaskBuilder builder, string name = null)
{
return new TaskBuilder<Pack>(builder, name);
}
public static ITaskBuilder<Push> NuGetPush(this ITaskBuilder builder, string name = null)
{
return new TaskBuilder<Push>(builder, name);
}
}
}
| // <copyright file="Plugin.cs" company="Bau contributors">
// Copyright (c) Bau contributors. ([email protected])
// </copyright>
namespace BauNuGet
{
using System;
using BauCore;
public static class Plugin
{
public static ITaskBuilder<Restore> NuGetRestore(this ITaskBuilder builder, string name = null)
{
return new TaskBuilder<Restore>(builder, name);
}
public static ITaskBuilder<Pack> NuGetPack(this ITaskBuilder builder, string name = null)
{
return new TaskBuilder<Pack>(builder, name);
}
public static ITaskBuilder<Push> NuGetPush(this ITaskBuilder builder, string name = null)
{
return new TaskBuilder<Push>(builder, name);
}
}
}
| mit | C# |
1f7582b57d63e5fcbea2370f25daa2b1bf1869f4 | Fix binding validation which disallow publishing to HTTPS addresses. | campersau/NuGetPackageExplorer,dsplaisted/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,BreeeZe/NuGetPackageExplorer | PackageExplorer/PublishUrlValidationRule.cs | PackageExplorer/PublishUrlValidationRule.cs | using System;
using System.Windows.Controls;
namespace PackageExplorer {
public class PublishUrlValidationRule : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
string stringValue = (string)value;
Uri url;
if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) {
return ValidationResult.ValidResult;
}
else {
return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
}
}
else {
return new ValidationResult(false, "Invalid publish url.");
}
}
}
} | using System;
using System.Windows.Controls;
namespace PackageExplorer {
public class PublishUrlValidationRule : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
string stringValue = (string)value;
Uri url;
if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)) {
return ValidationResult.ValidResult;
}
else {
return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
}
}
else {
return new ValidationResult(false, "Invalid publish url.");
}
}
}
}
| mit | C# |
fab31e6cb3a1a1501f6a38082716e713ddf890b9 | Add "Consistency" report tag | Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector | KenticoInspector.Core/Constants/ReportTags.cs | KenticoInspector.Core/Constants/ReportTags.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace KenticoInspector.Core.Constants
{
public class ReportTags
{
public const string Database = "Database";
public const string EventLog = "Event Log";
public const string Health = "Health";
public const string Consistency = "Consistency";
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace KenticoInspector.Core.Constants
{
public class ReportTags
{
public const string Database = "Database";
public const string EventLog = "Event Log";
public const string Health = "Health";
}
}
| mit | C# |
721b8f3e190d353d39f1cb3ec512712d102741cc | increase version | tinohager/Nager.PublicSuffix,tinohager/Nager.PublicSuffix,tinohager/Nager.PublicSuffix | Nager.PublicSuffix/Properties/AssemblyInfo.cs | Nager.PublicSuffix/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Nager.PublicSuffix")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Nager.PublicSuffix")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5b564bba-82bd-4031-9cee-7253527e881a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]
| 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("Nager.PublicSuffix")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Nager.PublicSuffix")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5b564bba-82bd-4031-9cee-7253527e881a")]
// 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.*")]
| mit | C# |
7a46b2fd1b9622d1886558f878a349b119d9c132 | Improve user profile view | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Manage/Index.cshtml | BTCPayServer/Views/Manage/Index.cshtml | @model IndexViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.Index, "Profile");
}
<partial name="_StatusMessage" />
@if (!this.ViewContext.ModelState.IsValid)
{
<div class="row">
<div class="col-md-6">
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</div>
}
<form method="post">
<div class="form-row">
<div class="col-md-6 mb-3">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="col-md-6 mb-3 d-flex align-items-end">
@if(Model.IsEmailConfirmed)
{
<span class="badge badge-success p-2 my-1">
<span class="fa fa-check"></span>
confirmed
</span>
}
else
{
<button asp-action="SendVerificationEmail" class="btn btn-secondary">Send verification email</button>
}
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| @model IndexViewModel
@{
ViewData.SetActivePageAndTitle(ManageNavPages.Index, "Profile");
}
<partial name="_StatusMessage" />
<div class="row">
<div class="col-md-6">
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<form method="post">
<div class="form-group">
<label asp-for="Username"></label>
<input asp-for="Username" class="form-control" disabled />
</div>
<div class="form-group">
<label asp-for="Email"></label>
@if(Model.IsEmailConfirmed)
{
<div class="input-group">
<input asp-for="Email" class="form-control" />
<span class="input-group-addon" aria-hidden="true"><span class="fa fa-check text-success"></span></span>
</div>
}
else
{
<input asp-for="Email" class="form-control" />
<button asp-action="SendVerificationEmail" class="btn btn-link">Send verification email</button>
}
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
| mit | C# |
ea1dc13449e2e2b2dd82b17e2712fd76edaa43e2 | Add Testing channel to UpdateSettings (#1211) | sillsdev/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso | SIL.Core.Desktop/Settings/UpdateSettings.cs | SIL.Core.Desktop/Settings/UpdateSettings.cs | using System;
namespace SIL.Settings
{
/// <summary>
/// Settings for checking for, downloading, and installing updates
/// </summary>
[Serializable]
public class UpdateSettings
{
public enum Channels
{
/// <summary>
/// Get the latest stable release (recommended for most users)
/// </summary>
Stable,
/// <summary>
/// Get the latest Beta (recommended for users who want the latest features and don't mind a few bugs)
/// </summary>
Beta,
/// <summary>
/// Get the latest Alpha (recommended only if the developers invite you)
/// </summary>
Alpha,
/// <summary>
/// Get the latest nightly builds (not recommended)
/// </summary>
/// <remarks>This option should not be made available to users</remarks>
Nightly,
/// <summary>
/// Get specific testing builds (not recommended)
/// </summary>
/// <remarks>
/// This option should not be made available to users
/// This option is intended for very specific testing builds.
/// e.g Testing that appropriate warnings are presented before updating if a data model has changed.
/// </remarks>
Testing
}
public enum Behaviors
{
/// <summary>
/// Download and install the latest updates
/// </summary>
Install,
/// <summary>
/// Download the latest updates and prompt to install
/// </summary>
Download,
/// <summary>
/// Notify the user when updates are available and prompt to download
/// </summary>
Notify,
/// <summary>
/// Do not check for updates
/// </summary>
DoNotCheck
}
/// <summary>
/// Which channel to check for updates
/// </summary>
public Channels Channel { get; set; }
/// <summary>
/// What to do when an update is available
/// </summary>
public Behaviors Behavior { get; set; }
/// <summary>
/// Create a new UpdateSettings with defaults: Channel: Stable; Behavior: Download
/// </summary>
public UpdateSettings()
{
Channel = Channels.Stable;
Behavior = Behaviors.Download;
}
}
} | using System;
namespace SIL.Settings
{
/// <summary>
/// Settings for checking for, downloading, and installing updates
/// </summary>
[Serializable]
public class UpdateSettings
{
public enum Channels
{
/// <summary>
/// Get the latest stable release (recommended for most users)
/// </summary>
Stable,
/// <summary>
/// Get the latest Beta (recommended for users who want the latest features and don't mind a few bugs)
/// </summary>
Beta,
/// <summary>
/// Get the latest Alpha (recommended only if the developers invite you)
/// </summary>
Alpha,
/// <summary>
/// Get the latest nightly builds (not recommended)
/// </summary>
/// <remarks>This option should not be made available to users</remarks>
Nightly
}
public enum Behaviors
{
/// <summary>
/// Download and install the latest updates
/// </summary>
Install,
/// <summary>
/// Download the latest updates and prompt to install
/// </summary>
Download,
/// <summary>
/// Notify the user when updates are available and prompt to download
/// </summary>
Notify,
/// <summary>
/// Do not check for updates
/// </summary>
DoNotCheck
}
/// <summary>
/// Which channel to check for updates
/// </summary>
public Channels Channel { get; set; }
/// <summary>
/// What to do when an update is available
/// </summary>
public Behaviors Behavior { get; set; }
/// <summary>
/// Create a new UpdateSettings with defaults: Channel: Stable; Behavior: Download
/// </summary>
public UpdateSettings()
{
Channel = Channels.Stable;
Behavior = Behaviors.Download;
}
}
} | mit | C# |
3f2a053a9d34ce8aac23b9e075e9115e4ffb6639 | Stop using ConcurrentBag | KodamaSakuno/Library | Sakuno.Base/PropertyChangedEventListener.cs | Sakuno.Base/PropertyChangedEventListener.cs | using System;
using System.Collections.Concurrent;
using System.ComponentModel;
namespace Sakuno
{
public sealed class PropertyChangedEventListener : EventListener<PropertyChangedEventHandler>
{
static ConcurrentDictionary<INotifyPropertyChanged, PropertyChangedEventListener> r_Listeners = new ConcurrentDictionary<INotifyPropertyChanged, PropertyChangedEventListener>();
WeakReference<INotifyPropertyChanged> r_Source;
ConcurrentDictionary<string, ConcurrentDictionary<PropertyChangedEventHandler, object>> r_HandlerDictionary = new ConcurrentDictionary<string, ConcurrentDictionary<PropertyChangedEventHandler, object>>();
public PropertyChangedEventListener(INotifyPropertyChanged rpSource)
{
if (rpSource == null)
throw new ArgumentNullException(nameof(rpSource));
r_Source = new WeakReference<INotifyPropertyChanged>(rpSource);
Initialize(r => rpSource.PropertyChanged += r, r => rpSource.PropertyChanged -= r, (_, e) => RaiseHandler(e));
}
public static PropertyChangedEventListener FromSource(INotifyPropertyChanged rpSource) =>
r_Listeners.GetOrAdd(rpSource, r => new PropertyChangedEventListener(r));
public void Add(string rpPropertyName, PropertyChangedEventHandler rpHandler) =>
r_HandlerDictionary.GetOrAdd(rpPropertyName ?? string.Empty, _ => new ConcurrentDictionary<PropertyChangedEventHandler, object>()).TryAdd(rpHandler, null);
void RaiseHandler(PropertyChangedEventArgs e)
{
INotifyPropertyChanged rSource;
if (!r_Source.TryGetTarget(out rSource))
return;
ConcurrentDictionary<PropertyChangedEventHandler, object> rHandlers;
if (!r_HandlerDictionary.TryGetValue(e.PropertyName ?? string.Empty, out rHandlers))
return;
foreach (var rHandler in rHandlers.Keys)
rHandler(rSource, e);
}
protected override void DisposeManagedResources()
{
INotifyPropertyChanged rSource;
if (r_Source.TryGetTarget(out rSource))
{
PropertyChangedEventListener rListener;
r_Listeners.TryRemove(rSource, out rListener);
}
r_HandlerDictionary.Clear();
base.DisposeManagedResources();
}
}
}
| using System;
using System.Collections.Concurrent;
using System.ComponentModel;
namespace Sakuno
{
public sealed class PropertyChangedEventListener : EventListener<PropertyChangedEventHandler>
{
static ConcurrentDictionary<INotifyPropertyChanged, PropertyChangedEventListener> r_Listeners = new ConcurrentDictionary<INotifyPropertyChanged, PropertyChangedEventListener>();
WeakReference<INotifyPropertyChanged> r_Source;
ConcurrentDictionary<string, ConcurrentBag<PropertyChangedEventHandler>> r_HandlerDictionary = new ConcurrentDictionary<string, ConcurrentBag<PropertyChangedEventHandler>>();
public PropertyChangedEventListener(INotifyPropertyChanged rpSource)
{
if (rpSource == null)
throw new ArgumentNullException(nameof(rpSource));
r_Source = new WeakReference<INotifyPropertyChanged>(rpSource);
Initialize(r => rpSource.PropertyChanged += r, r => rpSource.PropertyChanged -= r, (_, e) => RaiseHandler(e));
}
public static PropertyChangedEventListener FromSource(INotifyPropertyChanged rpSource)
{
return r_Listeners.GetOrAdd(rpSource, r => new PropertyChangedEventListener(r));
}
public void Add(string rpPropertyName, PropertyChangedEventHandler rpHandler)
{
r_HandlerDictionary.GetOrAdd(rpPropertyName ?? string.Empty, _ => new ConcurrentBag<PropertyChangedEventHandler>()).Add(rpHandler);
}
void RaiseHandler(PropertyChangedEventArgs e)
{
INotifyPropertyChanged rSource;
if (!r_Source.TryGetTarget(out rSource))
return;
ConcurrentBag<PropertyChangedEventHandler> rHandlerList;
if (!r_HandlerDictionary.TryGetValue(e.PropertyName ?? string.Empty, out rHandlerList))
return;
foreach (var rHandler in rHandlerList)
rHandler(rSource, e);
}
protected override void DisposeManagedResources()
{
INotifyPropertyChanged rSource;
if (r_Source.TryGetTarget(out rSource))
{
PropertyChangedEventListener rListener;
r_Listeners.TryRemove(rSource, out rListener);
}
r_HandlerDictionary.Clear();
base.DisposeManagedResources();
}
}
}
| mit | C# |
85a3f508ede8448066f910f53da47c608db0d976 | Remove debug message | knexer/Chinese-Rooms-what-do-they-know-do-they-know-things-lets-find-out | Assets/DraggableVertexMachine.cs | Assets/DraggableVertexMachine.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DraggableVertexMachine : MonoBehaviour
{
public float distanceThreshold = Mathf.Infinity;
private MachineGrid grid;
// Use this for initialization
void Start()
{
grid = FindObjectOfType<MachineGrid>();
}
private void OnMouseDrag()
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
Vector3 closestVertexPosition = grid.getClosestVertex(transform.position).transform.position;
if (Vector2.Distance(transform.position, closestVertexPosition) < distanceThreshold)
{
transform.position = closestVertexPosition;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DraggableVertexMachine : MonoBehaviour
{
public float distanceThreshold = Mathf.Infinity;
private MachineGrid grid;
// Use this for initialization
void Start()
{
grid = FindObjectOfType<MachineGrid>();
}
private void OnMouseDrag()
{
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = new Vector3(transform.position.x, transform.position.y, 0);
Vector3 closestVertexPosition = grid.getClosestVertex(transform.position).transform.position;
if (Vector2.Distance(transform.position, closestVertexPosition) < distanceThreshold)
{
transform.position = closestVertexPosition;
}
Debug.Log("FUCK");
}
}
| mit | C# |
162058580be2faee93db269c60694778bc07e1a2 | Backup directory implementation | gniriki/Sync.Net | src/Sync.Net/SyncNet.cs | src/Sync.Net/SyncNet.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sync.Net
{
public class SyncNet
{
public void Backup(IFileObject file, IDirectoryObject targetDirectory)
{
if (!targetDirectory.ContainsFile(file.Name))
{
targetDirectory.CreateFile(file.Name);
}
IFileObject targetFile = targetDirectory.GetFile(file.Name);
using (var stream = file.GetStream())
{
using (var destination = targetFile.GetStream())
{
stream.CopyTo(destination);
}
}
}
public void Backup(IDirectoryObject sourceDirectory, IDirectoryObject targetDirectory)
{
var files = sourceDirectory.GetFiles();
foreach (var fileObject in files)
{
Backup(fileObject, targetDirectory);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sync.Net
{
public class SyncNet
{
public void Backup(IFileObject file, IDirectoryObject targetDirectory)
{
if (!targetDirectory.ContainsFile(file.Name))
{
targetDirectory.CreateFile(file.Name);
}
IFileObject targetFile = targetDirectory.GetFile(file.Name);
using (var stream = file.GetStream())
{
using (var destination = targetFile.GetStream())
{
stream.CopyTo(destination);
}
}
}
public void Backup(IDirectoryObject sourceDirectory, IDirectoryObject targetDirectory)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
1c9071900690d450f2b3cb1671627561b33d763d | Change default behavior of ToAsyncEnumerable() extension method: 'runSynchronously' is set to True by default | tyrotoxin/AsyncEnumerable | IEnumerableExtensions.cs | IEnumerableExtensions.cs | using System.Collections.Async;
using System.Linq;
namespace System.Collections
{
/// <summary>
/// Converts generic IEnumerable to IAsyncEnumerable
/// </summary>
[ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)]
public static class IEnumerableExtensions
{
/// <summary>
/// Converts IEnumerable to IAsyncEnumerable
/// </summary>
/// <param name="enumerable">The instance of IEnumerable to convert</param>
/// <param name="runSynchronously">If True the enumeration will be performed on the same thread, otherwise the MoveNext will be executed on a separate thread with Task.Run method</param>
/// <returns>Returns an instance of IAsyncEnumerable implementation</returns>
public static IAsyncEnumerable ToAsyncEnumerable(this IEnumerable enumerable, bool runSynchronously = true)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
return enumerable as IAsyncEnumerable ?? new AsyncEnumerableWrapper<object>(enumerable.Cast<object>(), runSynchronously);
}
}
}
namespace System.Collections.Generic
{
/// <summary>
/// Converts generic IEnumerable to IAsyncEnumerable
/// </summary>
[ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)]
public static class IEnumerableExtensions
{
/// <summary>
/// Converts generic IEnumerable to IAsyncEnumerable
/// </summary>
/// <typeparam name="T">The element type</typeparam>
/// <param name="enumerable">The instance of IEnumerable to convert</param>
/// <param name="runSynchronously">If True the enumeration will be performed on the same thread, otherwise the MoveNext will be executed on a separate thread with Task.Run method</param>
/// <returns>Returns an instance of IAsyncEnumerable implementation</returns>
public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> enumerable, bool runSynchronously = true)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
return enumerable as IAsyncEnumerable<T> ?? new AsyncEnumerableWrapper<T>(enumerable, runSynchronously);
}
}
}
| using System.Collections.Async;
using System.Linq;
namespace System.Collections
{
/// <summary>
/// Converts generic IEnumerable to IAsyncEnumerable
/// </summary>
[ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)]
public static class IEnumerableExtensions
{
/// <summary>
/// Converts IEnumerable to IAsyncEnumerable
/// </summary>
/// <param name="enumerable">The instance of IEnumerable to convert</param>
/// <param name="runSynchronously">If True the enumeration will be performed on the same thread, otherwise the MoveNext will be executed on a separate thread with Task.Run method</param>
/// <returns>Returns an instance of IAsyncEnumerable implementation</returns>
public static IAsyncEnumerable ToAsyncEnumerable(this IEnumerable enumerable, bool runSynchronously = false)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
return enumerable as IAsyncEnumerable ?? new AsyncEnumerableWrapper<object>(enumerable.Cast<object>(), runSynchronously);
}
}
}
namespace System.Collections.Generic
{
/// <summary>
/// Converts generic IEnumerable to IAsyncEnumerable
/// </summary>
[ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never)]
public static class IEnumerableExtensions
{
/// <summary>
/// Converts generic IEnumerable to IAsyncEnumerable
/// </summary>
/// <typeparam name="T">The element type</typeparam>
/// <param name="enumerable">The instance of IEnumerable to convert</param>
/// <param name="runSynchronously">If True the enumeration will be performed on the same thread, otherwise the MoveNext will be executed on a separate thread with Task.Run method</param>
/// <returns>Returns an instance of IAsyncEnumerable implementation</returns>
public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> enumerable, bool runSynchronously = false)
{
if (enumerable == null)
throw new ArgumentNullException(nameof(enumerable));
return enumerable as IAsyncEnumerable<T> ?? new AsyncEnumerableWrapper<T>(enumerable, runSynchronously);
}
}
}
| mit | C# |
9a087192053ef6d7b03d133f0674e2eeacb991e9 | Bump version to 1.0.1 | github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | common/SolutionInfo.cs | common/SolutionInfo.cs | #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
// this is for the AssemblyVersion and AssemblyVersion attributes, which can't handle alphanumerics
internal const string VersionForAssembly = "1.0.1";
// Actual real version
internal const string Version = "1.0.1";
}
}
| #pragma warning disable 436
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub for Unity")]
[assembly: AssemblyVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyFileVersion(System.AssemblyVersionInformation.VersionForAssembly)]
[assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)]
[assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)]
//Required for NSubstitute
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)]
//Required for Unity compilation
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)]
namespace System
{
internal static class AssemblyVersionInformation {
// this is for the AssemblyVersion and AssemblyVersion attributes, which can't handle alphanumerics
internal const string VersionForAssembly = "1.0.0";
// Actual real version
internal const string Version = "1.0.0";
}
}
| mit | C# |
d41c738ed23d44d80938abfa03079b548a8410ce | Update IOptions.cs | wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Core2D/Model/Containers/IOptions.cs | src/Core2D/Model/Containers/IOptions.cs | using Core2D.Path;
namespace Core2D.Containers
{
/// <summary>
/// Defines options interface.
/// </summary>
public interface IOptions : IObservableObject
{
/// <summary>
/// Gets or sets how grid snapping is handled.
/// </summary>
bool SnapToGrid { get; set; }
/// <summary>
/// Gets or sets how much grid X axis is snapped.
/// </summary>
double SnapX { get; set; }
/// <summary>
/// Gets or sets how much grid Y axis is snapped.
/// </summary>
double SnapY { get; set; }
/// <summary>
/// Gets or sets hit test threshold radius.
/// </summary>
double HitThreshold { get; set; }
/// <summary>
/// Gets or sets how selected shapes are moved.
/// </summary>
MoveMode MoveMode { get; set; }
/// <summary>
/// Gets or sets value indicating whether path/shape is stroked during creation.
/// </summary>
bool DefaultIsStroked { get; set; }
/// <summary>
/// Gets or sets value indicating whether path/shape is filled during creation.
/// </summary>
bool DefaultIsFilled { get; set; }
/// <summary>
/// Gets or sets value indicating whether path is closed during creation.
/// </summary>
bool DefaultIsClosed { get; set; }
/// <summary>
/// Gets or sets value indicating whether path segment is smooth join during creation.
/// </summary>
bool DefaultIsSmoothJoin { get; set; }
/// <summary>
/// Gets or sets value indicating path fill rule during creation.
/// </summary>
FillRule DefaultFillRule { get; set; }
/// <summary>
/// Gets or sets how point connection is handled.
/// </summary>
bool TryToConnect { get; set; }
}
}
| using Core2D.Path;
using Core2D.Shapes;
using Core2D.Style;
namespace Core2D.Containers
{
/// <summary>
/// Defines options interface.
/// </summary>
public interface IOptions
{
/// <summary>
/// Gets or sets how grid snapping is handled.
/// </summary>
bool SnapToGrid { get; set; }
/// <summary>
/// Gets or sets how much grid X axis is snapped.
/// </summary>
double SnapX { get; set; }
/// <summary>
/// Gets or sets how much grid Y axis is snapped.
/// </summary>
double SnapY { get; set; }
/// <summary>
/// Gets or sets hit test threshold radius.
/// </summary>
double HitThreshold { get; set; }
/// <summary>
/// Gets or sets how selected shapes are moved.
/// </summary>
MoveMode MoveMode { get; set; }
/// <summary>
/// Gets or sets value indicating whether path/shape is stroked during creation.
/// </summary>
bool DefaultIsStroked { get; set; }
/// <summary>
/// Gets or sets value indicating whether path/shape is filled during creation.
/// </summary>
bool DefaultIsFilled { get; set; }
/// <summary>
/// Gets or sets value indicating whether path is closed during creation.
/// </summary>
bool DefaultIsClosed { get; set; }
/// <summary>
/// Gets or sets value indicating whether path segment is smooth join during creation.
/// </summary>
bool DefaultIsSmoothJoin { get; set; }
/// <summary>
/// Gets or sets value indicating path fill rule during creation.
/// </summary>
FillRule DefaultFillRule { get; set; }
/// <summary>
/// Gets or sets how point connection is handled.
/// </summary>
bool TryToConnect { get; set; }
}
}
| mit | C# |
5a41f0fb01ca19519fd4f7b48df7e73574d844dc | Fix missing metadata attribute | x335/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp,x335/scriptsharp | src/Libraries/Node/Node.Core/IO/Path.cs | src/Libraries/Node/Node.Core/IO/Path.cs | // Path.cs
// Script#/Libraries/Node/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace NodeApi.IO {
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptDependency("path")]
[ScriptName("path")]
public static class Path {
[ScriptName("sep")]
public static string PathSeparator = null;
[ScriptName("dirname")]
public static string GetDirectoryName(string path) {
return null;
}
[ScriptName("extname")]
public static string GetExtension(string path) {
return null;
}
[ScriptName("basename")]
public static string GetName(string path) {
return null;
}
[ScriptName("basename")]
public static string GetName(string path, string extensionToStrip) {
return null;
}
public static string Join(params string[] pathParts) {
return null;
}
[ScriptName("relative")]
public static string MakeRelative(string from, string to) {
return null;
}
public static string Normalize(string path) {
return null;
}
public static string Resolve(string from, string to) {
return null;
}
}
}
| // Path.cs
// Script#/Libraries/Node/Core
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Runtime.CompilerServices;
namespace NodeApi.IO {
[ScriptImport]
[ScriptIgnoreNamespace]
[ScriptDependency("path")]
public static class Path {
[ScriptName("sep")]
public static string PathSeparator = null;
[ScriptName("dirname")]
public static string GetDirectoryName(string path) {
return null;
}
[ScriptName("extname")]
public static string GetExtension(string path) {
return null;
}
[ScriptName("basename")]
public static string GetName(string path) {
return null;
}
[ScriptName("basename")]
public static string GetName(string path, string extensionToStrip) {
return null;
}
public static string Join(params string[] pathParts) {
return null;
}
[ScriptName("relative")]
public static string MakeRelative(string from, string to) {
return null;
}
public static string Normalize(string path) {
return null;
}
public static string Resolve(string from, string to) {
return null;
}
}
}
| apache-2.0 | C# |
da320859a4c3c67d62de1b4a574fabdf22163073 | update version to 5.5.2 | chimpinano/WebApi,congysu/WebApi,yonglehou/WebApi,lungisam/WebApi,lewischeng-ms/WebApi,abkmr/WebApi,abkmr/WebApi,yonglehou/WebApi,LianwMS/WebApi,lewischeng-ms/WebApi,congysu/WebApi,LianwMS/WebApi,chimpinano/WebApi,scz2011/WebApi,scz2011/WebApi,lungisam/WebApi | OData/src/CommonAssemblyInfo.cs | OData/src/CommonAssemblyInfo.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.5.2.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.5.2.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyCompany("Microsoft Corporation.")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
#endif
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
#if !NOT_CLS_COMPLIANT
[assembly: CLSCompliant(true)]
#endif
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("Serviceable", "True")]
// ===========================================================================
// DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT.
// Version numbers are automatically generated based on regular expressions.
// ===========================================================================
#if ASPNETODATA
#if !BUILD_GENERATED_VERSION
[assembly: AssemblyVersion("5.5.1.0")] // ASPNETODATA
[assembly: AssemblyFileVersion("5.5.1.0")] // ASPNETODATA
#endif
[assembly: AssemblyProduct("Microsoft OData Web API")]
#endif | mit | C# |
c434a9587743ed71a9ab76a0f92811df27c3a4f9 | Add exception handling to console | andburn/dds-reader | DDSReader/DDSReader.Console/Program.cs | DDSReader/DDSReader.Console/Program.cs | using System;
using System.IO;
namespace DDSReader.Console
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
System.Console.WriteLine("ERROR: input and output file required\n");
Environment.Exit(1);
}
var input = args[0];
var output = args[1];
if (!File.Exists(input))
{
System.Console.WriteLine("ERROR: input file does not exist\n");
Environment.Exit(1);
}
try
{
var dds = new DDSImage(input);
dds.Save(output);
}
catch (Exception e)
{
System.Console.WriteLine("ERROR: failed to convert DDS file\n");
System.Console.WriteLine(e);
Environment.Exit(1);
}
if (File.Exists(output))
{
System.Console.WriteLine("Successfully created " + output);
}
else
{
System.Console.WriteLine("ERROR: something went wrong!\n");
Environment.Exit(1);
}
}
}
}
| using System;
namespace DDSReader.Console
{
class Program
{
static void Main(string[] args)
{
var dds = new DDSImage(args[0]);
dds.Save(args[1]);
}
}
}
| mit | C# |
bc86db596ed53641a204037fd4a071d32e36ec54 | Fix primary screen getter | mono/xwt,TheBrainTech/xwt,akrisiun/xwt,mminns/xwt,hamekoz/xwt,iainx/xwt,cra0zy/xwt,sevoku/xwt,antmicro/xwt,mminns/xwt,hwthomas/xwt,steffenWi/xwt,directhex/xwt,lytico/xwt,residuum/xwt | Xwt.Gtk/Xwt.GtkBackend/GtkDesktopBackend.cs | Xwt.Gtk/Xwt.GtkBackend/GtkDesktopBackend.cs | //
// GtkDesktopBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Collections.Generic;
namespace Xwt.GtkBackend
{
public class GtkDesktopBackend: DesktopBackend
{
#region implemented abstract members of DesktopBackend
public GtkDesktopBackend ()
{
Gdk.Screen.Default.SizeChanged += delegate {
OnScreensChanged ();
};
Gdk.Screen.Default.CompositedChanged += delegate {
OnScreensChanged ();
};
}
public override Point GetMouseLocation ()
{
int x, y;
Gdk.Display.Default.GetPointer (out x, out y);
return new Point (x, y);
}
public override IEnumerable<object> GetScreens ()
{
for (int n=0; n<Gdk.Screen.Default.NMonitors; n++)
yield return n;
}
public override bool IsPrimaryScreen (object backend)
{
if (Platform.IsMac)
return (int)backend == 0;
else
return (int)backend == Gdk.Screen.Default.GetMonitorAtPoint (0, 0);
}
public override Rectangle GetScreenBounds (object backend)
{
var r = Gdk.Screen.Default.GetMonitorGeometry ((int)backend);
return new Rectangle (r.X, r.Y, r.Width, r.Height);
}
public override Rectangle GetScreenVisibleBounds (object backend)
{
var r = Gdk.Screen.Default.GetUsableMonitorGeometry ((int)backend);
return new Rectangle (r.X, r.Y, r.Width, r.Height);
}
public override string GetScreenDeviceName (object backend)
{
return backend.ToString ();
}
#endregion
}
}
| //
// GtkDesktopBackend.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using System.Collections.Generic;
namespace Xwt.GtkBackend
{
public class GtkDesktopBackend: DesktopBackend
{
#region implemented abstract members of DesktopBackend
public GtkDesktopBackend ()
{
Gdk.Screen.Default.SizeChanged += delegate {
OnScreensChanged ();
};
Gdk.Screen.Default.CompositedChanged += delegate {
OnScreensChanged ();
};
}
public override Point GetMouseLocation ()
{
int x, y;
Gdk.Display.Default.GetPointer (out x, out y);
return new Point (x, y);
}
public override IEnumerable<object> GetScreens ()
{
for (int n=0; n<Gdk.Screen.Default.NMonitors; n++)
yield return n;
}
public override bool IsPrimaryScreen (object backend)
{
return (int)backend == Gdk.Screen.Default.GetMonitorAtPoint (0, 0);
}
public override Rectangle GetScreenBounds (object backend)
{
var r = Gdk.Screen.Default.GetMonitorGeometry ((int)backend);
return new Rectangle (r.X, r.Y, r.Width, r.Height);
}
public override Rectangle GetScreenVisibleBounds (object backend)
{
var r = Gdk.Screen.Default.GetUsableMonitorGeometry ((int)backend);
return new Rectangle (r.X, r.Y, r.Width, r.Height);
}
public override string GetScreenDeviceName (object backend)
{
return backend.ToString ();
}
#endregion
}
}
| mit | C# |
f29a0edc196e9a77e93ba2701b2ddbfc6d80794f | Add ItemId attribute to Account | jcvandan/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,XeroAPI/XeroAPI.Net,TDaphneB/XeroAPI.Net | source/XeroApi/Model/Account.cs | source/XeroApi/Model/Account.cs | using System;
namespace XeroApi.Model
{
public class Account : ModelBase
{
[ItemId]
public Guid AccountID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public string TaxType { get; set; }
public string Description { get; set; }
public string Class { get; set; }
public string SystemAccount { get; set; }
public bool? EnablePaymentsToAccount { get; set; }
public string BankAccountNumber { get; set; }
public string CurrencyCode { get; set; }
public string ReportingCode { get; set; }
public string ReportingCodeName { get; set; }
}
public class Accounts : ModelList<Account>
{
}
} | using System;
namespace XeroApi.Model
{
public class Account : ModelBase
{
public Guid AccountID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public string TaxType { get; set; }
public string Description { get; set; }
public string Class { get; set; }
public string SystemAccount { get; set; }
public bool? EnablePaymentsToAccount { get; set; }
public string BankAccountNumber { get; set; }
public string CurrencyCode { get; set; }
public string ReportingCode { get; set; }
public string ReportingCodeName { get; set; }
}
public class Accounts : ModelList<Account>
{
}
} | mit | C# |
d0b26057fd749afe709f906877ead3371d879d63 | Remove unused IsValid method | Vtek/Bartender | src/Bartender/IMessageValidator.cs | src/Bartender/IMessageValidator.cs | namespace Bartender
{
/// <summary>
/// Define a message validator
/// </summary>
public interface IMessageValidator<TMessage> where TMessage : IMessage
{
/// <summary>
/// Validate the specified message.
/// </summary>
/// <param name="message">Message.</param>
void Validate(TMessage message);
}
}
| namespace Bartender
{
/// <summary>
/// Define a message validator
/// </summary>
public interface IMessageValidator<TMessage> where TMessage : IMessage
{
/// <summary>
/// Validate the specified message.
/// </summary>
/// <param name="message">Message.</param>
void Validate(TMessage message);
/// <summary>
/// True if the message is valid, otherwise false
/// </summary>
/// <param name="message">Message.</param>
/// <returns>True if the message is valid, otherwise false</returns>
bool IsValid(TMessage message);
}
}
| mit | C# |
71f0078727cfa2d60a6d50a3c83a1c40a97ef5cf | Bump minor version and push to NuGet | pragmatrix/NEventSocket,danbarua/NEventSocket,danbarua/NEventSocket,pragmatrix/NEventSocket | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NEventSocket")]
[assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")]
[assembly: AssemblyCompany("Dan Barua")]
[assembly: AssemblyProduct("NEventSocket")]
[assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")]
[assembly: AssemblyVersion("0.3.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("NEventSocket")]
[assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")]
[assembly: AssemblyCompany("Dan Barua")]
[assembly: AssemblyProduct("NEventSocket")]
[assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")]
[assembly: AssemblyVersion("0.2.0.0")]
| mpl-2.0 | C# |
931acb3197eedde66b8f4db85ef539360e4dafee | Make setters private | Intelliflo/JustSaying,Intelliflo/JustSaying,eric-davis/JustSaying | JustEat.Simples.Messaging/Messages/OrderResolved/OrderResolvedMessage.cs | JustEat.Simples.Messaging/Messages/OrderResolved/OrderResolvedMessage.cs | namespace JustEat.Simples.NotificationStack.Messaging.Messages.OrderResolved
{
public abstract class OrderResolvedMessage : Message
{
public int OrderId { get; private set; }
public string AuditComment { get; private set; }
public bool NotifiyCustomer { get; private set; }
public OrderResolutionStatus OrderResolutionStatus { get; private set; }
protected OrderResolvedMessage(int orderId, string auditComment, bool notifiyCustomer, OrderResolutionStatus orderResolutionStatus)
{
OrderResolutionStatus = orderResolutionStatus;
NotifiyCustomer = notifiyCustomer;
AuditComment = auditComment;
OrderId = orderId;
}
}
} | namespace JustEat.Simples.NotificationStack.Messaging.Messages.OrderResolved
{
public class OrderResolvedMessage : Message
{
public int OrderId { get; set; }
public string AuditComment { get; set; }
public bool NotifiyCustomer { get; set; }
public OrderResolutionStatus OrderResolutionStatus { get; set; }
public OrderResolvedMessage(int orderId, string auditComment, bool notifiyCustomer, OrderResolutionStatus orderResolutionStatus)
{
OrderResolutionStatus = orderResolutionStatus;
NotifiyCustomer = notifiyCustomer;
AuditComment = auditComment;
OrderId = orderId;
}
}
} | apache-2.0 | C# |
c333a6dd2a632cd374234b786b5711ee74e8c62c | Update assembly info | toehead2001/pdn-barcode | Barcode/Properties/AssemblyInfo.cs | Barcode/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Barcode Effect")]
[assembly: AssemblyDescription("Barcode Generator")]
[assembly: AssemblyConfiguration("Barcode|Code 39|POSTNET|UPC")]
[assembly: AssemblyCompany("toe_head2001")]
[assembly: AssemblyProduct("Barcode Effect")]
[assembly: AssemblyCopyright("Copyright © 2018 toe_head2001, Michael J. Sepcot")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.5.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Barcode Effect")]
[assembly: AssemblyDescription("Barcode Generator")]
[assembly: AssemblyConfiguration("Barcode|Code 39|POSTNET|UPC")]
[assembly: AssemblyCompany("Sepcot & toe_head2001")]
[assembly: AssemblyProduct("Barcode Effect")]
[assembly: AssemblyCopyright("Copyright © 2018 Michael J. Sepcot & toe_head2001")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.5.0.0")] | mit | C# |
9f30d7ec4a633fca63cd9680d62e6b2395c00b5d | add comment to GenerateUtil | peopleware/net-ppwcode-util-oddsandends | src/II/SpreadSheet/GenerateUtil.cs | src/II/SpreadSheet/GenerateUtil.cs | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
namespace PPWCode.Util.OddsAndEnds.II.SpreadSheet
{
public class GenerateUtil
{
/// <summary>
/// Reads an excel sheet into a IList of given type.
/// </summary>
/// <typeparam name="T">The given type.</typeparam>
/// <param name="xlsFile">The excel file.</param>
/// <param name="sheet">The sheet to read.</param>
/// <param name="columns">The columns.</param>
/// <param name="spreadSheetRowResolver">The DbDataReader and type.</param>
/// <returns>An IList of given type.</returns>
public static IList<T> ReadSheet<T>(string xlsFile, string sheet, List<string> columns, Func<DbDataReader, T> spreadSheetRowResolver)
where T : class
{
ExcelUtil excelUtil = new ExcelUtil(xlsFile);
StringBuilder selectStatement = new StringBuilder();
selectStatement.Append(@"select");
foreach (string item in columns)
{
selectStatement.Append("[" + item + "],");
}
selectStatement.Remove(selectStatement.Length - 1, 1);
selectStatement.Append(string.Format(@"from [{0}$]", sheet));
try
{
return excelUtil.ReadSheet<T>(selectStatement.ToString(), spreadSheetRowResolver);
}
catch (Exception e)
{
throw new Exception(string.Format("Structure error in sheet: {0} with message : {1}", sheet, e.Message));
}
}
}
} | // Copyright 2014 by PeopleWare n.v..
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;
namespace PPWCode.Util.OddsAndEnds.II.SpreadSheet
{
public class GenerateUtil
{
public static IList<T> ReadSheet<T>(string xlsFile, string sheet, List<string> columns, Func<DbDataReader, T> spreadSheetRowResolver)
where T : class
{
ExcelUtil excelUtil = new ExcelUtil(xlsFile);
StringBuilder selectStatement = new StringBuilder();
selectStatement.Append(@"select");
foreach (string item in columns)
{
selectStatement.Append("[" + item + "],");
}
selectStatement.Remove(selectStatement.Length - 1, 1);
selectStatement.Append(string.Format(@"from [{0}$]", sheet));
try
{
return excelUtil.ReadSheet<T>(selectStatement.ToString(), spreadSheetRowResolver);
}
catch (Exception e)
{
throw new Exception(string.Format("Structure error in sheet: {0} with message : {1}", sheet, e.Message));
}
}
}
} | apache-2.0 | C# |
394970a1e138139eb78ab8f9494c6649dccdf26d | Use “yield” instead of List for GetTransitions | lou1306/CIV,lou1306/CIV | CIV.Ccs/Processes/PrefixProcess.cs | CIV.Ccs/Processes/PrefixProcess.cs | using System;
using System.Collections.Generic;
using CIV.Common;
namespace CIV.Ccs
{
class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
protected override IEnumerable<Transition> EnumerateTransitions()
{
yield return new Transition
{
Label = Label,
Process = Inner
};
}
protected override string BuildRepr()
{
return $"{Label}{Const.prefix}{Inner}";
}
}
}
| using System;
using System.Collections.Generic;
using CIV.Common;
namespace CIV.Ccs
{
class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
protected override IEnumerable<Transition> EnumerateTransitions()
{
return new List<Transition>{
new Transition{
Label = Label,
Process = Inner
}
};
}
protected override string BuildRepr()
{
return $"{Label}{Const.prefix}{Inner}";
}
}
}
| mit | C# |
f696a842e42df5fd1966d2284496edb707f65550 | Add SO link | aloisdg/algo | Algo/CaesarCipher/CaesarCipher.cs | Algo/CaesarCipher/CaesarCipher.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaesarCipher
{
public class CaesarCipher
{
/*
* http://en.wikipedia.org/wiki/Caesar_cipher
*/
public static string Encrypt(string input, int code)
{
return RunCipher(input, code);
}
public static string Decrypt(string input, int code)
{
return RunCipher(input, -code);
}
private static string RunCipher(string letters, int shift)
{
return new String(MoveLetters(letters, shift).ToArray());
}
//http://stackoverflow.com/questions/8501444/caesar-cipher-in-c-sharp?rq=1
public static IEnumerable<char> MoveLetters(string letters, int shift)
{
return from letter in letters
let diffCase = Char.IsLower(letter) ? 0 : 32
let max = 'z' - diffCase
let min = 'a' - diffCase
let isAsciiLetter = letter >= min && letter <= max
let l = (char)(letter + shift % 26)
select isAsciiLetter
? (char)(l > max ? l - 26 : l < min ? l + 26 : l)
: letter;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CaesarCipher
{
public class CaesarCipher
{
/*
* http://en.wikipedia.org/wiki/Caesar_cipher
*/
public static string Encrypt(string input, int code)
{
return RunCipher(input, code);
}
public static string Decrypt(string input, int code)
{
return RunCipher(input, -code);
}
private static string RunCipher(string letters, int shift)
{
return new String(MoveLetters(letters, shift).ToArray());
}
public static IEnumerable<char> MoveLetters(string letters, int shift)
{
return from letter in letters
let diffCase = Char.IsLower(letter) ? 0 : 32
let max = 'z' - diffCase
let min = 'a' - diffCase
let isAsciiLetter = letter >= min && letter <= max
let l = (char)(letter + shift % 26)
select isAsciiLetter
? (char)(l > max ? l - 26 : l < min ? l + 26 : l)
: letter;
}
}
}
| bsd-3-clause | C# |
7bc59b132aeb3831068a89515745183ab34bfa17 | mark method as public | Recognos/CodeChalenges | Challenge2/Challenge2/Solution.cs | Challenge2/Challenge2/Solution.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Challenge2
{
class Solution
{
const int MaxConcurrency = 5;
const int TotalNumberOfExecutions = 20;
static int currentlyActiveOperations = 0;
static int startedOperations = 0;
static SemaphoreSlim semaphore = new SemaphoreSlim(MaxConcurrency);
public static void RunMain(string[] args)
{
Task[] tasks = new Task[TotalNumberOfExecutions];
for (int i = 0; i < TotalNumberOfExecutions; i++)
{
tasks[i] = Task.Factory.StartNew(() => LongRunningCpuIntensiveOperationAsync()).Unwrap();
}
Task.WhenAll(tasks).Wait();
Console.WriteLine("done");
Console.ReadKey();
}
private static async Task LongRunningCpuIntensiveOperationAsync()
{
try
{
await semaphore.WaitAsync();
await RealOpeartion();
}
finally
{
semaphore.Release();
}
}
// Simulates async work. You can't modify tis method
private static async Task RealOpeartion()
{
Interlocked.Increment(ref currentlyActiveOperations);
if (currentlyActiveOperations > MaxConcurrency)
{
throw new InvalidOperationException("Too much concurrency");
}
var number = Interlocked.Increment(ref startedOperations);
Console.WriteLine("Starting {0}", number);
await Task.Delay(1000);
Console.WriteLine("Completed {0}", number);
Interlocked.Decrement(ref currentlyActiveOperations);
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace Challenge2
{
class Solution
{
const int MaxConcurrency = 5;
const int TotalNumberOfExecutions = 20;
static int currentlyActiveOperations = 0;
static int startedOperations = 0;
static SemaphoreSlim semaphore = new SemaphoreSlim(MaxConcurrency);
private static void RunMain()
{
Task[] tasks = new Task[TotalNumberOfExecutions];
for (int i = 0; i < TotalNumberOfExecutions; i++)
{
tasks[i] = Task.Factory.StartNew(() => LongRunningCpuIntensiveOperationAsync()).Unwrap();
}
Task.WhenAll(tasks).Wait();
Console.WriteLine("done");
Console.ReadKey();
}
private static async Task LongRunningCpuIntensiveOperationAsync()
{
try
{
await semaphore.WaitAsync();
await RealOpeartion();
}
finally
{
semaphore.Release();
}
}
// Simulates async work. You can't modify tis method
private static async Task RealOpeartion()
{
Interlocked.Increment(ref currentlyActiveOperations);
if (currentlyActiveOperations > MaxConcurrency)
{
throw new InvalidOperationException("Too much concurrency");
}
var number = Interlocked.Increment(ref startedOperations);
Console.WriteLine("Starting {0}", number);
await Task.Delay(1000);
Console.WriteLine("Completed {0}", number);
Interlocked.Decrement(ref currentlyActiveOperations);
}
}
}
| apache-2.0 | C# |
2680454fda31eb6cdc1f105e595775a53331770c | Set UserAgent on HTTP Client. | lewishenson/FluentMetacritic,lewishenson/FluentMetacritic | FluentMetacritic/Net/HttpClientWrapper.cs | FluentMetacritic/Net/HttpClientWrapper.cs | using System.Net.Http;
using System.Threading.Tasks;
namespace FluentMetacritic.Net
{
public class HttpClientWrapper : IHttpClient
{
private static readonly HttpClient Client;
static HttpClientWrapper()
{
Client = new HttpClient();
Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36");
}
public async Task<string> GetContentAsync(string address)
{
return await Client.GetStringAsync(address);
}
}
} | using System.Net.Http;
using System.Threading.Tasks;
namespace FluentMetacritic.Net
{
public class HttpClientWrapper : IHttpClient
{
private static readonly HttpClient Client = new HttpClient();
public async Task<string> GetContentAsync(string address)
{
return await Client.GetStringAsync(address);
}
}
} | mit | C# |
80e553b95797e961045fe1f985086e8e41405ffd | Change version to 1.9 | Seddryck/NBi,Seddryck/NBi | AssemblyInfo.cs | AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// 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: AssemblyCompany("NBi Team - Cédric L. Charlier")]
[assembly: AssemblyProduct("NBi")]
[assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2012-2014")]
[assembly: AssemblyDescription("NBi is a testing framework (add-on to NUnit) for Microsoft Business Intelligence platform and Data Access. The main goal of this framework is to let users create tests with a declarative approach based on an Xml syntax. By the means of NBi, you don't need to develop C# code to specify your tests! Either, you don't need Visual Studio to compile your test suite. Just create an Xml file and let the framework interpret it and play your tests. The framework is designed as an add-on of NUnit but with the possibility to port it easily to other testing frameworks.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//Reference the testing class to ensure access to internal members
[assembly: InternalsVisibleTo("NBi.Testing")]
// 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.9.0.*")] | using System.Reflection;
using System.Runtime.CompilerServices;
// 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: AssemblyCompany("NBi Team - Cédric L. Charlier")]
[assembly: AssemblyProduct("NBi")]
[assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2012-2014")]
[assembly: AssemblyDescription("NBi is a testing framework (add-on to NUnit) for Microsoft Business Intelligence platform and Data Access. The main goal of this framework is to let users create tests with a declarative approach based on an Xml syntax. By the means of NBi, you don't need to develop C# code to specify your tests! Either, you don't need Visual Studio to compile your test suite. Just create an Xml file and let the framework interpret it and play your tests. The framework is designed as an add-on of NUnit but with the possibility to port it easily to other testing frameworks.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//Reference the testing class to ensure access to internal members
[assembly: InternalsVisibleTo("NBi.Testing")]
// 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.8.0.*")] | apache-2.0 | C# |
8779ba86dba68bb960a931104194cff1a88e46d1 | Set proper names for CallBase tests | Moq/moq | src/Moq/Moq.Tests/CallBaseTests.cs | src/Moq/Moq.Tests/CallBaseTests.cs | using System;
using System.ComponentModel;
using Xunit;
using Moq.Sdk;
using static Moq.Syntax;
using Sample;
namespace Moq.Tests
{
public class CallBaseTests
{
[Fact]
public void CallBaseNotCalled()
{
var mock = Mock.Of<Calculator>();
mock.TurnOn();
Assert.False(mock.TurnOnCalled);
}
[Fact]
public void CallBaseCalledForMockConfig()
{
var mock = Mock.Of<Calculator>().CallBase();
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
}
[Fact]
public void CallBaseCalledForInvocationConfig()
{
var mock = Mock.Of<Calculator>();
mock.Setup(x => x.TurnOn()).CallBase();
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
}
[Fact]
public void ThrowsForStrictMockAndMissingSetup()
{
// Configure CallBase at the Mock level
var mock = Mock.Of<Calculator>(MockBehavior.Strict).CallBase();
Assert.Throws<StrictMockException>(() => mock.TurnOn());
}
[Fact]
public void CallBaseCalledForStrictMockAndMockConfig()
{
// Configure CallBase at the Mock level
var mock = Mock.Of<Calculator>(MockBehavior.Strict).CallBase();
mock.Setup(x => x.TurnOn());
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
// And we make sure we throw for other missing setups
Assert.Throws<StrictMockException>(() => mock.Recall(""));
}
[Fact]
public void CallBaseCalledForStrickMockAndInvocationConfig()
{
var mock = Mock.Of<Calculator>(MockBehavior.Strict);
// Configure CallBase at the invocation level
mock.Setup(x => x.TurnOn()).CallBase();
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
// And we make sure we throw for other missing setups
Assert.Throws<StrictMockException>(() => mock.Recall(""));
}
}
} | using System;
using System.ComponentModel;
using Xunit;
using Moq.Sdk;
using static Moq.Syntax;
using Sample;
namespace Moq.Tests
{
public class CallBaseTests
{
[Fact]
public void callbase1()
{
var mock = Mock.Of<Calculator>();
mock.TurnOn();
Assert.False(mock.TurnOnCalled);
}
[Fact]
public void callbase2()
{
var mock = Mock.Of<Calculator>().CallBase();
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
}
[Fact]
public void callbase3()
{
var mock = Mock.Of<Calculator>();
mock.Setup(x => x.TurnOn()).CallBase();
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
}
[Fact]
public void callbase4()
{
var mock = Mock.Of<Calculator>(MockBehavior.Strict).CallBase();
Assert.Throws<StrictMockException>(() => mock.TurnOn());
}
[Fact]
public void callbase5()
{
var mock = Mock.Of<Calculator>(MockBehavior.Strict).CallBase();
mock.Setup(x => x.TurnOn());
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
Assert.Throws<StrictMockException>(() => mock.Recall(""));
}
[Fact]
public void callbase6()
{
var mock = Mock.Of<Calculator>(MockBehavior.Strict);
mock.Setup(x => x.TurnOn()).CallBase();
mock.TurnOn();
Assert.True(mock.TurnOnCalled);
Assert.Throws<StrictMockException>(() => mock.Recall(""));
}
}
} | apache-2.0 | C# |
7837e967d2230870c3baf286877066de57a7a7af | update value | jefking/King.Mapper | King.Mapper/Properties/AssemblyInfo.cs | King.Mapper/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("King.Mapper")]
[assembly: AssemblyDescription("High performance model mapping.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("King.Mapper")]
[assembly: AssemblyCopyright("Copyright © Jef King 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("900a2472-c826-4e99-aa69-60b56745f56a")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.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("King.Mapper")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("King.Mapper")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4067bd7b-accc-47e6-bee7-0f5d6486e286")]
| mit | C# |
d217ca3ffd5d53de7f950617cc6d8b5056a0eb6f | Update ConfigExplorerMiddleware.cs | ctolkien/SodaPop.ConfigExplorer | src/ConfigExplorerMiddleware.cs | src/ConfigExplorerMiddleware.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using RazorLight;
using System.Linq;
namespace SodaPop.ConfigExplorer
{
public class ConfigExplorerMiddleware
{
private readonly IConfigurationRoot _config;
private readonly ConfigExplorerOptions _explorerOptions;
private readonly RequestDelegate _next;
public ConfigExplorerMiddleware(RequestDelegate next, IConfigurationRoot config, ConfigExplorerOptions explorerOptions)
{
_config = config;
_explorerOptions = explorerOptions;
_next = next;
}
public async Task Invoke(HttpContext context)
{
var configs = CreateConfigurationList(_config.GetChildren()).ToList();
var engine = EngineFactory.CreateEmbedded(typeof(ConfigExplorerMiddleware));
var result = engine.Parse("Configs", configs);
await context.Response.WriteAsync(result);
}
/// <summary>
/// Builds a tree of options via recursion
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
private IEnumerable<ConfigurationItem> CreateConfigurationList(IEnumerable<IConfigurationSection> config)
{
//todo: make this less bad
var iter = config.GetEnumerator();
while (iter.MoveNext())
{
var c = iter.Current;
var o = new ConfigurationItem { Path = c.Path, Key = c.Key, Value = c.Value };
if (_explorerOptions.TryRedactConnectionStrings)
{
//todo: especially this bit
if (o.Path.Contains("ConnectionString", StringComparison.OrdinalIgnoreCase))
{
o.Value = "REDACTED";
}
}
o.Children = CreateConfigurationList(c.GetChildren());
yield return o;
}
}
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using RazorLight;
using System.Linq;
namespace SodaPop.ConfigExplorer
{
public class ConfigExplorerMiddleware
{
private readonly IConfigurationRoot _config;
private readonly ConfigExplorerOptions _explorerOptions;
private readonly RequestDelegate _next;
public ConfigExplorerMiddleware(RequestDelegate next, IConfigurationRoot config, ConfigExplorerOptions explorerOptions)
{
_config = config;
_explorerOptions = explorerOptions;
_next = next;
}
public async Task Invoke(HttpContext context)
{
var configs = CreateConfigurationList(_config.GetChildren()).ToList();
var engine = EngineFactory.CreateEmbedded(typeof(ConfigExplorerMiddleware));
var result = engine.Parse("Configs", configs);
await context.Response.WriteAsync(result);
}
/// <summary>
/// Builds a tree of options via recursion
/// </summary>
/// <param name="config"></param>
/// <returns></returns>
private IEnumerable<ConfigurationItem> CreateConfigurationList(IEnumerable<IConfigurationSection> config)
{
//todo: make this less bad
var iter = config.GetEnumerator();
while (iter.MoveNext())
{
var c = iter.Current;
var o = new ConfigurationItem { Path = c.Path, Key = c.Key, Value = c.Value };
if (_explorerOptions.TryRedactConnectionStrings)
{
//todo: especially this bit
if (o.Path.Contains("ConnectionString", StringComparison.OrdinalIgnoreCase))
{
o.Value = "REDACTED";
}
}
o.Children = CreateConfigurationList(c.GetChildren());
yield return o;
}
}
}
}
| mit | C# |
148de4f8b28ec158b29146066f99e225d7a7fe69 | Fix Text AssemblyInfo | YallaDotNet/syslog | Text/Properties/AssemblyInfo.cs | Text/Properties/AssemblyInfo.cs | using System;
using System.Reflection;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyTitle("SyslogNet.Client.Text")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("SyslogNet.Client")]
[assembly: AssemblyCopyright("Copyright © 2014-2015 Xamarin Inc. (www.xamarin.com)")]
[assembly: AssemblyTrademark("Xamarin Inc.")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("1.0.*")]
| using System;
using System.Reflection;
// 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("SyslogNet.Client.Text")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Andrew Smith")]
[assembly: AssemblyProduct("SyslogNet.Client")]
[assembly: AssemblyCopyright("Copyright © Andrew Smith 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
952f6e4834aa796cedd74010a44646ff9876101c | Sort graph descending | jaredpar/Bugs,jaredpar/Bugs,jaredpar/Bugs | TheBugs/Views/Bugs/Graph.cshtml | TheBugs/Views/Bugs/Graph.cshtml | @using TheBugs.Models
@using System.Text;
@model ListModel
@{
ViewBag.Title = "Assigned Graph";
var title = $"Assigned Issues";
var header = $"Developer,Count";
var builder = new StringBuilder();
foreach (var group in Model.Issues.GroupBy(x => x.Assignee).OrderByDescending(g => g.Count()))
{
var count = group.Count();
if (builder.Length > 0)
{
builder.Append(";");
}
builder.Append($"{group.Key},{count}");
}
}
<div>
<h2>Assigned Bugs</h2>
<h3>Total: @Model.Issues.Count</h3>
</div>
<div id="pie_chart" style="width: 900px; height: 500px" data-title="@title" data-header="@header" data-values="@builder.ToString()" ></div>
@Html.Partial("PartialQueryFilter", Model.QueryModel)
@section scripts {
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/Charts/pie-chart.js")"></script>
}
| @using TheBugs.Models
@using System.Text;
@model ListModel
@{
ViewBag.Title = "Assigned Graph";
var title = $"Assigned Issues";
var header = $"Developer,Count";
var builder = new StringBuilder();
foreach (var group in Model.Issues.GroupBy(x => x.Assignee))
{
var count = group.Count();
if (builder.Length > 0)
{
builder.Append(";");
}
builder.Append($"{group.Key},{count}");
}
}
<div>
<h2>Assigned Bugs</h2>
<h3>Total: @Model.Issues.Count</h3>
</div>
<div id="pie_chart" style="width: 900px; height: 500px" data-title="@title" data-header="@header" data-values="@builder.ToString()" ></div>
@Html.Partial("PartialQueryFilter", Model.QueryModel)
@section scripts {
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/Charts/pie-chart.js")"></script>
}
| apache-2.0 | C# |
7e02f60ae9b7a2c26db9b452d2cc3e98a730439e | Update src/Workspaces/Core/Portable/Storage/LegacyPersistentStorageService.cs | jasonmalinowski/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,sharwell/roslyn,KevinRansom/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,KevinRansom/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,mavasani/roslyn,weltkante/roslyn,dotnet/roslyn,bartdesmet/roslyn,mavasani/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn | src/Workspaces/Core/Portable/Storage/LegacyPersistentStorageService.cs | src/Workspaces/Core/Portable/Storage/LegacyPersistentStorageService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Storage
{
/// <summary>
/// Obsolete. Roslyn no longer supports a mechanism to perform arbitrary persistence of data. If such functionality
/// is needed, consumers are responsible for providing it themselves with whatever semantics are needed.
/// </summary>
[Obsolete("Roslyn no longer exports a mechanism to perform persistence.", error: true)]
internal sealed class LegacyPersistentStorageService : IPersistentStorageService
{
[ExportWorkspaceServiceFactory(typeof(IPersistentStorageService)), Shared]
internal sealed class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new LegacyPersistentStorageService();
}
public LegacyPersistentStorageService()
{
}
public IPersistentStorage GetStorage(Solution solution)
=> NoOpPersistentStorage.GetOrThrow(throwOnFailure: false);
public ValueTask<IPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken)
=> new(NoOpPersistentStorage.GetOrThrow(throwOnFailure: false));
}
}
| // 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.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Storage
{
/// <summary>
/// Obsolete. Roslyn no longer supports a mechanism to perform arbitrary persistence of data. If such functionality
/// is needed, consumers are resonsible for providing it themselves with whatever semantics are needed.
/// </summary>
[Obsolete("Roslyn no longer exports a mechanism to perform persistence.", error: true)]
internal sealed class LegacyPersistentStorageService : IPersistentStorageService
{
[ExportWorkspaceServiceFactory(typeof(IPersistentStorageService)), Shared]
internal sealed class Factory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public Factory()
{
}
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new LegacyPersistentStorageService();
}
public LegacyPersistentStorageService()
{
}
public IPersistentStorage GetStorage(Solution solution)
=> NoOpPersistentStorage.GetOrThrow(throwOnFailure: false);
public ValueTask<IPersistentStorage> GetStorageAsync(Solution solution, CancellationToken cancellationToken)
=> new(NoOpPersistentStorage.GetOrThrow(throwOnFailure: false));
}
}
| mit | C# |
14cabbb882983dd6677d6df3a4e499d50a27ef6a | Fix unawaited async call | CollabIP/Tethr.AudioBroker.SDK | src/UploadRecordingSample/Program.cs | src/UploadRecordingSample/Program.cs | using System;
using System.Configuration;
using System.IO;
using Tethr.Api;
using Tethr.Api.Model;
//////////////////////////////////////////////////////////////////////////////
// The credentials for connecting to the Tethr environment
// are stored in the App.config file (UploadRecording.exe.config after build)
// under these keys:
// <appSettings>
// <add key = "apiUri" value="Uri goes here" />
// <add key = "apiUser" value="API user name goes here" />
// <add key = "apiPassword" value="API password goes here" />
// </appSettings>
//
// Invoke this demo app by passing the path to a json file (which is preformatted for the HTTPS request)
// or to an XML file containing the Numonix metadata. A wav file is assumed to be "next to" the
// metadata file and have the same name.
//
// For the purpose of this demo program, the CallDirection field must exist in the xml file.
namespace UploadRecordingSample
{
class Program
{
private static OauthApiConnection _apiConnection;
static void Main(string[] args)
{
var apiUri = new Uri(ConfigurationManager.AppSettings["apiUri"]);
var apiUser = ConfigurationManager.AppSettings["apiUser"];
var apiPassword = ConfigurationManager.AppSettings["apiPassword"];
// The OauthApiConnection object should be reused on subsequent sends so that
// the oauth bearer token can be reused and refreshed only when it expires
_apiConnection = new OauthApiConnection();
_apiConnection.Initialize(apiUri, apiUser, apiPassword, null);
var tethrConnection = new TethrConnection(_apiConnection);
var fileName = args.Length < 2 ? "SampleRecording.json" : args[1] ?? "";
var jsonStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var wavStream = new FileStream(Path.ChangeExtension(fileName, ".wav"), FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
var recording = jsonStream.JsonDeserialize<RecordingInfo>();
// The sessionID must be unique per recording
// Here we are appending the time so we can test with the same file multiple times.
recording.SessionId += DateTime.UtcNow.ToString("o");
var result = tethrConnection.SendRecording(recording, wavStream).GetAwaiter().GetResult();
Console.WriteLine("Sent recording to Tethr as {0}", result.CallId);
}
}
}
| using System;
using System.Configuration;
using System.IO;
using Tethr.Api;
using Tethr.Api.Model;
//////////////////////////////////////////////////////////////////////////////
// The credentials for connecting to the Tethr environment
// are stored in the App.config file (UploadRecording.exe.config after build)
// under these keys:
// <appSettings>
// <add key = "apiUri" value="Uri goes here" />
// <add key = "apiUser" value="API user name goes here" />
// <add key = "apiPassword" value="API password goes here" />
// </appSettings>
//
// Invoke this demo app by passing the path to a json file (which is preformatted for the HTTPS request)
// or to an XML file containing the Numonix metadata. A wav file is assumed to be "next to" the
// metadata file and have the same name.
//
// For the purpose of this demo program, the CallDirection field must exist in the xml file.
namespace UploadRecordingSample
{
class Program
{
private static OauthApiConnection _apiConnection;
static void Main(string[] args)
{
var apiUri = new Uri(ConfigurationManager.AppSettings["apiUri"]);
var apiUser = ConfigurationManager.AppSettings["apiUser"];
var apiPassword = ConfigurationManager.AppSettings["apiPassword"];
// The OauthApiConnection object should be reused on subsequent sends so that
// the oauth bearer token can be reused and refreshed only when it expires
_apiConnection = new OauthApiConnection();
_apiConnection.Initialize(apiUri, apiUser, apiPassword, null);
var tethrConnection = new TethrConnection(_apiConnection);
var fileName = args.Length < 2 ? "SampleRecording.json" : args[1] ?? "";
var jsonStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var wavStream = new FileStream(Path.ChangeExtension(fileName, ".wav"), FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
var recording = jsonStream.JsonDeserialize<RecordingInfo>();
// The sessionID must be unique per recording
// Here we are appending the time so we can test with the same file multiple times.
recording.SessionId += DateTime.UtcNow.ToString("o");
var result = tethrConnection.SendRecording(recording, wavStream);
Console.WriteLine("Sent recording to Tethr as {0}", result.Result.CallId);
}
}
}
| mit | C# |
6287c685debbb4d3a0790c93b3c5d8e384e0eddf | build 7.1.34.0 | agileharbor/channelAdvisorAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.34.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.33.0" ) ] | bsd-3-clause | C# |
4f74ea78fb4f27b23a2a4eadcad05d3fbe2d76ad | update assembly | agileharbor/shipStationAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.62.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.61.0" ) ] | bsd-3-clause | C# |
d3e08472069d9126815855e158aa587791f71e76 | fix compile error | kheiakiyama/speech-eng-functions | SentenceScraping/run.csx | SentenceScraping/run.csx | #r "System.Configuration"
#load "../QuestionEntity.csx"
using System.Net;
using System.Net.Http;
using System.Configuration;
using System.Linq;
using Newtonsoft.Json;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using LinqToTwitter;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("ResultCount function processed a request.");
if (req.Method == HttpMethod.Post)
return await Post(req, log);
else
return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation");
}
private static async Task<HttpResponseMessage> Post(HttpRequestMessage req, TraceWriter log)
{
var auth = new LinqToTwitter.SingleUserAuthorizer
{
CredentialStore = new LinqToTwitter.SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["Twitter_ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["Twitter_ConsumerSecret"],
AccessToken = ConfigurationManager.AppSettings["Twitter_AccessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["Twitter_AccessTokenSecret"]
}
};
var twitter = new TwitterContext(auth);
var dic = await EigoMeigen_bot(twitter);
foreach (var key in dic.Keys)
{
var existEntity = QuestionEntity.GetEntity(key.ToString());
if (existEntity != null)
continue;
var entity = new QuestionEntity(key) {
Sentence = dic[key],
};
entity.Insert();
}
return req.CreateResponse(HttpStatusCode.OK, new {
});
}
private static async Task<Dictionary<ulong, string>> EigoMeigen_bot(TwitterContext context)
{
var tweets = await context.Status
.Where(tweet => tweet.Type == StatusType.User && tweet.ScreenName == "EigoMeigen_bot")
.ToListAsync();
Dictionary<ulong, string> dic = new Dictionary<ulong, string>();
tweets.ForEach((obj) => {
var english = obj.Text.Split(new string[] { "¥n" }, StringSplitOptions.None).FirstOrDefault();
dic.Add(obj.StatusID, english);
});
return dic;
} | #r "System.Configuration"
#load "../QuestionEntity.csx"
using System.Net;
using System.Net.Http;
using System.Configuration;
using Newtonsoft.Json;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using LinqToTwitter;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info("ResultCount function processed a request.");
if (req.Method == HttpMethod.Post)
return await Post(req, log);
else
return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation");
}
private static async Task<HttpResponseMessage> Post(HttpRequestMessage req, TraceWriter log)
{
var auth = new LinqToTwitter.SingleUserAuthorizer
{
CredentialStore = new LinqToTwitter.SingleUserInMemoryCredentialStore
{
ConsumerKey = ConfigurationManager.AppSettings["Twitter_ConsumerKey"],
ConsumerSecret = ConfigurationManager.AppSettings["Twitter_ConsumerSecret"],
AccessToken = ConfigurationManager.AppSettings["Twitter_AccessToken"],
AccessTokenSecret = ConfigurationManager.AppSettings["Twitter_AccessTokenSecret"]
}
};
var twitter = new TwitterContext(auth);
var dic = await EigoMeigen_bot(twitter);
foreach (var key in dic.Keys)
{
var existEntity = QuestionEntity.GetEntity(key.ToString());
if (existEntity != null)
continue;
var entity = new QuestionEntity(key) {
Sentence = dic[key],
};
entity.Insert();
}
return req.CreateResponse(HttpStatusCode.OK, new {
});
}
private static async Task<Dictionary<ulong, string>> EigoMeigen_bot(TwitterContext context)
{
var tweets = await context.Status
.Where(tweet => tweet.Type == StatusType.User && tweet.ScreenName == "EigoMeigen_bot")
.ToListAsync();
Dictionary<ulong, string> dic = new Dictionary<ulong, string>();
tweets.ForEach((obj) => {
var english = obj.Text.Split(new string[] { "¥n" }, StringSplitOptions.None).FirstOrDefault();
dic.Add(obj.StatusID, english);
});
return dic;
} | mit | C# |
279f0bd4bcc2e23aa82914878bc78e2187de563a | add IFileUsage interface | IUMDPI/IUMediaHelperApps | Common/Models/FileUsages.cs | Common/Models/FileUsages.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Common.Models
{
public interface IFileUsage
{
string FileUse { get; }
string FullFileUse { get; }
}
public class FileUsages : IFileUsage
{
private FileUsages(string fileUse, string fullFileUse)
{
FileUse = fileUse;
FullFileUse = fullFileUse;
}
public string FileUse { get; }
public string FullFileUse { get; }
public static readonly FileUsages PreservationMaster = new FileUsages("pres", "Preservation Master");
public static readonly FileUsages PreservationIntermediateMaster = new FileUsages("presInt", "Preservation Master - Intermediate");
public static readonly FileUsages ProductionMaster = new FileUsages("prod", "Production Master");
public static readonly FileUsages MezzanineFile = new FileUsages("mezz", "Mezzanine File");
public static readonly FileUsages AccessFile = new FileUsages("access", "Access File");
public static readonly FileUsages LabelImageFile = new FileUsages("label", "Label Image File");
public static readonly FileUsages XmlFile = new FileUsages("", "Xml File");
public static readonly FileUsages PreservationToneReference = new FileUsages("presRef", "Preservation Master Tone Reference File");
public static readonly FileUsages PreservationIntermediateToneReference = new FileUsages("intRef",
"Preservation Master - Intermediate Tone Reference File");
public static readonly FileUsages UnknownFile = new FileUsages("", "Raw object file");
private static readonly List<FileUsages> AllImportableUsages = new List<FileUsages>
{
PreservationMaster,
PreservationIntermediateMaster,
PreservationToneReference,
PreservationIntermediateToneReference,
ProductionMaster,
MezzanineFile,
AccessFile,
LabelImageFile
};
public static FileUsages GetUsage(string fileUse)
{
var usage = AllImportableUsages.SingleOrDefault(
u => u.FileUse.Equals(fileUse, StringComparison.InvariantCultureIgnoreCase));
return usage ?? UnknownFile;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Common.Models
{
public class FileUsages
{
private FileUsages(string fileUse, string fullFileUse)
{
FileUse = fileUse;
FullFileUse = fullFileUse;
}
public string FileUse { get; }
public string FullFileUse { get; }
public static readonly FileUsages PreservationMaster = new FileUsages("pres", "Preservation Master");
public static readonly FileUsages PreservationIntermediateMaster = new FileUsages("presInt", "Preservation Master - Intermediate");
public static readonly FileUsages ProductionMaster = new FileUsages("prod", "Production Master");
public static readonly FileUsages MezzanineFile = new FileUsages("mezz", "Mezzanine File");
public static readonly FileUsages AccessFile = new FileUsages("access", "Access File");
public static readonly FileUsages LabelImageFile = new FileUsages("label", "Label Image File");
public static readonly FileUsages XmlFile = new FileUsages("", "Xml File");
public static readonly FileUsages UnknownFile = new FileUsages("", "Raw object file");
public static readonly FileUsages PreservationToneReference = new FileUsages("presRef", "Preservation Master Tone Reference File");
public static readonly FileUsages PreservationIntermediateToneReference = new FileUsages("intRef", "Preservation Master - Intermediate Tone Reference File");
private static readonly List<FileUsages> AllImportableUsages = new List< FileUsages>
{
PreservationMaster,
PreservationIntermediateMaster,
PreservationToneReference,
PreservationIntermediateToneReference,
ProductionMaster,
MezzanineFile,
AccessFile,
LabelImageFile
};
public static FileUsages GetUsage(string fileUse)
{
var usage = AllImportableUsages.SingleOrDefault(
u => u.FileUse.Equals(fileUse, StringComparison.InvariantCultureIgnoreCase));
return usage ?? UnknownFile;
}
}
}
| apache-2.0 | C# |
f0ba7133263224c3dc8d1e5a52d9eaf1170d442c | Add db context constructor | Orationi/Master | Orationi.Master/Model/MasterContext.cs | Orationi.Master/Model/MasterContext.cs | using System.Data.Entity;
namespace Orationi.Master.Model
{
class MasterContext : DbContext
{
public DbSet<SlaveDescription> Slaves { get; set; }
public DbSet<ModuleDescription> Modules { get; set; }
public DbSet<ModuleVersion> ModuleVersions { get; set; }
public DbSet<SlaveModule> SlaveModules { get; set; }
public MasterContext() : base(typeof(MasterContext).Name)
{
}
}
}
| using System.Data.Entity;
namespace Orationi.Master.Model
{
class MasterContext : DbContext
{
public DbSet<SlaveDescription> Slaves { get; set; }
public DbSet<ModuleDescription> Modules { get; set; }
public DbSet<ModuleVersion> ModuleVersions { get; set; }
public DbSet<SlaveModule> SlaveModules { get; set; }
}
}
| mit | C# |
7ae5cdcf43296536b4ca8cf17893a9133ad40376 | 修复创建匹配器的错误! | huoxudong125/Zongsoft.CoreLibrary,Zongsoft/Zongsoft.CoreLibrary,MetSystem/Zongsoft.CoreLibrary | src/Services/MatcherAttribute.cs | src/Services/MatcherAttribute.cs | /*
* Authors:
* 钟峰(Popeye Zhong) <[email protected]>
*
* Copyright (C) 2010-2013 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Services
{
[AttributeUsage(AttributeTargets.Class)]
public class MatcherAttribute : Attribute
{
#region 成员字段
private Type _type;
#endregion
#region 构造函数
public MatcherAttribute(Type type)
{
if(type == null)
throw new ArgumentNullException("type");
if(!typeof(IMatcher).IsAssignableFrom(type))
throw new ArgumentException("The type is not a IMatcher.");
_type = type;
}
public MatcherAttribute(string typeName)
{
if(string.IsNullOrWhiteSpace(typeName))
throw new ArgumentNullException("typeName");
var type = Type.GetType(typeName, false);
if(type == null || !typeof(IMatcher).IsAssignableFrom(type))
throw new ArgumentException("The type is not a IMatcher.");
_type = type;
}
#endregion
#region 公共属性
public Type Type
{
get
{
return _type;
}
}
public IMatcher Matcher
{
get
{
if(_type == null)
return null;
return Activator.CreateInstance(_type) as IMatcher;
}
}
#endregion
}
}
| /*
* Authors:
* 钟峰(Popeye Zhong) <[email protected]>
*
* Copyright (C) 2010-2013 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Services
{
[AttributeUsage(AttributeTargets.Class)]
public class MatcherAttribute : Attribute
{
#region 成员字段
private Type _type;
#endregion
#region 构造函数
public MatcherAttribute(Type type)
{
if(type == null)
throw new ArgumentNullException("type");
if(!typeof(IMatcher).IsAssignableFrom(type))
throw new ArgumentException("The type is not a IMatcher.");
_type = type;
}
public MatcherAttribute(string typeName)
{
if(string.IsNullOrWhiteSpace(typeName))
throw new ArgumentNullException("typeName");
var type = Type.GetType(typeName, false);
if(type == null || !typeof(IMatcher).IsAssignableFrom(type))
throw new ArgumentException("The type is not a IMatcher.");
_type = type;
}
#endregion
#region 公共属性
public Type Type
{
get
{
return _type;
}
}
public IMatcher Matcher
{
get
{
if(_type == null)
return null;
return Activator.CreateInstance<IMatcher>();
}
}
#endregion
}
}
| lgpl-2.1 | C# |
3edcea6e8c5607bd1a4964201f4df60ac8583e61 | Revert "Using ternary instead of coalesce in fallback enumerable value selection" | agileobjects/AgileMapper | AgileMapper/ObjectPopulation/ExistingOrDefaultValueDataSourceFactory.cs | AgileMapper/ObjectPopulation/ExistingOrDefaultValueDataSourceFactory.cs | namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System.Linq.Expressions;
using DataSources;
using Members;
internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
{
public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();
public IDataSource Create(IMemberMappingData mappingData)
=> mappingData.MapperData.TargetMember.IsReadable
? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
: DefaultValueDataSourceFactory.Instance.Create(mappingData);
private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
{
public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
: base(mapperData.SourceMember, GetValue(mapperData), mapperData)
{
}
private static Expression GetValue(IMemberMapperData mapperData)
{
var existingValue = mapperData.GetTargetMemberAccess();
if (!mapperData.TargetMember.IsEnumerable)
{
return existingValue;
}
var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();
return Expression.Coalesce(existingValue, emptyEnumerable);
}
}
}
} | namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System.Linq.Expressions;
using DataSources;
using Extensions;
using Members;
internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
{
public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();
public IDataSource Create(IMemberMappingData mappingData)
=> mappingData.MapperData.TargetMember.IsReadable
? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
: DefaultValueDataSourceFactory.Instance.Create(mappingData);
private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
{
public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
: base(mapperData.SourceMember, GetValue(mapperData), mapperData)
{
}
private static Expression GetValue(IMemberMapperData mapperData)
{
var existingValue = mapperData.GetTargetMemberAccess();
if (!mapperData.TargetMember.IsEnumerable)
{
return existingValue;
}
var existingValueNotNull = existingValue.GetIsNotDefaultComparison();
var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();
return Expression.Condition(
existingValueNotNull,
existingValue,
emptyEnumerable,
existingValue.Type);
}
}
}
} | mit | C# |
7feb8bdec4f02eacebe7cfe21104a2b3ee0740d4 | Change option page position | Zvirja/ReSharperHelpers | AlexPovar.ReSharperHelpers/Settings/ReSharperHelpersOptionsPage.xaml.cs | AlexPovar.ReSharperHelpers/Settings/ReSharperHelpersOptionsPage.xaml.cs | using JetBrains.Annotations;
using JetBrains.DataFlow;
using JetBrains.ReSharper.Feature.Services.OptionPages.CodeEditing;
using JetBrains.UI.CrossFramework;
using JetBrains.UI.Options;
using JetBrains.UI.Options.OptionPages.ToolsPages;
namespace AlexPovar.ReSharperHelpers.Settings
{
[OptionsPage(PID, "Alex Povar ReSharper Helpers", typeof(MainThemedIcons.HelpersContextAction), ParentId = CodeEditingPage.PID)]
public partial class ReSharperHelpersOptionsPage : IOptionsPage
{
// ReSharper disable once InconsistentNaming
private const string PID = "AlexPovarReSharperHelpers";
public ReSharperHelpersOptionsPage([NotNull] Lifetime lifetime, [NotNull] OptionsSettingsSmartContext settingsSmart)
{
this.InitializeComponent();
this.DataContext = new ReSharperHelpersOptionsPageViewModel(lifetime, settingsSmart);
this.Control = this;
}
public bool OnOk() => true;
public bool ValidatePage() => true;
public EitherControl Control { get; }
public string Id => PID;
}
} | using JetBrains.Annotations;
using JetBrains.DataFlow;
using JetBrains.UI.CrossFramework;
using JetBrains.UI.Options;
using JetBrains.UI.Options.OptionPages.ToolsPages;
namespace AlexPovar.ReSharperHelpers.Settings
{
[OptionsPage(PID, "Alex Povar ReSharper Helpers", typeof(MainThemedIcons.HelpersContextAction), ParentId = ToolsPage.PID)]
public partial class ReSharperHelpersOptionsPage : IOptionsPage
{
// ReSharper disable once InconsistentNaming
private const string PID = "AlexPovarReSharperHelpers";
public ReSharperHelpersOptionsPage([NotNull] Lifetime lifetime, [NotNull] OptionsSettingsSmartContext settingsSmart)
{
this.InitializeComponent();
this.DataContext = new ReSharperHelpersOptionsPageViewModel(lifetime, settingsSmart);
this.Control = this;
}
public bool OnOk() => true;
public bool ValidatePage() => true;
public EitherControl Control { get; }
public string Id => PID;
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.