content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
/*
* Original author: Nicholas Shulman <nicksh .at. u.washington.edu>,
* MacCoss Lab, Department of Genome Sciences, UW
*
* Copyright 2018 University of Washington - Seattle, WA
*
* 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 Microsoft.VisualStudio.TestTools.UnitTesting;
using pwiz.Skyline.Model.DocSettings.AbsoluteQuantification;
using pwiz.SkylineTestUtil;
namespace pwiz.SkylineTest
{
[TestClass]
public class LinearInLogSpaceTest : AbstractUnitTest
{
/// <summary>
/// Verifies that for y=mx^p, the slope of the calibration curve is p, and the intercept is
/// log(m).
/// </summary>
[TestMethod]
public void TestLinearInLogSpace()
{
foreach (double factor in new[] {.5, 1.0, 2.0})
{
foreach (double power in new [] {-1.0, 0, 1.0, 2.5})
{
var points = Enumerable.Range(1, 10).Select(x => new WeightedPoint(x, factor * Math.Pow(x, power), 1)).ToArray();
var calibrationCurve = RegressionFit.LINEAR_IN_LOG_SPACE.Fit(points);
Assert.AreEqual(power, calibrationCurve.Slope.Value, .00001);
Assert.AreEqual(Math.Log(factor), calibrationCurve.Intercept.Value, .00001);
}
}
}
}
}
| 37.235294 | 133 | 0.639284 | [
"Apache-2.0"
] | austinkeller/pwiz | pwiz_tools/Skyline/Test/LinearInLogSpaceTest.cs | 1,901 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
namespace StoredProcedureEFCore
{
internal class StoredProcBuilder : IStoredProcBuilder
{
private const string RetParamName = "_retParam";
private readonly DbCommand _cmd;
public StoredProcBuilder(DbContext ctx, string name)
{
if (name is null)
throw new ArgumentNullException(nameof(name));
DbCommand cmd = ctx.Database.GetDbConnection().CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = name;
cmd.Transaction = ctx.Database.CurrentTransaction?.GetDbTransaction();
cmd.CommandTimeout = ctx.Database.GetCommandTimeout().GetValueOrDefault(cmd.CommandTimeout);
_cmd = cmd;
}
public IStoredProcBuilder AddParam<T>(string name, T val)
{
AddParamInner(name, val, ParameterDirection.Input);
return this;
}
public IStoredProcBuilder AddParam<T>(string name, out IOutParam<T> outParam)
{
outParam = AddOutputParamInner(name, default(T), ParameterDirection.Output);
return this;
}
public IStoredProcBuilder AddParam<T>(string name, T val, out IOutParam<T> outParam, int size = 0, byte precision = 0, byte scale = 0)
{
outParam = AddOutputParamInner(name, val, ParameterDirection.InputOutput, size, precision, scale);
return this;
}
public IStoredProcBuilder AddParam<T>(string name, out IOutParam<T> outParam, int size = 0, byte precision = 0, byte scale = 0)
{
outParam = AddOutputParamInner(name, default(T), ParameterDirection.Output, size, precision, scale);
return this;
}
public IStoredProcBuilder AddParam<T>(string name, T val, out IOutParam<T> outParam)
{
outParam = AddOutputParamInner(name, val, ParameterDirection.InputOutput);
return this;
}
public IStoredProcBuilder AddParam(DbParameter parameter)
{
if (parameter == null)
{
throw new ArgumentNullException(nameof(parameter));
}
_cmd.Parameters.Add(parameter);
return this;
}
public IStoredProcBuilder ReturnValue<T>(out IOutParam<T> retParam)
{
retParam = AddOutputParamInner(RetParamName, default(T), ParameterDirection.ReturnValue);
return this;
}
public IStoredProcBuilder SetTimeout(int timeout)
{
_cmd.CommandTimeout = timeout;
return this;
}
public void Exec(Action<DbDataReader> action)
{
if (action is null)
throw new ArgumentNullException(nameof(action));
bool ownsConnection = false;
try
{
ownsConnection = OpenConnection();
using (DbDataReader r = _cmd.ExecuteReader())
{
action(r);
}
}
finally
{
if (ownsConnection)
CloseConnection();
Dispose();
}
}
public Task ExecAsync(Func<DbDataReader, Task> action)
{
return ExecAsync(action, CancellationToken.None);
}
public async Task ExecAsync(Func<DbDataReader, Task> action, CancellationToken cancellationToken)
{
if (action is null)
throw new ArgumentNullException(nameof(action));
bool ownsConnection = false;
try
{
ownsConnection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
using (DbDataReader r = await _cmd.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
{
try
{
await action(r).ConfigureAwait(false);
}
catch (Exception)
{
// In case the action bombs out, cancel the command and rethrow to propagate the actual action
// exception. If we don't cancel the command, we will be stuck on disposing of the reader until
// the sproc completes, even though the action has already thrown an exception. This is also the
// case when the cancellation token is cancelled after the action exception but before the sproc
// completes: we will still be stuck on disposing of the reader until the sproc completes. This
// is caused by the fact that DbDataReader.Dispose does not react to cancellations and simply
// waits for the sproc to complete. // The only way to cancel the execution when the reader has
// been engaged and the action has thrown, is to cancel the command.
_cmd.Cancel();
throw;
}
}
}
finally
{
if (ownsConnection)
CloseConnection();
Dispose();
}
}
public int ExecNonQuery()
{
bool ownsConnection = false;
try
{
ownsConnection = OpenConnection();
return _cmd.ExecuteNonQuery();
}
finally
{
if (ownsConnection)
CloseConnection();
Dispose();
}
}
public Task<int> ExecNonQueryAsync()
{
return ExecNonQueryAsync(CancellationToken.None);
}
public async Task<int> ExecNonQueryAsync(CancellationToken cancellationToken)
{
bool ownsConnection = false;
try
{
ownsConnection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
return await _cmd.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
if (ownsConnection)
CloseConnection();
Dispose();
}
}
public void ExecScalar<T>(out T val)
{
bool ownsConnection = false;
try
{
ownsConnection = OpenConnection();
object scalar = _cmd.ExecuteScalar();
val = DefaultIfDBNull<T>(scalar);
}
finally
{
if (ownsConnection)
CloseConnection();
Dispose();
}
}
public Task ExecScalarAsync<T>(Action<T> action)
{
return ExecScalarAsync(action, CancellationToken.None);
}
public async Task ExecScalarAsync<T>(Action<T> action, CancellationToken cancellationToken)
{
bool ownsConnection = false;
try
{
ownsConnection = await OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
object scalar = await _cmd.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
T val = DefaultIfDBNull<T>(scalar);
action(val);
}
finally
{
if (ownsConnection)
CloseConnection();
Dispose();
}
}
public void Dispose()
{
_cmd.Dispose();
}
private OutputParam<T> AddOutputParamInner<T>(string name, T val, ParameterDirection direction, int size = 0, byte precision = 0, byte scale = 0)
{
DbParameter param = AddParamInner(name, val, direction, size, precision, scale);
return new OutputParam<T>(param);
}
private DbParameter AddParamInner<T>(string name, T val, ParameterDirection direction, int size = 0, byte precision = 0, byte scale = 0)
{
if (name is null)
throw new ArgumentNullException(nameof(name));
DbParameter param = _cmd.CreateParameter();
param.ParameterName = name;
param.Value = (object) val ?? DBNull.Value;
param.Direction = direction;
param.DbType = DbTypeConverter.ConvertToDbType<T>();
param.Size = size;
param.Precision = precision;
param.Scale = scale;
_cmd.Parameters.Add(param);
return param;
}
private bool OpenConnection()
{
if (_cmd.Connection.State == ConnectionState.Closed)
{
_cmd.Connection.Open();
return true;
}
return false;
}
private async Task<bool> OpenConnectionAsync(CancellationToken cancellationToken)
{
if (_cmd.Connection.State == ConnectionState.Closed)
{
await _cmd.Connection.OpenAsync(cancellationToken).ConfigureAwait(false);
return true;
}
return false;
}
private void CloseConnection()
{
_cmd.Connection.Close();
}
private static T DefaultIfDBNull<T>(object o)
{
return o == DBNull.Value ? default(T) : (T) o;
}
}
}
| 34.482759 | 154 | 0.5254 | [
"MIT"
] | IsraelBoiko/StoredProcedureEFCore | StoredProcedureEFCore/StoredProcBuilder.cs | 10,002 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace SmartStore.Persistance.Migrations
{
public partial class InitialCreate31 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Category",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(maxLength: 400, nullable: true),
Description = table.Column<string>(nullable: true),
ParentCategoryId = table.Column<int>(nullable: false),
Published = table.Column<bool>(nullable: false),
CreatedOnUtc = table.Column<DateTime>(nullable: false),
UpdatedOnUtc = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Category", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Manufacturer",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(maxLength: 400, nullable: false),
Description = table.Column<string>(nullable: true),
Published = table.Column<bool>(nullable: false),
CreatedOnUtc = table.Column<DateTime>(nullable: false),
UpdatedOnUtc = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufacturer", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Product",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(maxLength: 400, nullable: true),
Description = table.Column<string>(nullable: true),
BarCode = table.Column<string>(maxLength: 400, nullable: true),
StockQuantity = table.Column<int>(nullable: false),
Price = table.Column<decimal>(type: "decimal(18,4)", nullable: false),
Weight = table.Column<decimal>(type: "decimal(18,4)", nullable: false),
Length = table.Column<decimal>(type: "decimal(18,4)", nullable: false),
Width = table.Column<decimal>(type: "decimal(18,4)", nullable: false),
Height = table.Column<decimal>(type: "decimal(18,4)", nullable: false),
Published = table.Column<bool>(nullable: false),
CreatedOnUtc = table.Column<DateTime>(nullable: false),
UpdatedOnUtc = table.Column<DateTime>(nullable: false),
CategoryId = table.Column<int>(nullable: true),
ManufacturerId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Product", x => x.Id);
table.ForeignKey(
name: "FK_Product_Category_CategoryId",
column: x => x.CategoryId,
principalTable: "Category",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Product_Manufacturer_ManufacturerId",
column: x => x.ManufacturerId,
principalTable: "Manufacturer",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Product_CategoryId",
table: "Product",
column: "CategoryId");
migrationBuilder.CreateIndex(
name: "IX_Product_ManufacturerId",
table: "Product",
column: "ManufacturerId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Product");
migrationBuilder.DropTable(
name: "Category");
migrationBuilder.DropTable(
name: "Manufacturer");
}
}
}
| 46.407407 | 125 | 0.524541 | [
"MIT"
] | SebastianRuzanowski/Ubiquitous | src/Adapters/U.SmartStoreAdapter/U.SmartStoreAdapter.Persistance/Migrations/20200525145136_InitialCreate31.cs | 5,014 | C# |
// Copyright 2018 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;
namespace PPWCode.Vernacular.Persistence.IV
{
public interface ITimeProvider
{
DateTime Now { get; }
DateTime UtcNow { get; }
}
}
| 34.454545 | 75 | 0.728232 | [
"Apache-2.0"
] | peopleware/net-ppwcode-vernacular-persistence | src/IV/Interfaces/ITimeProvider.cs | 760 | C# |
using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FilterApp
{
public partial class UserControl2 : UserControl
{
Capture video;
Image<Bgr, Byte> currentFrame;
Bitmap temp;
string selected;
public UserControl2()
{
InitializeComponent();
cbFiltervid.Items.Add("Laplaciano");
cbFiltervid.Items.Add("Substracción de Media");
cbFiltervid.Items.Add("Direccional NS");
cbFiltervid.Items.Add("Sobel");
cbFiltervid.Items.Add("Menos-Laplaciano");
cbFiltervid.Items.Add("Negativo");
}
private void btnImpvid_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Files (*.mp4)|*.mp4";
if (ofd.ShowDialog() == DialogResult.OK)
{
video = new Capture(ofd.FileName);
currentFrame = video.QueryFrame().Resize(700, 394, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
imageBox1.Image = currentFrame;
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (currentFrame != null)
{
timer1.Enabled = true;
}
else
{
MessageBox.Show("No se agregó ningún video.", "Advertencia");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
currentFrame = video.QueryFrame();
if (currentFrame != null)
{
if (selected == null)
{
imageBox1.Image = currentFrame;
}
else
{
temp = currentFrame.Bitmap;
var classVideo = new Video(temp, imageBox1);
classVideo.addFilter(selected);
}
}
else
{
timer1.Enabled = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void btnAddvid_Click(object sender, EventArgs e)
{
selected = this.cbFiltervid.GetItemText(this.cbFiltervid.SelectedItem);
lbFiltervid.Items.Add(selected);
}
private void btnClearvid_Click(object sender, EventArgs e)
{
lbFiltervid.Items.Clear();
selected = null;
}
}
}
| 27.829787 | 104 | 0.507645 | [
"Apache-2.0"
] | Diego1803631/Procesamiento | FilterApp/UserControl2.cs | 2,621 | C# |
namespace UrbanSolution.Web.Areas.Manager.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using UrbanSolution.Models;
using static UrbanSolutionUtilities.WebConstants;
[Area(ManagerArea)]
[Authorize(Roles = ManagerRole)]
public class BaseController : Controller
{
protected BaseController(UserManager<User> userManager)
{
this.UserManager = userManager;
}
protected UserManager<User> UserManager { get; }
}
} | 27.285714 | 63 | 0.699825 | [
"MIT"
] | DareDevil23/UrbanSolution | UrbanSolution.Web/Areas/Manager/Controllers/BaseController.cs | 575 | C# |
/***************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
This code is licensed under the Visual Studio SDK license terms.
THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
***************************************************************************/
using System;
using System.Collections.Generic;
using Microsoft.Build.Evaluation;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Samples.VisualStudio.CodeSweep.UnitTests
{
/// <summary>
///This is a test class for CodeSweep.VSPackage.BackgroundScanner and is intended
///to contain all CodeSweep.VSPackage.BackgroundScanner Unit Tests
///</summary>
[TestClass()]
public class BackgroundScannerTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//
static MockServiceProvider _serviceProvider;
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
if (CodeSweep.VSPackage.Factory_Accessor.ServiceProvider == null)
{
_serviceProvider = new MockServiceProvider();
CodeSweep.VSPackage.Factory_Accessor.ServiceProvider = _serviceProvider;
}
else
{
_serviceProvider = CodeSweep.VSPackage.Factory_Accessor.ServiceProvider as MockServiceProvider;
}
CodeSweep.VSPackage.Factory_Accessor.GetBuildManager().CreatePerUserFilesAsNecessary();
}
//Use ClassCleanup to run code after all tests in a class have run
//
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//
[TestCleanup()]
public void MyTestCleanup()
{
// If the test left the scanner running, stop it now.
if (_scanner != null)
{
_scanner.StopIfRunning(true);
_scanner = null;
}
Utilities.CleanUpTempFiles();
Utilities.RemoveCommandHandlers(_serviceProvider);
}
//
#endregion
CodeSweep.VSPackage.BackgroundScanner_Accessor _scanner;
CodeSweep.VSPackage.BackgroundScanner_Accessor GetScanner()
{
_scanner = new CodeSweep.VSPackage.BackgroundScanner_Accessor(_serviceProvider);
return _scanner;
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
[ExpectedException(typeof(ArgumentNullException))]
public void CreateWithNullArg()
{
IServiceProvider provider = null;
object target = new CodeSweep.VSPackage.BackgroundScanner_Accessor(provider);
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
[ExpectedException(typeof(ArgumentNullException))]
public void StartWithNullArg()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
accessor.Start(null);
}
string CreateMinimalTermTableFile()
{
return Utilities.CreateTermTable(new string[] { "foo" });
}
//TODO: This test is subject to timing issues where the build finishes before checking
//the properties of the object under test. Need to fix this issue to enable this unit test.
[Ignore()]
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void StartWhenAlreadyRunning()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
Project project = Utilities.SetupMSBuildProject(new string[] { Utilities.CreateBigFile() }, new string[] { CreateMinimalTermTableFile() });
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
bool thrown = false;
accessor.Start(new IVsProject[] { vsProject });
try
{
accessor.Start(new IVsProject[] { new MockIVsProject(project.FullPath) });
}
catch (InvalidOperationException)
{
thrown = true;
}
Utilities.WaitForStop(accessor);
Assert.IsTrue(thrown, "Start did not throw InvalidOperationException with scan already running.");
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void StartOnProjectWithoutScannerTask()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
Project project = Utilities.SetupMSBuildProject();
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
// TODO: if we could, it would be good to make sure the Started event isn't fired --
// but apparently the VS test framework doesn't support events.
accessor.Start(new IVsProject[] { vsProject });
Assert.IsFalse(accessor.IsRunning, "IsRunning returned true after Start() called with project that does not contain a scanner config.");
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void StartUpdatesTaskList()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
// Set up events so we know when the task list is called.
Guid activeProvider = Guid.Empty;
MockTaskList taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as MockTaskList;
taskList.OnSetActiveProvider += delegate(object sender, MockTaskList.SetActiveProviderArgs args) { activeProvider = args.ProviderGuid; };
bool cmdPosted = false;
MockShell shell = _serviceProvider.GetService(typeof(SVsUIShell)) as MockShell;
shell.OnPostExecCommand += delegate(object sender, MockShell.PostExecCommandArgs args)
{
if (args.Group == VSConstants.GUID_VSStandardCommandSet97 && args.ID == (uint)VSConstants.VSStd97CmdID.TaskListWindow)
{
cmdPosted = true;
}
};
Project project = Utilities.SetupMSBuildProject(new string[] { Utilities.CreateBigFile() }, new string[] { CreateMinimalTermTableFile() });
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject });
Assert.IsTrue(cmdPosted, "Start did not activate the task list.");
Assert.AreEqual(new Guid("{9ACC41B7-15B4-4dd7-A0F3-0A935D5647F3}"), activeProvider, "Start did not select the correct task bucket.");
Utilities.WaitForStop(accessor);
}
//TODO: This test is subject to timing issues where the build finishes before checking
//the properties of the object under test. Need to fix this issue to enable this unit test.
[Ignore()]
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void ProgressShowsInStatusBar()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
bool inProgress = false;
string label = null;
uint complete = 0;
uint total = 0;
MockStatusBar statusBar = _serviceProvider.GetService(typeof(SVsStatusbar)) as MockStatusBar;
statusBar.OnProgress += delegate(object sender, MockStatusBar.ProgressArgs args)
{
inProgress = (args.InProgress == 0) ? false : true;
label = args.Label;
complete = args.Complete;
total = args.Total;
};
Project project = Utilities.SetupMSBuildProject(new string[] { Utilities.CreateBigFile() }, new string[] { CreateMinimalTermTableFile() });
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject });
Assert.IsTrue(inProgress, "Start did not show progress in status bar.");
Assert.AreEqual((uint)0, complete, "Scan did not start with zero complete.");
// TODO: if time allows: scan several files, detect (by task list updates) when each one is done, and check to make sure the status bar has been updated accordingly.
Utilities.WaitForStop(accessor);
Assert.IsFalse(inProgress, "Progress bar not cleared when scan ends.");
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void TaskListIsUpdated()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
List<int> resultCounts = new List<int>();
MockTaskList taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as MockTaskList;
taskList.OnRefreshTasks += delegate(object sender, MockTaskList.RefreshTasksArgs args)
{
resultCounts.Add(Utilities.TasksOfProvider(args.Provider).Count);
};
string firstFile = Utilities.CreateTempTxtFile("foo abc foo def foo");
string secondFile = Utilities.CreateTempTxtFile("bar bar bar floop doop bar");
string termTable1 = Utilities.CreateTermTable(new string[] { "foo", "bar" });
string termTable2 = Utilities.CreateTermTable(new string[] { "floop" });
Project project1 = Utilities.SetupMSBuildProject(new string[] { firstFile, secondFile }, new string[] { termTable1, termTable2 });
MockIVsProject vsProject1 = Utilities.RegisterProjectWithMocks(project1, _serviceProvider);
string thirdFile = Utilities.CreateTempTxtFile("blarg");
string termTable3 = Utilities.CreateTermTable(new string[] { "blarg" });
Project project2 = Utilities.SetupMSBuildProject(new string[] { thirdFile }, new string[] { termTable3 });
MockIVsProject vsProject2 = Utilities.RegisterProjectWithMocks(project2, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject1, vsProject2 });
Utilities.WaitForStop(accessor);
Assert.AreEqual(4, resultCounts.Count, "Task list did not recieve correct number of updates.");
Assert.AreEqual(0, resultCounts[0], "Number of hits in first update is wrong.");
Assert.AreEqual(3, resultCounts[1], "Number of hits in second update is wrong.");
Assert.AreEqual(3 + 5, resultCounts[2], "Number of hits in third update is wrong.");
Assert.AreEqual(3 + 5 + 1, resultCounts[3], "Number of hits in fourth update is wrong.");
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void RepeatLastProducesSameResultsAsPreviousScan()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
string firstFile = Utilities.CreateTempTxtFile("foo abc foo def foo");
string secondFile = Utilities.CreateTempTxtFile("bar bar bar floop doop bar");
string termTable1 = Utilities.CreateTermTable(new string[] { "foo", "bar" });
string termTable2 = Utilities.CreateTermTable(new string[] { "floop" });
Project project1 = Utilities.SetupMSBuildProject(new string[] { firstFile, secondFile }, new string[] { termTable1, termTable2 });
MockIVsProject vsProject1 = Utilities.RegisterProjectWithMocks(project1, _serviceProvider);
string thirdFile = Utilities.CreateTempTxtFile("blarg");
string termTable3 = Utilities.CreateTermTable(new string[] { "blarg" });
Project project2 = Utilities.SetupMSBuildProject(new string[] { thirdFile }, new string[] { termTable3 });
MockIVsProject vsProject2 = Utilities.RegisterProjectWithMocks(project2, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject1, vsProject2 });
Utilities.WaitForStop(accessor);
List<int> resultCounts = new List<int>();
MockTaskList taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as MockTaskList;
taskList.OnRefreshTasks += delegate(object sender, MockTaskList.RefreshTasksArgs args)
{
resultCounts.Add(Utilities.TasksOfProvider(args.Provider).Count);
};
accessor.RepeatLast();
Utilities.WaitForStop(accessor);
Assert.AreEqual(4, resultCounts.Count, "Task list did not recieve correct number of updates.");
Assert.AreEqual(0, resultCounts[0], "Number of hits in first update is wrong.");
Assert.AreEqual(3, resultCounts[1], "Number of hits in second update is wrong.");
Assert.AreEqual(3 + 5, resultCounts[2], "Number of hits in third update is wrong.");
Assert.AreEqual(3 + 5 + 1, resultCounts[3], "Number of hits in fourth update is wrong.");
}
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
[ExpectedException(typeof(InvalidOperationException))]
public void RepeatLastWithNoPreviousScan()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
accessor.RepeatLast();
}
//TODO: This test is subject to timing issues where the build finishes before checking
//the properties of the object under test. Need to fix this issue to enable this unit test.
[Ignore()]
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
[ExpectedException(typeof(InvalidOperationException))]
public void RepeatLastWhenAlreadyRunning()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
Project project = Utilities.SetupMSBuildProject(new string[] { Utilities.CreateBigFile() }, new string[] { CreateMinimalTermTableFile() });
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject });
accessor.RepeatLast();
}
//TODO: This test is subject to timing issues where the build finishes before checking
//the properties of the object under test. Need to fix this issue to enable this unit test.
[Ignore()]
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void StopStopsScanBeforeNextFile()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
int refreshes = 0;
MockTaskList taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as MockTaskList;
taskList.OnRefreshTasks +=
delegate(object sender, MockTaskList.RefreshTasksArgs args)
{
++refreshes;
};
string firstFile = Utilities.CreateBigFile();
string secondFile = Utilities.CreateTempTxtFile("bar bar bar floop doop bar");
string termTable = Utilities.CreateTermTable(new string[] { "foo", "bar" });
Project project = Utilities.SetupMSBuildProject(new string[] { firstFile, secondFile }, new string[] { termTable });
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject });
accessor.StopIfRunning(true);
// There should be one update, when the task list was initially cleared.
Assert.AreEqual(1, refreshes, "Stop did not stop scan before next file.");
}
//TODO: This test is subject to timing issues where the build finishes before checking
//the properties of the object under test. Need to fix this issue to enable this unit test.
[Ignore()]
[DeploymentItem("VsPackage.dll")]
[TestMethod()]
public void IsRunning()
{
CodeSweep.VSPackage.BackgroundScanner_Accessor accessor = GetScanner();
int refreshes = 0;
MockTaskList taskList = _serviceProvider.GetService(typeof(SVsTaskList)) as MockTaskList;
taskList.OnRefreshTasks += delegate(object sender, MockTaskList.RefreshTasksArgs args) { ++refreshes; };
string firstFile = Utilities.CreateBigFile();
string secondFile = Utilities.CreateTempTxtFile("bar bar bar floop doop bar");
string termTable = Utilities.CreateTermTable(new string[] { "foo", "bar" });
Project project = Utilities.SetupMSBuildProject(new string[] { firstFile, secondFile }, new string[] { termTable });
MockIVsProject vsProject = Utilities.RegisterProjectWithMocks(project, _serviceProvider);
accessor.Start(new IVsProject[] { vsProject });
Assert.IsTrue(accessor.IsRunning, "IsRunning was not true after Start.");
accessor.StopIfRunning(false);
Assert.IsTrue(accessor.IsRunning, "IsRunning was not true after Stop called while scan is still running.");
}
}
}
| 45.276699 | 178 | 0.620993 | [
"Apache-2.0"
] | LiveMirror/Visual-Studio-2010-SDK-Samples | Code Sweep/C#,C++/TDD/BackgroundScannerTest.cs | 18,656 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using Dbosoft.IdentityServer.EfCore.Storage.Mappers;
using Dbosoft.IdentityServer.Storage.Models;
using FluentAssertions;
using Xunit;
namespace Dbosoft.IdentityServer.EfCore.Storage.UnitTests.Mappers
{
public class PersistedGrantMappersTests
{
[Fact]
public void PersistedGrantAutomapperConfigurationIsValid()
{
PersistedGrantMappers.Mapper.ConfigurationProvider.AssertConfigurationIsValid<PersistedGrantMapperProfile>();
}
[Fact]
public void CanMap()
{
var model = new PersistedGrant()
{
ConsumedTime = new System.DateTime(2020, 02, 03, 4, 5, 6)
};
var mappedEntity = model.ToEntity();
mappedEntity.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6));
var mappedModel = mappedEntity.ToModel();
mappedModel.ConsumedTime.Value.Should().Be(new System.DateTime(2020, 02, 03, 4, 5, 6));
Assert.NotNull(mappedModel);
Assert.NotNull(mappedEntity);
}
}
} | 33.973684 | 121 | 0.642912 | [
"Apache-2.0"
] | dbosoft/IdentityServer | tests/IdentityServer.EfCore.Storage.UnitTests/Mappers/PersistedGrantMappersTests.cs | 1,293 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WatsonTcp;
namespace TestServer
{
internal class TestServer
{
private static string serverIp = "";
private static int serverPort = 0;
private static bool useSsl = false;
private static WatsonTcpServer<BlankMetadata> server = null;
private static string certFile = "";
private static string certPass = "";
private static bool debugMessages = true;
private static bool acceptInvalidCerts = true;
private static bool mutualAuthentication = true;
private static string lastIpPort = null;
private static void Main(string[] args)
{
serverIp = InputString("Server IP:", "127.0.0.1", false);
serverPort = InputInteger("Server port:", 9000, true, false);
useSsl = InputBoolean("Use SSL:", false);
try
{
if (!useSsl)
{
server = new WatsonTcpServer<BlankMetadata>(serverIp, serverPort);
}
else
{
certFile = InputString("Certificate file:", "test.pfx", false);
certPass = InputString("Certificate password:", "password", false);
acceptInvalidCerts = InputBoolean("Accept invalid certs:", true);
mutualAuthentication = InputBoolean("Mutually authenticate:", false);
server = new WatsonTcpServer<BlankMetadata>(serverIp, serverPort, certFile, certPass);
server.AcceptInvalidCertificates = acceptInvalidCerts;
server.MutuallyAuthenticate = mutualAuthentication;
}
server.ClientConnected += ClientConnected;
server.ClientDisconnected += ClientDisconnected;
server.MessageReceived += MessageReceived;
server.SyncRequestReceived = SyncRequestReceived;
// server.PresharedKey = "0000000000000000";
// server.IdleClientTimeoutSeconds = 10;
server.Logger = Logger;
server.DebugMessages = debugMessages;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return;
}
// server.Start();
Task serverStart = server.StartAsync();
bool runForever = true;
List<string> clients;
string ipPort;
BlankMetadata metadata;
bool success = false;
while (runForever)
{
string userInput = InputString("Command [? for help]:", null, false);
switch (userInput)
{
case "?":
Console.WriteLine("Available commands:");
Console.WriteLine(" ? help (this menu)");
Console.WriteLine(" q quit");
Console.WriteLine(" cls clear screen");
Console.WriteLine(" list list clients");
Console.WriteLine(" dispose dispose of the connection");
Console.WriteLine(" send send message to client");
Console.WriteLine(" send md send message with metadata to client");
Console.WriteLine(" sendasync send message to a client asynchronously");
Console.WriteLine(" sendasync md send message with metadata to a client asynchronously");
Console.WriteLine(" sendandwait send message and wait for a response");
Console.WriteLine(" sendempty send empty message with metadata");
Console.WriteLine(" sendandwait empty send empty message with metadata and wait for a response");
Console.WriteLine(" remove disconnect client");
Console.WriteLine(" psk set preshared key");
Console.WriteLine(" stats display server statistics");
Console.WriteLine(" stats reset reset statistics other than start time and uptime");
Console.WriteLine(" comp set the compression type, currently: " + server.Compression.ToString());
Console.WriteLine(" debug enable/disable debug (currently " + server.DebugMessages + ")");
break;
case "q":
runForever = false;
break;
case "cls":
Console.Clear();
break;
case "list":
clients = server.ListClients().ToList();
if (clients != null && clients.Count > 0)
{
Console.WriteLine("Clients");
foreach (string curr in clients)
{
Console.WriteLine(" " + curr);
}
}
else
{
Console.WriteLine("None");
}
break;
case "dispose":
server.Dispose();
break;
case "send":
ipPort = InputString("IP:port:", lastIpPort, false);
userInput = InputString("Data:", null, false);
if (!server.Send(ipPort, userInput)) Console.WriteLine("Failed");
break;
case "send md":
ipPort = InputString("IP:port:", lastIpPort, false);
userInput = InputString("Data:", null, false);
metadata = InputDictionary();
if (!server.Send(ipPort, metadata, userInput)) Console.WriteLine("Failed");
Console.WriteLine(success);
break;
case "send md large":
ipPort = InputString("IP:port:", lastIpPort, false);
metadata = new BlankMetadata();
if (!server.Send(ipPort, metadata, "Hello!")) Console.WriteLine("Failed");
break;
case "sendasync":
ipPort = InputString("IP:port:", lastIpPort, false);
userInput = InputString("Data:", null, false);
success = server.SendAsync(ipPort, Encoding.UTF8.GetBytes(userInput)).Result;
if (!success) Console.WriteLine("Failed");
break;
case "sendasync md":
ipPort = InputString("IP:port:", lastIpPort, false);
userInput = InputString("Data:", null, false);
metadata = InputDictionary();
success = server.SendAsync(ipPort, metadata, Encoding.UTF8.GetBytes(userInput)).Result;
if (!success) Console.WriteLine("Failed");
break;
case "sendandwait":
SendAndWait();
break;
case "sendempty":
ipPort = InputString("IP:port:", lastIpPort, false);
metadata = InputDictionary();
if (!server.Send(ipPort, metadata)) Console.WriteLine("Failed");
break;
case "sendandwait empty":
SendAndWaitEmpty();
break;
case "remove":
ipPort = InputString("IP:port:", lastIpPort, false);
server.DisconnectClient(ipPort);
break;
case "psk":
server.PresharedKey = InputString("Preshared key:", "1234567812345678", false);
break;
case "stats":
Console.WriteLine(server.Stats.ToString());
break;
case "stats reset":
server.Stats.Reset();
break;
case "comp":
server.Compression = (CompressionType)(Enum.Parse(typeof(CompressionType), InputString("Compression [None|Default|Gzip]:", "None", false)));
break;
case "debug":
server.DebugMessages = !server.DebugMessages;
Console.WriteLine("Debug set to: " + server.DebugMessages);
break;
default:
break;
}
}
}
private static bool InputBoolean(string question, bool yesDefault)
{
Console.Write(question);
if (yesDefault) Console.Write(" [Y/n]? ");
else Console.Write(" [y/N]? ");
string userInput = Console.ReadLine();
if (String.IsNullOrEmpty(userInput))
{
if (yesDefault) return true;
return false;
}
userInput = userInput.ToLower();
if (yesDefault)
{
if (
(String.Compare(userInput, "n") == 0)
|| (String.Compare(userInput, "no") == 0)
)
{
return false;
}
return true;
}
else
{
if (
(String.Compare(userInput, "y") == 0)
|| (String.Compare(userInput, "yes") == 0)
)
{
return true;
}
return false;
}
}
private static string InputString(string question, string defaultAnswer, bool allowNull)
{
while (true)
{
Console.Write(question);
if (!String.IsNullOrEmpty(defaultAnswer))
{
Console.Write(" [" + defaultAnswer + "]");
}
Console.Write(" ");
string userInput = Console.ReadLine();
if (String.IsNullOrEmpty(userInput))
{
if (!String.IsNullOrEmpty(defaultAnswer)) return defaultAnswer;
if (allowNull) return null;
else continue;
}
return userInput;
}
}
private static int InputInteger(string question, int defaultAnswer, bool positiveOnly, bool allowZero)
{
while (true)
{
Console.Write(question);
Console.Write(" [" + defaultAnswer + "] ");
string userInput = Console.ReadLine();
if (String.IsNullOrEmpty(userInput))
{
return defaultAnswer;
}
int ret = 0;
if (!Int32.TryParse(userInput, out ret))
{
Console.WriteLine("Please enter a valid integer.");
continue;
}
if (ret == 0)
{
if (allowZero)
{
return 0;
}
}
if (ret < 0)
{
if (positiveOnly)
{
Console.WriteLine("Please enter a value greater than zero.");
continue;
}
}
return ret;
}
}
private static BlankMetadata InputDictionary()
{
Console.WriteLine("Build metadata, press ENTER on 'Key' to exit");
return new BlankMetadata();
// TODO: Reimplement me
}
private static void ClientConnected(object sender, ClientConnectedEventArgs args)
{
lastIpPort = args.IpPort;
Console.WriteLine("Client connected: " + args.IpPort);
// Console.WriteLine("Disconnecting: " + args.IpPort);
// server.DisconnectClient(args.IpPort);
}
private static void ClientDisconnected(object sender, ClientDisconnectedEventArgs args)
{
Console.WriteLine("Client disconnected: " + args.IpPort + ": " + args.Reason.ToString());
}
private static void MessageReceived(object sender, MessageReceivedFromClientEventArgs<BlankMetadata> args)
{
lastIpPort = args.IpPort;
Console.Write("Message received from " + args.IpPort + ": ");
if (args.Data != null) Console.WriteLine(Encoding.UTF8.GetString(args.Data));
else Console.WriteLine("[null]");
}
private static SyncResponse<BlankMetadata> SyncRequestReceived(SyncRequest<BlankMetadata> req)
{
Console.Write("Synchronous request received from " + req.IpPort + ": ");
if (req.Data != null) Console.WriteLine(Encoding.UTF8.GetString(req.Data));
else Console.WriteLine("[null]");
var retMetadata = new BlankMetadata();
// Uncomment to test timeout
// Task.Delay(10000).Wait();
Console.WriteLine("Sending synchronous response");
return new SyncResponse<BlankMetadata>(req, retMetadata, "Here is your response!");
}
private static void SendAndWait()
{
string ipPort = InputString("IP:port:", lastIpPort, false);
string userInput = InputString("Data:", null, false);
int timeoutMs = InputInteger("Timeout (milliseconds):", 5000, true, false);
try
{
SyncResponse<BlankMetadata> resp = server.SendAndWait(ipPort, timeoutMs, userInput);
Console.WriteLine("Response: " + Encoding.UTF8.GetString(resp.Data));
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
private static void SendAndWaitEmpty()
{
string ipPort = InputString("IP:port:", lastIpPort, false);
int timeoutMs = InputInteger("Timeout (milliseconds):", 5000, true, false);
var dict = new BlankMetadata();
try
{
var resp = server.SendAndWait(ipPort, dict, timeoutMs);
Console.WriteLine("Response: " + Encoding.UTF8.GetString(resp.Data));
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
private static void Logger(string msg)
{
Console.WriteLine(msg);
}
}
} | 38.566502 | 164 | 0.463022 | [
"MIT"
] | AdamFrisby/WatsonTcp | Test.Server/Program.cs | 15,660 | C# |
using AutoMapper;
using ParkingSlotAPI.Controllers;
using ParkingSlotAPI.Database;
using ParkingSlotAPI.Entities;
using ParkingSlotAPI.Helpers;
using ParkingSlotAPI.Models;
using ParkingSlotAPI.Services;
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace ParkingSlotAPI.Repository
{
public interface IParkingRepository
{
PagedList<Carpark> GetCarparks(CarparkResourceParameters carparkResourceParameters);
Carpark GetCarpark(Guid carparkId);
IEnumerable<Carpark> GetAllCarparks();
void AddCarpark(Carpark carpark);
void DeleteCarpark(Carpark carpark);
void UpdateCarpark(Carpark carpark);
void UpdateCarparks(List<Carpark> carparks);
void SaveChanges();
}
public class ParkingRepository : IParkingRepository
{
private ParkingContext _context;
private IMapper _mapper;
private ICarparkRatesRepository _carparkRatesRepository;
private readonly IPropertyMappingService _propertyMappingService;
public ParkingRepository(ParkingContext context, IMapper mapper, ICarparkRatesRepository carparkRatesRepository, IPropertyMappingService propertyMappingService)
{
_context = context;
_mapper = mapper;
_carparkRatesRepository = carparkRatesRepository;
_propertyMappingService = propertyMappingService;
}
public IEnumerable<Carpark> GetAllCarparks()
{
return _context.Carparks.OrderBy(a => a.CarparkId);
}
public double CalculateCarparkPrice(Guid id, DateTime StartTime,DateTime EndTime, String vehicleType)
{
var duration = 0.0;
double Price = 0;
Boolean IsNUll = false, NonExistenceCarparkRate = false, InvalidDate = false, FlatRateExistence = false;
DateTime RateStartTimeFromDB = new DateTime(1, 1, 1); ;
DateTime RateEndTimeFromDB = new DateTime(1, 1, 1);
var carpark = _carparkRatesRepository.GetCarparkRateById(id, vehicleType);
List<CarparkRate> CarParkRateList = carpark.ToList();
if (EndTime.ToString() == "1/1/0001 12:00:00 AM" && StartTime.ToString() == "1/1/0001 12:00:00 AM")
{
duration = 60;
}
else if (EndTime.ToString() != "1/1/0001 12:00:00 AM" && StartTime.ToString() == "1/1/0001 12:00:00 AM")
{
StartTime = DateTime.Now;
StartTime = new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, StartTime.Hour, StartTime.Minute, 0);
duration = (EndTime - StartTime).TotalMinutes;
}
else
{
duration = (EndTime - StartTime).TotalMinutes;
}
if (duration >= 0)
{
if (CarParkRateList.Count != 0)
{
var result = new Calculation(StartTime, (int)duration);
List<HoursPerDay> dayOfWeek = result.getparkingDay(StartTime, EndTime);
foreach (HoursPerDay EachHoursPerDay in dayOfWeek)
{
if (EachHoursPerDay.getDay() > 0 && EachHoursPerDay.getDay() < 6)
{
//weekdays calculation
if (vehicleType != "Motorcycle")
{
double TimeChecker = EachHoursPerDay.getDayDuration();
while (TimeChecker != 0)
{
int checkAllIfFailed = 0;
for (int i = 0; i < CarParkRateList.Count; i++)
{
if ((Convert.ToInt32(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's'))) <= 30)
{
double durationOfStaticTimeInMin = Convert.ToDouble(CarParkRateList[i].Duration) * 60;
if (EachHoursPerDay.getEndTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = RateStartTimeFromDB.AddMinutes(durationOfStaticTimeInMin);
}
else if (EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateStartTimeFromDB = RateEndTimeFromDB.Subtract(new TimeSpan(0, (int)durationOfStaticTimeInMin, 0));
}
else
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
double durationOfDynamicTimeInMin = result.getPeriodDuration(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay());
if (RateStartTimeFromDB.TimeOfDay == EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay &&
durationOfDynamicTimeInMin <= durationOfStaticTimeInMin && TimeChecker > 0)
{
result.setDuration((int)EachHoursPerDay.getDayDuration());
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].WeekdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= durationOfDynamicTimeInMin;
checkAllIfFailed--;
}
else if (TimeChecker > 0 && result.TimePeriodOverlaps(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
result.setDuration((int)(EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].WeekdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= (int)(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - (EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
checkAllIfFailed--;
}
else if (TimeChecker > 0 && result.TimePeriodOverlapsRight(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
double redundantValue = (double)(EachHoursPerDay.getEndTimeOfTheDay() - RateEndTimeFromDB).TotalMinutes;
result.setDuration((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].WeekdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= ((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - ((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setStartTimeOfTheDay(EachHoursPerDay.getStartTimeOfTheDay().AddMinutes(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue)));
checkAllIfFailed--;
}
if (result.TimePeriodOverlaps(StartTime, EndTime, RateStartTimeFromDB, RateEndTimeFromDB) == false)
{
checkAllIfFailed++;
}
if (TimeChecker == 0)
{
break;
}
}
else if ((Convert.ToInt32(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's'))) > 30)
{
FlatRateExistence = true;
}
}
if (checkAllIfFailed >= CarParkRateList.Count)
{
NonExistenceCarparkRate = true;
break;
}
/* else if(FlatRateExistence==true&& TimeChecker!=0)
{
}*/
}
}
else
{
//////motorcycle
double TimeChecker = EachHoursPerDay.getDayDuration();
while (TimeChecker != 0)
{
int checkAllIfFailed = 0;
for (int i = 0; i < CarParkRateList.Count; i++)
{
double durationOfStaticTimeInMin = Convert.ToDouble(CarParkRateList[i].Duration) * 60;
if (EachHoursPerDay.getEndTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = RateStartTimeFromDB.AddMinutes(durationOfStaticTimeInMin);
}
else if (EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateStartTimeFromDB = RateEndTimeFromDB.Subtract(new TimeSpan(0, (int)durationOfStaticTimeInMin, 0));
}
else
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
double durationOfDynamicTimeInMin = result.getPeriodDuration(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay());
if (RateStartTimeFromDB.TimeOfDay == EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay &&
durationOfDynamicTimeInMin <= durationOfStaticTimeInMin && TimeChecker > 0)
{
result.setDuration((int)EachHoursPerDay.getDayDuration());
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].WeekdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= durationOfDynamicTimeInMin;
checkAllIfFailed--;
}
else if (result.TimePeriodOverlaps(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
result.setDuration((int)(EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].WeekdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= (int)(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - (EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
checkAllIfFailed--;
}
else if (result.TimePeriodOverlapsRight(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
double redundantValue = (double)(EachHoursPerDay.getEndTimeOfTheDay() - RateEndTimeFromDB).TotalMinutes;
result.setDuration((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].WeekdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].WeekdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= ((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - ((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setStartTimeOfTheDay(EachHoursPerDay.getStartTimeOfTheDay().AddMinutes(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue)));
checkAllIfFailed--;
}
else
{
checkAllIfFailed++;
}
}
if (checkAllIfFailed >= CarParkRateList.Count)
{
NonExistenceCarparkRate = true;
break;
}
}
}
}
else if (EachHoursPerDay.getDay() == 6)
{
//Sat calculation
if (vehicleType != "Motorcycle")
{
double TimeChecker = EachHoursPerDay.getDayDuration();
while (TimeChecker != 0)
{
int checkAllIfFailed = 0;
for (int i = 0; i < CarParkRateList.Count; i++)
{
if ((Convert.ToInt32(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's'))) <= 30)
{
double durationOfStaticTimeInMin = Convert.ToDouble(CarParkRateList[i].Duration) * 60;
if (EachHoursPerDay.getEndTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = RateStartTimeFromDB.AddMinutes(durationOfStaticTimeInMin);
}
else if (EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateStartTimeFromDB = RateEndTimeFromDB.Subtract(new TimeSpan(0, (int)durationOfStaticTimeInMin, 0));
}
else
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
double durationOfDynamicTimeInMin = result.getPeriodDuration(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay());
if (RateStartTimeFromDB.TimeOfDay == EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay &&
durationOfDynamicTimeInMin <= durationOfStaticTimeInMin && TimeChecker > 0)
{
result.setDuration((int)EachHoursPerDay.getDayDuration());
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SatdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= durationOfDynamicTimeInMin;
checkAllIfFailed--;
}
else if (TimeChecker > 0 && result.TimePeriodOverlaps(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
result.setDuration((int)(EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SatdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= (int)(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - (EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
checkAllIfFailed--;
}
else if (TimeChecker > 0 && result.TimePeriodOverlapsRight(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
double redundantValue = (double)(EachHoursPerDay.getEndTimeOfTheDay() - RateEndTimeFromDB).TotalMinutes;
result.setDuration((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SatdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= ((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - ((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setStartTimeOfTheDay(EachHoursPerDay.getStartTimeOfTheDay().AddMinutes(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue)));
checkAllIfFailed--;
}
if (result.TimePeriodOverlaps(StartTime, EndTime, RateStartTimeFromDB, RateEndTimeFromDB) == false)
{
checkAllIfFailed++;
}
if (TimeChecker == 0)
{
break;
}
}
else if ((Convert.ToInt32(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's'))) > 30)
{
FlatRateExistence = true;
}
}
if (checkAllIfFailed >= CarParkRateList.Count)
{
NonExistenceCarparkRate = true;
break;
}
/* else if(FlatRateExistence==true&& TimeChecker!=0)
{
}*/
}
}
else
{
//motorcycle
double TimeChecker = EachHoursPerDay.getDayDuration();
while (TimeChecker != 0)
{
int checkAllIfFailed = 0;
for (int i = 0; i < CarParkRateList.Count; i++)
{
double durationOfStaticTimeInMin = Convert.ToDouble(CarParkRateList[i].Duration) * 60;
if (EachHoursPerDay.getEndTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = RateStartTimeFromDB.AddMinutes(durationOfStaticTimeInMin);
}
else if (EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateStartTimeFromDB = RateEndTimeFromDB.Subtract(new TimeSpan(0, (int)durationOfStaticTimeInMin, 0));
}
else
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
double durationOfDynamicTimeInMin = result.getPeriodDuration(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay());
if (RateStartTimeFromDB.TimeOfDay == EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay &&
durationOfDynamicTimeInMin <= durationOfStaticTimeInMin && TimeChecker > 0)
{
result.setDuration((int)EachHoursPerDay.getDayDuration());
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SunPHRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= durationOfDynamicTimeInMin;
checkAllIfFailed--;
}
else if (result.TimePeriodOverlaps(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
result.setDuration((int)(EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SunPHRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= (int)(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - (EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
checkAllIfFailed--;
}
else if (result.TimePeriodOverlapsRight(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
double redundantValue = (double)(EachHoursPerDay.getEndTimeOfTheDay() - RateEndTimeFromDB).TotalMinutes;
result.setDuration((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SunPHRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= ((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - ((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setStartTimeOfTheDay(EachHoursPerDay.getStartTimeOfTheDay().AddMinutes(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue)));
checkAllIfFailed--;
}
else
{
checkAllIfFailed++;
}
}
if (checkAllIfFailed >= CarParkRateList.Count)
{
NonExistenceCarparkRate = true;
break;
}
}
}
}
else
{
//SUN and PH calculation
if (vehicleType != "Motorcycle")
{
double TimeChecker = EachHoursPerDay.getDayDuration();
while (TimeChecker != 0)
{
int checkAllIfFailed = 0;
for (int i = 0; i < CarParkRateList.Count; i++)
{
if ((Convert.ToInt32(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's'))) <= 30)
{
double durationOfStaticTimeInMin = Convert.ToDouble(CarParkRateList[i].Duration) * 60;
if (EachHoursPerDay.getEndTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = RateStartTimeFromDB.AddMinutes(durationOfStaticTimeInMin);
}
else if (EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateStartTimeFromDB = RateEndTimeFromDB.Subtract(new TimeSpan(0, (int)durationOfStaticTimeInMin, 0));
}
else
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
double durationOfDynamicTimeInMin = result.getPeriodDuration(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay());
if (RateStartTimeFromDB.TimeOfDay == EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay &&
durationOfDynamicTimeInMin <= durationOfStaticTimeInMin && TimeChecker > 0)
{
result.setDuration((int)EachHoursPerDay.getDayDuration());
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SunPHRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= durationOfDynamicTimeInMin;
checkAllIfFailed--;
}
else if (TimeChecker > 0 && result.TimePeriodOverlaps(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
result.setDuration((int)(EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SunPHRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= (int)(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - (EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
checkAllIfFailed--;
}
else if (TimeChecker > 0 && result.TimePeriodOverlapsRight(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
double redundantValue = (double)(EachHoursPerDay.getEndTimeOfTheDay() - RateEndTimeFromDB).TotalMinutes;
result.setDuration((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SunPHRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= ((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - ((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setStartTimeOfTheDay(EachHoursPerDay.getStartTimeOfTheDay().AddMinutes(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue)));
checkAllIfFailed--;
}
if (result.TimePeriodOverlaps(StartTime, EndTime, RateStartTimeFromDB, RateEndTimeFromDB) == false)
{
checkAllIfFailed++;
}
if (TimeChecker == 0)
{
break;
}
}
else if ((Convert.ToInt32(CarParkRateList[i].SunPHMin.Trim('m', 'i', 'n', 's'))) > 30)
{
FlatRateExistence = true;
}
}
if (checkAllIfFailed >= CarParkRateList.Count)
{
NonExistenceCarparkRate = true;
break;
}
/* else if(FlatRateExistence==true&& TimeChecker!=0)
{
}*/
}
}
else
{
// motorcycle
double TimeChecker = EachHoursPerDay.getDayDuration();
while (TimeChecker != 0)
{
int checkAllIfFailed = 0;
for (int i = 0; i < CarParkRateList.Count; i++)
{
double durationOfStaticTimeInMin = Convert.ToDouble(CarParkRateList[i].Duration) * 60;
if (EachHoursPerDay.getEndTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = RateStartTimeFromDB.AddMinutes(durationOfStaticTimeInMin);
}
else if (EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay.TotalMinutes == 0)
{
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateStartTimeFromDB = RateEndTimeFromDB.Subtract(new TimeSpan(0, (int)durationOfStaticTimeInMin, 0));
}
else
{
RateStartTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getStartTimeOfTheDay().Day + "/" + EachHoursPerDay.getStartTimeOfTheDay().Month + "/" + EachHoursPerDay.getStartTimeOfTheDay().Year + " " + CarParkRateList[i].StartTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
RateEndTimeFromDB = DateTime.ParseExact(EachHoursPerDay.getEndTimeOfTheDay().Day + "/" + EachHoursPerDay.getEndTimeOfTheDay().Month + "/" + EachHoursPerDay.getEndTimeOfTheDay().Year + " " + CarParkRateList[i].EndTime, "d/M/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
double durationOfDynamicTimeInMin = result.getPeriodDuration(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay());
if (RateStartTimeFromDB.TimeOfDay == EachHoursPerDay.getStartTimeOfTheDay().TimeOfDay &&
durationOfDynamicTimeInMin <= durationOfStaticTimeInMin && TimeChecker > 0)
{
result.setDuration((int)EachHoursPerDay.getDayDuration());
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SatdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= durationOfDynamicTimeInMin;
checkAllIfFailed--;
}
else if (result.TimePeriodOverlaps(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
result.setDuration((int)(EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SatdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= (int)(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - (EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes);
checkAllIfFailed--;
}
else if (result.TimePeriodOverlapsRight(EachHoursPerDay.getStartTimeOfTheDay(), EachHoursPerDay.getEndTimeOfTheDay(), RateStartTimeFromDB, RateEndTimeFromDB) == true)
{
double redundantValue = (double)(EachHoursPerDay.getEndTimeOfTheDay() - RateEndTimeFromDB).TotalMinutes;
result.setDuration((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
Price += result.calculatePrice(Convert.ToDouble(CarParkRateList[i].SatdayRate.Trim('$')), Convert.ToDouble(CarParkRateList[i].SatdayMin.Trim('m', 'i', 'n', 's')));
TimeChecker -= ((int)((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setDayDuration(EachHoursPerDay.getDayDuration() - ((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue));
EachHoursPerDay.setStartTimeOfTheDay(EachHoursPerDay.getStartTimeOfTheDay().AddMinutes(((EachHoursPerDay.getEndTimeOfTheDay() - EachHoursPerDay.getStartTimeOfTheDay()).TotalMinutes - redundantValue)));
checkAllIfFailed--;
}
else
{
checkAllIfFailed++;
}
}
if (checkAllIfFailed >= CarParkRateList.Count)
{
NonExistenceCarparkRate = true;
break;
}
}
}
}
}
}
else
{
IsNUll = true;
Price = 0;
}
}
else if (0 < duration)
{
InvalidDate = true;
}
//Price = Math.Round(Price, 2, MidpointRounding.ToEven);
return Price;
}
public double GetDistance(double fromLatitude, double fromLongitude, double toLatitude, double toLongitude)
{
var fromCoord = new GeoCoordinate(fromLatitude, fromLongitude);
var toCoord = new GeoCoordinate(toLatitude, toLongitude);
var distance = fromCoord.GetDistanceTo(toCoord);
return distance;
}
public PagedList<Carpark> GetCarparks(CarparkResourceParameters carparkResourceParameters)
{
var error = "";
var collectionBeforePaging = _context.Carparks.AsQueryable();
// filter agency type
if (!string.IsNullOrEmpty(carparkResourceParameters.AgencyType))
{
var agencyTypeForWhereClause = carparkResourceParameters.AgencyType.Trim();
if (agencyTypeForWhereClause == "HDB" || agencyTypeForWhereClause == "LTA" || agencyTypeForWhereClause == "URA")
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.AgencyType == agencyTypeForWhereClause);
}
else
{
error += $"Cannot find the specified agency type {carparkResourceParameters.AgencyType}. ";
}
}
// filter vehicle type
if (!string.IsNullOrEmpty(carparkResourceParameters.VehType))
{
if (carparkResourceParameters.VehType == "Car")
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.LotType.Contains('C'));
}
else if (carparkResourceParameters.VehType == "Motorcycle")
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.LotType.Contains('M'));
}
else if (carparkResourceParameters.VehType == "Heavy Vehicle")
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.LotType.Contains('H'));
}
else if (carparkResourceParameters.VehType == "All")
{
// do nothing.
}
else
{
error += $"Cannot find the specified vehicle type {carparkResourceParameters.VehType}. ";
}
}
if (carparkResourceParameters.Latitude != Double.MinValue || carparkResourceParameters.Longitude != Double.MinValue)
{
collectionBeforePaging = collectionBeforePaging.Where(carpark => GetDistance(carparkResourceParameters.Latitude, carparkResourceParameters.Longitude, Double.Parse(carpark.XCoord), Double.Parse(carpark.YCoord)) <= carparkResourceParameters.Range);
}
// filtering of price
// if start date time and end date time are specified.
//if (carparkResourceParameters.StartDateTime != DateTime.MinValue || carparkResourceParameters.EndDateTime != DateTime.MinValue)
//{
// var carparks = collectionBeforePaging.ToList();
// carparks.ForEach(a =>
// {
// if (carparkResourceParameters.VehType == "All")
// {
// double carPrice = 0.0, hvPrice = 0.0, mPrice = 0.0;
// var asplit = a.LotType.Split(",");
// foreach (var x in asplit)
// {
// if (x.Contains("C"))
// {
// carPrice = CalculateCarparkPrice(a.Id, FormatDateTime(carparkResourceParameters.StartDateTime), FormatDateTime(carparkResourceParameters.EndDateTime), "Car");
// }
// else if (x.Contains("M"))
// {
// mPrice = CalculateCarparkPrice(a.Id, FormatDateTime(carparkResourceParameters.StartDateTime), FormatDateTime(carparkResourceParameters.EndDateTime), "Motorcycle");
// }
// else if (x.Contains("H"))
// {
// hvPrice = CalculateCarparkPrice(a.Id, FormatDateTime(carparkResourceParameters.StartDateTime), FormatDateTime(carparkResourceParameters.EndDateTime), "Heavy Vehicle");
// }
// }
// if (asplit.Length == 1)
// {
// if (carPrice != 0.0)
// {
// a.Price = carPrice;
// }
// else if (mPrice != 0.0)
// {
// a.Price = mPrice;
// }
// else if (hvPrice != 0.0)
// {
// a.Price = hvPrice;
// }
// }
// else if (asplit.Length == 2)
// {
// if (carPrice != 0.0 && mPrice != 0.0)
// {
// a.Price = Math.Min(carPrice, mPrice);
// }
// else if (carPrice != 0.0 && hvPrice != 0.0)
// {
// a.Price = Math.Min(carPrice, hvPrice);
// }
// else if (mPrice != 0.0 && hvPrice != 0.0)
// {
// a.Price = Math.Min(mPrice, hvPrice);
// }
// }
// else if (asplit.Length == 3)
// {
// a.Price = Math.Min(Math.Min(carPrice, mPrice), hvPrice);
// }
// }
// else
// {
// var price = CalculateCarparkPrice(a.Id, FormatDateTime(carparkResourceParameters.StartDateTime), FormatDateTime(carparkResourceParameters.EndDateTime), carparkResourceParameters.VehType);
// a.Price = price;
// }
// });
// // price is defaulted to max double, but if specified then it will set to lower or equal to that price.
// collectionBeforePaging = collectionBeforePaging.Where(a => a.Price <= carparkResourceParameters.Price).OrderBy(a => a.Price);
//}
//else
//// if datetime not specified.
//{
// var carparks = collectionBeforePaging.ToList();
// carparks.ForEach(a =>
// {
// if (carparkResourceParameters.VehType == "All")
// {
// double carPrice = 0.0, hvPrice = 0.0, mPrice = 0.0;
// var asplit = a.LotType.Split(",");
// foreach (var x in asplit)
// {
// if (x.Contains("C"))
// {
// carPrice = CalculateCarparkPrice(a.Id, FormatDateTime(DateTime.Now), FormatDateTime(DateTime.Now.AddHours(1)), "Car");
// }
// else if (x.Contains("M"))
// {
// mPrice = CalculateCarparkPrice(a.Id, FormatDateTime(DateTime.Now), FormatDateTime(DateTime.Now.AddHours(1)), "Motorcycle");
// }
// else if (x.Contains("H"))
// {
// hvPrice = CalculateCarparkPrice(a.Id, FormatDateTime(DateTime.Now), FormatDateTime(DateTime.Now.AddHours(1)), "Heavy Vehicle");
// }
// }
// if (asplit.Length == 1)
// {
// if (carPrice != 0.0)
// {
// a.Price = carPrice;
// }
// else if (mPrice != 0.0)
// {
// a.Price = mPrice;
// }
// else if (hvPrice != 0.0)
// {
// a.Price = hvPrice;
// }
// }
// else if (asplit.Length == 2)
// {
// if (carPrice != 0.0 && mPrice != 0.0)
// {
// a.Price = Math.Min(carPrice, mPrice);
// }
// else if (carPrice != 0.0 && hvPrice != 0.0)
// {
// a.Price = Math.Min(carPrice, hvPrice);
// }
// else if (mPrice != 0.0 && hvPrice != 0.0)
// {
// a.Price = Math.Min(mPrice, hvPrice);
// }
// }
// else if (asplit.Length == 3)
// {
// a.Price = Math.Min(Math.Min(carPrice, mPrice), hvPrice);
// }
// }
// else
// {
// // set start datetime to now and end datetime to one hour after now
// var price = CalculateCarparkPrice(a.Id, FormatDateTime(DateTime.Now), FormatDateTime(DateTime.Now.AddHours(1)), carparkResourceParameters.VehType);
// a.Price = price;
// }
// });
// // price is defaulted to max double, but if specified then it will set to lower or equal to that price.
// collectionBeforePaging = collectionBeforePaging.Where(a => a.Price <= carparkResourceParameters.Price).OrderBy(a => a.Price);
//}
// Electronic or Coupon Parking
if (carparkResourceParameters.IsElectronic == true)
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.ParkingSystem == "ELECTRONIC PARKING");
}
else
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.ParkingSystem == "COUPON PARKING");
}
// Is Central or Not
if (carparkResourceParameters.IsCentral)
{
collectionBeforePaging = collectionBeforePaging.Where(a => a.IsCentral);
}
// Search Query
if (!string.IsNullOrEmpty(carparkResourceParameters.SearchQuery))
{
var searchQueryForWhereClause = carparkResourceParameters.SearchQuery
.Trim().ToLowerInvariant();
collectionBeforePaging = collectionBeforePaging.Where(a => a.CarparkName.ToLowerInvariant().Contains(searchQueryForWhereClause));
}
// Sorting By CarparkName
collectionBeforePaging = collectionBeforePaging.ApplySort(carparkResourceParameters.OrderBy,
_propertyMappingService.GetPropertyMapping<CarparkDto, Carpark>());
if (error.Any())
{
throw new AppException(error);
}
return PagedList<Carpark>.Create(collectionBeforePaging, carparkResourceParameters.PageNumber, carparkResourceParameters.PageSize);
}
public DateTime FormatDateTime(DateTime time)
{
var datetime = DateTime.ParseExact($"{time.Month}/{time.Day}/{time.Year} {time.Hour}:{time.Minute}:0", "M/d/yyyy H:m:s", CultureInfo.InvariantCulture);
return datetime;
}
public Carpark GetCarpark(Guid carparkId)
{
return _context.Carparks.FirstOrDefault(a => a.Id == carparkId);
}
public Carpark GetCarparkById(string carparkId)
{
return _context.Carparks.FirstOrDefault(a => a.CarparkId == carparkId);
}
public void AddCarpark(Carpark carpark)
{
carpark.Id = Guid.NewGuid();
_context.Carparks.Add(carpark);
}
public void UpdateCarpark(Carpark carpark)
{
_context.Carparks.Update(carpark);
}
public void UpdateCarparks(List<Carpark> carparks)
{
_context.Carparks.AddRange(carparks);
}
public void SaveChanges()
{
_context.SaveChanges();
}
public void DeleteCarpark(Carpark carpark)
{
_context.Carparks.Remove(carpark);
}
}
}
| 50.003112 | 291 | 0.614713 | [
"MIT"
] | jlgoh/Parking-Slot-Web-App | backend/ParkingSlotAPI/Repository/ParkingRepository.cs | 48,205 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34209
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MetaInspector.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MetaInspector.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 44.5625 | 180 | 0.600281 | [
"MIT"
] | andro47/Thesis | MetaInspector/Properties/Resources.Designer.cs | 2,854 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
namespace BuildXL.Cache.ContentStore.Hashing
{
/// <summary>
/// Algorithms for building long streams of chunks into Merkle trees of DedupNodes
/// </summary>
public static class PackedDedupNodeTree
{
/// <summary>
/// Non-blocking enumerable of the whole tree given an emuerable of chunk leaves.
/// </summary>
public static IEnumerable<DedupNode> EnumerateTree(IEnumerable<ChunkInfo> chunks)
{
if (chunks is IReadOnlyCollection<ChunkInfo> collection)
{
return EnumerateTree(collection);
}
return EnumerateTree(chunks.Select(c => new DedupNode(c)));
}
/// <summary>
/// Non-blocking enumerable of the whole tree given an collection of chunk leaves.
/// </summary>
public static IEnumerable<DedupNode> EnumerateTree(IReadOnlyCollection<ChunkInfo> chunks)
{
var chunkNodes = chunks.Select(c => new DedupNode(c));
// Short-circuit for most nodes and avoid the recursion/yield-return slowness
if (chunks.Count <= DedupNode.MaxDirectChildrenPerNode)
{
return new[] { new DedupNode(chunkNodes) };
}
return EnumerateTree(chunkNodes);
}
/// <summary>
/// Non-blocking enumerable of the whole tree given an collection of nodes.
/// </summary>
public static IEnumerable<DedupNode> EnumerateTree(IEnumerable<DedupNode> nodes)
{
var nextLevel = new List<DedupNode>();
int nextLevelCount;
do
{
var thisLevel = new List<DedupNode>();
foreach (var node in nodes)
{
thisLevel.Add(node);
if (thisLevel.Count == DedupNode.MaxDirectChildrenPerNode)
{
var newNode = new DedupNode(thisLevel);
yield return newNode;
nextLevel.Add(newNode);
thisLevel.Clear();
}
}
nextLevel.AddRange(thisLevel);
foreach (var node in thisLevel)
{
yield return node;
}
nodes = nextLevel;
nextLevelCount = nextLevel.Count;
nextLevel = new List<DedupNode>();
}
while (nextLevelCount > DedupNode.MaxDirectChildrenPerNode);
if (nextLevelCount == 1)
{
yield return nodes.Single();
}
else
{
yield return new DedupNode(nodes);
}
}
}
}
| 34.727273 | 102 | 0.522579 | [
"MIT"
] | AzureMentor/BuildXL | Public/Src/Cache/ContentStore/Hashing/PackedDedupNodeTree.cs | 3,056 | C# |
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Flora License, Version 1.1 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://floralicense.org/license/
*
* 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 Tizen.Wearable.CircularUI.Forms;
using Xamarin.Forms.Xaml;
namespace WearableUIGallery.TC
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class TCIndexPageTemplate : IndexPage
{
public TCIndexPageTemplate()
{
InitializeComponent ();
}
private void OnCurrentPageChanged(object sender, EventArgs e)
{
var selectedItem = SelectedItem as MyImageData;
Console.WriteLine($"TCIndexPageTemplate OnCurrentPageChanged() SelectedItem:{selectedItem.Text}");
}
}
} | 31.473684 | 110 | 0.723244 | [
"SHL-0.51"
] | hj-na-park/Tizen.CircularUI | test/WearableUIGallery/WearableUIGallery/TC/TCIndexPageTemplate.xaml.cs | 1,198 | C# |
namespace King.David.Consulting.Common.AspNetCore.Security
{
public interface ICurrentUserAccessor
{
string GetCurrentUsername();
}
}
| 19.375 | 59 | 0.716129 | [
"MIT"
] | kdcllc/AspNetCore1_Jwt_Angular2_TravelApp | src/King.David.Consulting.Common/AspNetCore/Security/ICurrentUserAccessor.cs | 157 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.OData.Edm;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Exceptions;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.OData.Edm;
using Microsoft.OpenApi.OData.Properties;
using Microsoft.OpenApi.OData.Common;
namespace Microsoft.OpenApi.OData.Generator
{
/// <summary>
/// Extension methods to create <see cref="OpenApiSchema"/> for Edm type.
/// </summary>
internal static class OpenApiEdmTypeSchemaGenerator
{
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmTypeReference"/>.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="edmTypeReference">The Edm type reference.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateEdmTypeSchema(this ODataContext context, IEdmTypeReference edmTypeReference)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(edmTypeReference, nameof(edmTypeReference));
switch (edmTypeReference.TypeKind())
{
case EdmTypeKind.Collection:
// Collection-valued structural and navigation are represented as Schema Objects of type array.
// The value of the items keyword is a Schema Object specifying the type of the items.
return new OpenApiSchema
{
Type = "array",
Items = context.CreateEdmTypeSchema(edmTypeReference.AsCollection().ElementType())
};
// Complex, enum, entity, entity reference are represented as JSON References to the Schema Object of the complex,
// enum, entity and entity reference type, either as local references for types directly defined in the CSDL document,
// or as external references for types defined in referenced CSDL documents.
case EdmTypeKind.Complex:
case EdmTypeKind.Entity:
return context.CreateStructuredTypeSchema(edmTypeReference.AsStructured());
case EdmTypeKind.Enum:
return context.CreateEnumTypeSchema(edmTypeReference.AsEnum());
// Primitive properties of type Edm.PrimitiveType, Edm.Stream, and any of the Edm.Geo* types are
// represented as Schema Objects that are JSON References to definitions in the Definitions Object
case EdmTypeKind.Primitive:
IEdmPrimitiveTypeReference primitiveTypeReference = (IEdmPrimitiveTypeReference)edmTypeReference;
return context.CreateSchema(primitiveTypeReference);
case EdmTypeKind.TypeDefinition:
return context.CreateSchema(((IEdmTypeDefinitionReference)edmTypeReference).TypeDefinition().UnderlyingType);
case EdmTypeKind.EntityReference:
return context.CreateTypeDefinitionSchema(edmTypeReference.AsTypeDefinition());
case EdmTypeKind.None:
default:
throw Error.NotSupported(String.Format(SRResource.NotSupportedEdmTypeKind, edmTypeReference.TypeKind()));
}
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmPrimitiveTypeReference"/>.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="primitiveType">The Edm primitive reference.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateSchema(this ODataContext context, IEdmPrimitiveTypeReference primitiveType)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(primitiveType, nameof(primitiveType));
OpenApiSchema schema = context.CreateSchema(primitiveType.PrimitiveDefinition());
if (schema != null)
{
switch(primitiveType.PrimitiveKind())
{
case EdmPrimitiveTypeKind.Binary: // binary
IEdmBinaryTypeReference binaryTypeReference = (IEdmBinaryTypeReference)primitiveType;
schema.MaxLength = binaryTypeReference.MaxLength;
break;
case EdmPrimitiveTypeKind.Decimal: // decimal
IEdmDecimalTypeReference decimalTypeReference = (IEdmDecimalTypeReference)primitiveType;
if (decimalTypeReference.Precision != null)
{
if (decimalTypeReference.Scale != null)
{
// The precision is represented with the maximum and minimum keywords and a value of ±(10^ (precision - scale) - 10^ scale).
double tmp = Math.Pow(10, decimalTypeReference.Precision.Value - decimalTypeReference.Scale.Value)
- Math.Pow(10, -decimalTypeReference.Scale.Value);
schema.Minimum = (decimal?)(tmp * -1.0);
schema.Maximum = (decimal?)(tmp);
}
else
{
// If the scale facet has a numeric value, and ±(10^precision - 1) if the scale is variable
double tmp = Math.Pow(10, decimalTypeReference.Precision.Value) - 1;
schema.Minimum = (decimal?)(tmp * -1.0);
schema.Maximum = (decimal?)(tmp);
}
}
// The scale of properties of type Edm.Decimal are represented with the OpenAPI Specification keyword multipleOf and a value of 10 ^ -scale
schema.MultipleOf = decimalTypeReference.Scale == null ? null : (decimal?)(Math.Pow(10, decimalTypeReference.Scale.Value * -1));
break;
case EdmPrimitiveTypeKind.String: // string
IEdmStringTypeReference stringTypeReference = (IEdmStringTypeReference)primitiveType;
schema.MaxLength = stringTypeReference.MaxLength;
break;
}
// Nullable properties are marked with the keyword nullable and a value of true.
schema.Nullable = primitiveType.IsNullable ? true : false;
}
return schema;
}
/// <summary>
/// Create a <see cref="OpenApiSchema"/> for a <see cref="IEdmPrimitiveType"/>.
/// </summary>
/// <param name="context">The OData context.</param>
/// <param name="primitiveType">The Edm primitive type.</param>
/// <returns>The created <see cref="OpenApiSchema"/>.</returns>
public static OpenApiSchema CreateSchema(this ODataContext context, IEdmPrimitiveType primitiveType)
{
Utils.CheckArgumentNull(context, nameof(context));
Utils.CheckArgumentNull(primitiveType, nameof(primitiveType));
// Spec has different configure for double, AnyOf or OneOf?
OpenApiSchema schema = new OpenApiSchema
{
AllOf = null,
OneOf = null,
AnyOf = null
};
switch (primitiveType.PrimitiveKind)
{
case EdmPrimitiveTypeKind.Binary: // binary
schema.Type = "string";
schema.Format = "base64url";
break;
case EdmPrimitiveTypeKind.Boolean: // boolean
schema.Type = "boolean";
schema.Default = new OpenApiBoolean(false);
break;
case EdmPrimitiveTypeKind.Byte: // byte
schema.Type = "integer";
schema.Format = "uint8";
break;
case EdmPrimitiveTypeKind.DateTimeOffset: // datetime offset
schema.Type = "string";
schema.Format = "date-time";
schema.Pattern = "^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?(Z|[+-][0-9][0-9]:[0-9][0-9])$";
break;
case EdmPrimitiveTypeKind.Decimal: // decimal
if (context.Settings.IEEE754Compatible)
{
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema { Type = "number" },
new OpenApiSchema { Type = "string" },
};
}
else
{
schema.Type = "number";
}
schema.Format = "decimal";
break;
case EdmPrimitiveTypeKind.Double: // double
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema { Type = "number" },
new OpenApiSchema { Type = "string" },
new OpenApiSchema
{
Enum = new List<IOpenApiAny>
{
new OpenApiString("-INF"),
new OpenApiString("INF"),
new OpenApiString("NaN")
}
}
};
schema.Format = "double";
break;
case EdmPrimitiveTypeKind.Single: // single
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema { Type = "number" },
new OpenApiSchema { Type = "string" },
new OpenApiSchema
{
Enum = new List<IOpenApiAny>
{
new OpenApiString("-INF"),
new OpenApiString("INF"),
new OpenApiString("NaN")
}
}
};
schema.Format = "float";
break;
case EdmPrimitiveTypeKind.Guid: // guid
schema.Type = "string";
schema.Format = "uuid";
schema.Pattern = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
break;
case EdmPrimitiveTypeKind.Int16:
schema.Type = "integer";
schema.Format = "int16";
schema.Minimum = Int16.MinValue; // -32768
schema.Maximum = Int16.MaxValue; // 32767
break;
case EdmPrimitiveTypeKind.Int32:
schema.Type = "integer";
schema.Format = "int32";
schema.Minimum = Int32.MinValue; // -2147483648
schema.Maximum = Int32.MaxValue; // 2147483647
break;
case EdmPrimitiveTypeKind.Int64:
if (context.Settings.IEEE754Compatible)
{
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema { Type = "integer" },
new OpenApiSchema { Type = "string" }
};
}
else
{
schema.Type = "integer";
}
schema.Format = "int64";
break;
case EdmPrimitiveTypeKind.SByte:
schema.Type = "integer";
schema.Format = "int8";
schema.Minimum = SByte.MinValue; // -128
schema.Maximum = SByte.MaxValue; // 127
break;
case EdmPrimitiveTypeKind.String: // string
schema.Type = "string";
break;
case EdmPrimitiveTypeKind.Stream: // stream
schema.Type = "string";
schema.Format = "base64url";
break;
case EdmPrimitiveTypeKind.Duration: // duration
schema.Type = "string";
schema.Format = "duration";
schema.Pattern = "^-?P([0-9]+D)?(T([0-9]+H)?([0-9]+M)?([0-9]+([.][0-9]+)?S)?)?$";
break;
case EdmPrimitiveTypeKind.Date:
schema.Type = "string";
schema.Format = "date";
schema.Pattern = "^[0-9]{4,}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$";
break;
case EdmPrimitiveTypeKind.TimeOfDay:
schema.Type = "string";
schema.Format = "time";
schema.Pattern = "^([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]([.][0-9]{1,12})?$";
break;
case EdmPrimitiveTypeKind.Geography:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.Geography"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyPoint:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyPoint"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyLineString:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyLineString"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyPolygon:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyPolygon"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyCollection:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyCollection"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyMultiPolygon:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyMultiPolygon"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyMultiLineString:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyMultiLineString"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeographyMultiPoint:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeographyMultiPoint"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.Geometry: // Geometry
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.Geometry"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryPoint:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryPoint"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryLineString:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryLineString"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryPolygon:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryPolygon"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryCollection:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryCollection"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryMultiPolygon:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryMultiPolygon"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryMultiLineString:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryMultiLineString"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.GeometryMultiPoint:
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = "Edm.GeometryMultiPoint"
};
schema.UnresolvedReference = true;
break;
case EdmPrimitiveTypeKind.None:
default:
throw new OpenApiException(String.Format(SRResource.NotSupportedEdmTypeKind, primitiveType.PrimitiveKind));
}
return schema;
}
private static OpenApiSchema CreateEnumTypeSchema(this ODataContext context, IEdmEnumTypeReference typeReference)
{
Debug.Assert(context != null);
Debug.Assert(typeReference != null);
OpenApiSchema schema = new OpenApiSchema();
schema.Nullable = typeReference.IsNullable;
schema.Reference = null;
if (context.Settings.OpenApiSpecVersion >= OpenApiSpecVersion.OpenApi3_0)
{
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema
{
UnresolvedReference = true,
Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = typeReference.Definition.FullTypeName()
}
}
};
}
else
{
schema.Type = null;
schema.AnyOf = null;
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = typeReference.Definition.FullTypeName()
};
schema.UnresolvedReference = true;
}
return schema;
}
private static OpenApiSchema CreateStructuredTypeSchema(this ODataContext context, IEdmStructuredTypeReference typeReference)
{
Debug.Assert(context != null);
Debug.Assert(typeReference != null);
OpenApiSchema schema = new OpenApiSchema();
schema.Nullable = typeReference.IsNullable;
// AnyOf will only be valid openApi for version 3
// otherwise the reference should be set directly
// as per OASIS documentation for openApi version 2
if (typeReference.IsNullable &&
(context.Settings.OpenApiSpecVersion >= OpenApiSpecVersion.OpenApi3_0))
{
schema.Reference = null;
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema
{
UnresolvedReference = true,
Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = typeReference.Definition.FullTypeName()
}
}
};
}
else
{
schema.Type = null;
schema.AnyOf = null;
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = typeReference.Definition.FullTypeName()
};
schema.UnresolvedReference = true;
}
return schema;
}
private static OpenApiSchema CreateTypeDefinitionSchema(this ODataContext context, IEdmTypeDefinitionReference reference)
{
Debug.Assert(context != null);
Debug.Assert(reference != null);
OpenApiSchema schema = new OpenApiSchema();
schema.Nullable = reference.IsNullable;
schema.Reference = null;
if (context.Settings.OpenApiSpecVersion >= OpenApiSpecVersion.OpenApi3_0)
{
schema.AnyOf = new List<OpenApiSchema>
{
new OpenApiSchema
{
UnresolvedReference = true,
Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = reference.Definition.FullTypeName()
}
}
};
}
else
{
schema.Type = null;
schema.AnyOf = null;
schema.Reference = new OpenApiReference
{
Type = ReferenceType.Schema,
Id = reference.Definition.FullTypeName()
};
schema.UnresolvedReference = true;
}
return schema;
}
}
}
| 44.785185 | 179 | 0.476803 | [
"MIT"
] | Microsoft/OpenAPI.NET.OData | src/Microsoft.OpenApi.OData.Reader/Generator/OpenApiEdmTypeSchemaGenerator.cs | 24,188 | C# |
#if ENABLE_CRIWARE_SOFDEC
using System;
using UniRx;
using CriMana;
using Extensions;
namespace Modules.MovieManagement
{
public sealed class MovieElement
{
//----- params -----
//----- field -----
private CriManaMovieControllerForUI movieController = null;
private Subject<Unit> onFinish = null;
//----- property -----
/// <summary> 動画ファイルパス. </summary>
public string MoviePath { get; private set; }
/// <summary> 動画プレイヤー. </summary>
public Player Player { get; private set; }
/// <summary> 動画状態. </summary>
public Player.Status? Status { get; private set; }
/// <summary>
/// 再生時間(秒).
/// 再生準備中などで情報が取得できない時は-1.
/// </summary>
public float PlayTime { get; private set; }
/// <summary>
/// 動画時間(秒).
/// 再生準備中などで情報が取得できない時は-1.
/// </summary>
public float TotalTime { get; private set; }
//----- method -----
public MovieElement(Player moviePlayer, CriManaMovieControllerForUI movieController, string moviePath)
{
this.movieController = movieController;
MoviePath = moviePath;
Player = moviePlayer;
Status = moviePlayer.status;
}
public void Update()
{
if (UnityUtility.IsNull(movieController)) { return; }
var prevStatus = Status;
Status = Player.status;
PlayTime = GetPlayTime();
TotalTime = GetTotalTime();
if (prevStatus != Status && Status == Player.Status.PlayEnd)
{
UnityUtility.SetActive(movieController.gameObject, false);
UnityUtility.DeleteComponent(movieController);
if (onFinish != null)
{
onFinish.OnNext(Unit.Default);
}
}
}
private float GetPlayTime()
{
var frameInfo = Player.frameInfo;
if (frameInfo == null) { return -1f; }
return (float)frameInfo.frameNo / frameInfo.framerateN / frameInfo.framerateD * 1000000.0f;
}
private float GetTotalTime()
{
var movieInfo = Player.movieInfo;
if (movieInfo == null) { return -1f; }
return movieInfo.totalFrames * 1000.0f / movieInfo.framerateN;
}
public IObservable<Unit> OnFinishAsObservable()
{
return onFinish ?? (onFinish = new Subject<Unit>());
}
}
}
#endif
| 24.961905 | 110 | 0.531095 | [
"MIT"
] | oTAMAKOo/UniModules | Scripts/Modules/MovieManagement/MovieElement.cs | 2,757 | C# |
namespace XRoadLib.Soap;
public interface IFault
{ } | 13.5 | 25 | 0.777778 | [
"MIT"
] | e-rik/XRoadLib | src/XRoadLib/Soap/IFault.cs | 56 | C# |
namespace Rebus.NoDispatchHandlers.Tests.Handlers
{
public class SomeDependency: ISomeDependency {
}
} | 19.833333 | 50 | 0.714286 | [
"MIT"
] | MatthewDavidCampbell/RebusNoDispatchHandlerTest | Handlers/SomeDependency.cs | 119 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web.UI.DataVisualization.Charting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MOE.Common.Business.Bins;
using MOE.Common.Business.FilterExtensions;
using MOE.Common.Business.WCFServiceLibrary;
using MOE.Common.Models;
using MOE.Common.Models.Repositories;
using MOE.CommonTests.Models;
namespace MOE.CommonTests.Business.WCFServiceLibrary
{
public abstract class SignalAggregationCreateMetricTestsBase
{
public InMemoryMOEDatabase Db = new InMemoryMOEDatabase();
public SignalAggregationCreateMetricTestsBase()
{
Db.ClearTables();
Db.PopulateSignal();
Db.PopulateSignalsWithApproaches();
Db.PopulateApproachesWithDetectors();
MOE.Common.Models.Repositories.SignalsRepositoryFactory.SetSignalsRepository(new InMemorySignalsRepository(Db));
MetricTypeRepositoryFactory.SetMetricsRepository(new InMemoryMetricTypeRepository(Db));
ApplicationEventRepositoryFactory.SetApplicationEventRepository(new InMemoryApplicationEventRepository(Db));
Common.Models.Repositories.DirectionTypeRepositoryFactory.SetDirectionsRepository(new InMemoryDirectionTypeRepository());
ApproachRepositoryFactory.SetApproachRepository(new InMemoryApproachRepository(Db));
MOE.Common.Models.Repositories.SignalEventCountAggregationRepositoryFactory.SetRepository
(new InMemorySignalEventCountAggregationRepository(Db));
SetSpecificAggregateRepositoriesForTest();
}
private List<SeriesType> approvedSeries;
private List<XAxisType> approvedXaxis;
protected void SetOptionDefaults(SignalAggregationMetricOptions options)
{
options.SeriesWidth = 3;
SetFilterSignal(options);
options.ShowEventCount = true;
}
public virtual void CreateTimeMetricStartToFinishAllBinSizesAllAggregateDataTypesTest(SignalAggregationMetricOptions options)
{
AddValidValuestoLists();
SetOptionDefaults(options);
foreach (var xAxisType in Enum.GetValues(typeof(XAxisType)).Cast<XAxisType>().ToList())
{
options.SelectedXAxisType = xAxisType;
foreach (var seriesType in Enum.GetValues(typeof(SeriesType)).Cast<SeriesType>().ToList())
{
options.SelectedSeries = seriesType;
foreach (var tempBinSize in Enum.GetValues(typeof(BinFactoryOptions.BinSize))
.Cast<BinFactoryOptions.BinSize>().ToList())
{
SetTimeOptionsBasedOnBinSize(options, tempBinSize);
options.TimeOptions.SelectedBinSize = tempBinSize;
foreach (var aggregatedDataType in options.AggregatedDataTypes)
{
options.SelectedAggregatedDataType = aggregatedDataType;
try
{
if (IsValidCombination(options))
{
CreateStackedColumnChart(options);
Assert.IsTrue(options.ReturnList.Count == 1);
}
}
catch (InvalidBinSizeException e)
{
Debug.WriteLine(e.Message);
}
options.ReturnList = new List<string>();
}
}
}
}
}
private void AddValidValuestoLists()
{
approvedSeries = new List<SeriesType>();
approvedSeries.Add(SeriesType.Signal);
approvedSeries.Add(SeriesType.Route);
approvedXaxis = new List<XAxisType>();
approvedXaxis.Add(XAxisType.Time);
approvedXaxis.Add(XAxisType.TimeOfDay);
approvedXaxis.Add(XAxisType.Signal);
}
private static void SetTimeOptionsBasedOnBinSize(SignalAggregationMetricOptions options,
BinFactoryOptions.BinSize binSize)
{
if (binSize == BinFactoryOptions.BinSize.Day)
{
options.StartDate = Convert.ToDateTime("10/1/2017");
options.EndDate = Convert.ToDateTime("11/1/2017");
options.TimeOptions = new BinFactoryOptions(
Convert.ToDateTime("10/1/2017"),
Convert.ToDateTime("11/1/2017"),
null, null, null, null,
new List<DayOfWeek>
{
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday,
DayOfWeek.Saturday,
DayOfWeek.Sunday
},
BinFactoryOptions.BinSize.FifteenMinute,
BinFactoryOptions.TimeOptions.StartToEnd);
}
else if (binSize == BinFactoryOptions.BinSize.Month)
{
options.StartDate = Convert.ToDateTime("1/1/2017");
options.EndDate = Convert.ToDateTime("1/1/2018");
options.TimeOptions = new BinFactoryOptions(
Convert.ToDateTime("1/1/2017"),
Convert.ToDateTime("1/1/2018"),
null, null, null, null,
new List<DayOfWeek>
{
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday,
DayOfWeek.Saturday,
DayOfWeek.Sunday
},
BinFactoryOptions.BinSize.FifteenMinute,
BinFactoryOptions.TimeOptions.StartToEnd);
}
else if (binSize == BinFactoryOptions.BinSize.Year)
{
options.StartDate = Convert.ToDateTime("1/1/2016");
options.EndDate = Convert.ToDateTime("1/1/2018");
options.TimeOptions = new BinFactoryOptions(
Convert.ToDateTime("1/1/2016"),
Convert.ToDateTime("1/1/2018"),
null, null, null, null,
new List<DayOfWeek>
{
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday,
DayOfWeek.Saturday,
DayOfWeek.Sunday
},
BinFactoryOptions.BinSize.FifteenMinute,
BinFactoryOptions.TimeOptions.StartToEnd);
}
else
{
options.StartDate = Convert.ToDateTime("10/17/2017");
options.EndDate = Convert.ToDateTime("10/18/2017");
options.TimeOptions = new BinFactoryOptions(
Convert.ToDateTime("10/17/2017"),
Convert.ToDateTime("10/18/2017"),
null, null, null, null,
new List<DayOfWeek>
{
DayOfWeek.Monday,
DayOfWeek.Tuesday,
DayOfWeek.Wednesday,
DayOfWeek.Thursday,
DayOfWeek.Friday,
DayOfWeek.Saturday,
DayOfWeek.Sunday
},
BinFactoryOptions.BinSize.FifteenMinute,
BinFactoryOptions.TimeOptions.StartToEnd);
}
if (options.SelectedXAxisType == XAxisType.TimeOfDay)
{
options.TimeOptions.TimeOfDayStartHour = 7;
options.TimeOptions.TimeOfDayStartMinute = 0;
options.TimeOptions.TimeOfDayEndHour = 10;
options.TimeOptions.TimeOfDayStartHour = 0;
}
}
protected abstract void SetSpecificAggregateRepositoriesForTest();
protected abstract void PopulateSignalData(Signal signal);
protected void SetFilterSignal(SignalAggregationMetricOptions options)
{
List<FilterSignal> filterSignals = new List<FilterSignal>();
var signals = Db.Signals.Take(2);
foreach (var signal in signals)
{
var filterSignal = new FilterSignal {SignalId = signal.SignalID, Exclude = false};
foreach (var approach in signal.Approaches)
{
var filterApproach = new FilterApproach
{
ApproachId = approach.ApproachID,
Description = String.Empty,
Exclude = false
};
filterSignal.FilterApproaches.Add(filterApproach);
foreach (var detector in approach.Detectors)
{
filterApproach.FilterDetectors.Add(new FilterDetector
{
Id = detector.ID,
Description = String.Empty,
Exclude = false
});
}
}
filterSignals.Add(filterSignal);
}
options.FilterSignals = filterSignals;
options.FilterDirections = new List<FilterDirection>();
options.FilterDirections.Add(new FilterDirection { Description = "", DirectionTypeId = 0, Include = true });
options.FilterDirections.Add(new FilterDirection { Description = "", DirectionTypeId = 1, Include = true });
options.FilterDirections.Add(new FilterDirection { Description = "", DirectionTypeId = 2, Include = true });
options.FilterDirections.Add(new FilterDirection { Description = "", DirectionTypeId = 3, Include = true });
options.FilterMovements = new List<FilterMovement>();
options.FilterMovements.Add(new FilterMovement { Description = "", MovementTypeId = 0, Include = true });
options.FilterMovements.Add(new FilterMovement { Description = "", MovementTypeId = 1, Include = true });
options.FilterMovements.Add(new FilterMovement { Description = "", MovementTypeId = 2, Include = true });
options.FilterMovements.Add(new FilterMovement { Description = "", MovementTypeId = 3, Include = true });
}
protected void CreateStackedColumnChart(SignalAggregationMetricOptions options)
{
try
{
options.SelectedChartType = SeriesChartType.StackedColumn;
options.SelectedAggregationType = AggregationType.Sum;
options.CreateMetric();
//options.SelectedAggregationType = AggregationType.Average;
//options.CreateMetric();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
protected bool IsValidCombination(SignalAggregationMetricOptions options)
{
if(!approvedSeries.Contains(options.SelectedSeries))
return false;
if (!approvedXaxis.Contains(options.SelectedXAxisType))
return false;
if (options.SelectedXAxisType == XAxisType.Approach)
return false;
if(options.SelectedSeries == SeriesType.Route && options.SelectedXAxisType == XAxisType.Signal)
return false;
if (options.SelectedXAxisType == XAxisType.TimeOfDay &&
(options.TimeOptions.SelectedBinSize == BinFactoryOptions.BinSize.Day ||
options.TimeOptions.SelectedBinSize == BinFactoryOptions.BinSize.Month ||
options.TimeOptions.SelectedBinSize == BinFactoryOptions.BinSize.Year))
return false;
if (options.SelectedXAxisType == XAxisType.Direction && options.SelectedSeries == SeriesType.PhaseNumber)
return false;
if (options.SelectedXAxisType == XAxisType.Approach && options.SelectedSeries == SeriesType.Direction)
return false;
if (options.SelectedXAxisType == XAxisType.Detector)
return false;
if (options.SelectedSeries == SeriesType.Detector)
return false;
if (options.SelectedSeries == SeriesType.Direction)
return false;
if (options.SelectedSeries == SeriesType.Direction)
return false;
if ((options.SelectedXAxisType == XAxisType.Direction || options.SelectedXAxisType == XAxisType.Approach) &&
(options.SelectedSeries == SeriesType.Signal || options.SelectedSeries == SeriesType.Route))
return false;
return true;
}
public void CreateAllCharts(SignalAggregationMetricOptions options)
{
options.SelectedChartType = SeriesChartType.Column;
options.SelectedAggregationType = AggregationType.Sum;
options.CreateMetric();
options.SelectedAggregationType = AggregationType.Average;
options.CreateMetric();
options.SelectedChartType = SeriesChartType.Line;
options.SelectedAggregationType = AggregationType.Sum;
options.CreateMetric();
options.SelectedAggregationType = AggregationType.Average;
options.CreateMetric();
options.SelectedChartType = SeriesChartType.Pie;
options.SelectedAggregationType = AggregationType.Sum;
options.CreateMetric();
options.SelectedAggregationType = AggregationType.Average;
options.CreateMetric();
options.SelectedChartType = SeriesChartType.StackedColumn;
options.SelectedAggregationType = AggregationType.Sum;
options.CreateMetric();
options.SelectedAggregationType = AggregationType.Average;
options.CreateMetric();
options.SelectedChartType = SeriesChartType.StackedArea;
options.SelectedAggregationType = AggregationType.Sum;
options.CreateMetric();
options.SelectedAggregationType = AggregationType.Average;
options.CreateMetric();
}
}
} | 45.114804 | 133 | 0.562713 | [
"Apache-2.0"
] | avenueconsultants/ATSPM | MOE.CommonTests/Business/WCFServiceLibrary/SignalAggregationCreateMetricTestsBase.cs | 14,935 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
public static class FileParser
{
[FunctionName("FileParser")]
public static async Task<IActionResult> Run([HttpTrigger("GET")] HttpRequest request)
{
string connectionString = Environment.GetEnvironmentVariable("StorageConnectionString");
// return new OkObjectResult(connectionString);
BlobClient blob = new BlobClient(connectionString, "drop", "records.json");
var response = await blob.DownloadAsync();
return new FileStreamResult(response?.Value?.Content, response?.Value?.ContentType);
}
} | 36.9 | 97 | 0.723577 | [
"MIT"
] | TheCell/Kurs-AZ-204 | Allfiles/Labs/07/Starter/func/FileParser.cs | 738 | C# |
using Project.Services.Planets.Models;
using System.Collections.Generic;
namespace Project.Services.Planets
{
public interface IPlanetService
{
PlanetQueryServiceModel All(
string searchTerm = null,
int currentPage = 1,
int planetsPerPage = int.MaxValue);
IEnumerable<LatestPlanetServiceModel> Latest();
PlanetDetailsServiceModel Details(int planetId);
int Create(
string name,
double orbitalDistance,
double orbitalPeriod,
int radius,
double atmosphericPressure,
int? surfaceTemperature,
string analysis,
string imageUrl,
int planetarySystemId,
int creatorId);
void Delete(int id);
bool Edit(
int planetId,
string name,
double orbitalDistance,
double orbitalPeriod,
int radius,
double atmosphericPressure,
int? surfaceTemperature,
string analysis,
string imageUrl,
int planetarySystemId);
IEnumerable<PlanetServiceModel> ByUser(string userId);
bool IsByCreator(int planetId, int creatorId);
IEnumerable<PlanetarySystemServiceModel> AllPlanetarySystems();
bool PlanetarySystemExists(int planetartySystemId);
}
}
| 26.75 | 71 | 0.606758 | [
"MIT"
] | KamenRaykov/ASP.NET-Core-Project | Project/Services/Planets/IPlanetService.cs | 1,393 | C# |
using System;
using Ayehu.Sdk.ActivityCreation.Interfaces;
using Ayehu.Sdk.ActivityCreation.Extension;
using Ayehu.Sdk.ActivityCreation.Helpers;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Collections.Generic;
namespace Ayehu.Github
{
public class GH_Set_organization_membership_for_a_user : IActivityAsync
{
public string Jsonkeypath = "";
public string Accept = "";
public string password1 = "";
public string Username = "";
public string org = "";
public string username = "";
public string role = "";
private bool omitJsonEmptyorNull = true;
private string contentType = "application/json";
private string endPoint = "https://api.github.com";
private string httpMethod = "PUT";
private string _uriBuilderPath;
private string _postData;
private System.Collections.Generic.Dictionary<string, string> _headers;
private System.Collections.Generic.Dictionary<string, string> _queryStringArray;
private string uriBuilderPath {
get {
if (string.IsNullOrEmpty(_uriBuilderPath)) {
_uriBuilderPath = string.Format("/orgs/{0}/memberships/{1}",org,username);
}
return _uriBuilderPath;
}
set {
this._uriBuilderPath = value;
}
}
private string postData {
get {
if (string.IsNullOrEmpty(_postData)) {
_postData = string.Format("{{ \"role\": \"{0}\" }}",role);
}
return _postData;
}
set {
this._postData = value;
}
}
private System.Collections.Generic.Dictionary<string, string> headers {
get {
if (_headers == null) {
_headers = new Dictionary<string, string>() { {"User-Agent","" + Username},{"Accept",Accept},{"authorization","token " + password1} };
}
return _headers;
}
set {
this._headers = value;
}
}
private System.Collections.Generic.Dictionary<string, string> queryStringArray {
get {
if (_queryStringArray == null) {
_queryStringArray = new Dictionary<string, string>() { };
}
return _queryStringArray;
}
set {
this._queryStringArray = value;
}
}
public GH_Set_organization_membership_for_a_user() {
}
public GH_Set_organization_membership_for_a_user(string Jsonkeypath, string Accept, string password1, string Username, string org, string username, string role) {
this.Jsonkeypath = Jsonkeypath;
this.Accept = Accept;
this.password1 = password1;
this.Username = Username;
this.org = org;
this.username = username;
this.role = role;
}
public async System.Threading.Tasks.Task<ICustomActivityResult> Execute()
{
HttpClient client = new HttpClient();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
UriBuilder UriBuilder = new UriBuilder(endPoint);
UriBuilder.Path = uriBuilderPath;
UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray);
HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString());
if (contentType == "application/x-www-form-urlencoded")
myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData);
else
if (string.IsNullOrEmpty(postData) == false)
if (omitJsonEmptyorNull)
myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json");
else
myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType);
foreach (KeyValuePair<string, string> headeritem in headers)
client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value);
HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result;
switch (response.StatusCode)
{
case HttpStatusCode.NoContent:
case HttpStatusCode.Created:
case HttpStatusCode.Accepted:
case HttpStatusCode.OK:
{
if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
return this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath);
else
return this.GenerateActivityResult("Success");
}
default:
{
if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false)
throw new Exception(response.Content.ReadAsStringAsync().Result);
else if (string.IsNullOrEmpty(response.ReasonPhrase) == false)
throw new Exception(response.ReasonPhrase);
else
throw new Exception(response.StatusCode.ToString());
}
}
}
public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
} | 35.527273 | 251 | 0.615319 | [
"MIT"
] | Ayehu/custom-activities | Github/orgs/GH Set organization membership for a user/GH Set organization membership for a user.cs | 5,862 | C# |
//---------------------------------------------------------------------------------------------
// This file was AUTO-GENERATED by "Blazor Views" Xomega.Net generator.
//
// Manual CHANGES to this file WILL BE LOST when the code is regenerated.
//---------------------------------------------------------------------------------------------
using Demo.Client.Common.ViewModels;
using Microsoft.AspNetCore.Components;
using Xomega.Framework.Blazor.Views;
using Xomega.Framework.Views;
namespace Demo.Client.Blazor.Common.Views
{
public partial class MaintenanceTemplateViewBase : BlazorDetailsView
{
[Inject] protected MaintenanceTemplateViewModel VM { get; set; }
protected override void OnInitialized()
{
base.OnInitialized();
BindTo(VM);
}
public override void BindTo(ViewModel viewModel)
{
VM = viewModel as MaintenanceTemplateViewModel;
base.BindTo(viewModel);
}
}
}
| 31.967742 | 95 | 0.547931 | [
"MIT"
] | Xomega-Net/Demos | MultiEnumDict/Demo/Demo.Client.Blazor.Common/Views/MaintenanceTemplateViewBase.cs | 991 | C# |
//
// CanvasCellView.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// 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.Drawing;
using Xwt.Backends;
namespace Xwt
{
public class CanvasCellView: CellView, ICanvasCellViewFrontend
{
public CanvasCellView ()
{
}
protected void QueueDraw ()
{
((ICanvasCellViewBackend)BackendHost.Backend).QueueDraw ();
}
/// <summary>
/// Signals that the size of the cell may have changed, and the row
/// that contains it may need to be resized
/// </summary>
protected void QueueResize ()
{
((ICanvasCellViewBackend)BackendHost.Backend).QueueResize ();
}
/// <summary>
/// Called when the cell needs to be redrawn
/// </summary>
/// <param name='ctx'>
/// Drawing context
/// </param>
protected virtual void OnDraw (Context ctx, Rectangle cellArea)
{
}
protected virtual Rectangle OnGetDrawingAreaForBounds (Rectangle cellBounds)
{
return cellBounds;
}
[Obsolete("Use OnGetRequiredSize (SizeConstraint widthConstraint)")]
protected virtual Size OnGetRequiredSize ()
{
return new Size ();
}
protected virtual Size OnGetRequiredSize (SizeConstraint widthConstraint)
{
#pragma warning disable 618
return OnGetRequiredSize ();
#pragma warning restore 618
}
#region ICanvasCellRenderer implementation
void ICanvasCellViewFrontend.Draw (object ctxBackend, Rectangle cellArea)
{
using (var ctx = new Context (ctxBackend, BackendHost.ToolkitEngine)) {
ctx.Reset (null);
OnDraw (ctx, cellArea);
}
}
Rectangle ICanvasCellViewFrontend.GetDrawingAreaForBounds (Rectangle cellBounds)
{
return OnGetDrawingAreaForBounds (cellBounds);
}
Size ICanvasCellViewFrontend.GetRequiredSize ()
{
return OnGetRequiredSize (SizeConstraint.Unconstrained);
}
Size ICanvasCellViewFrontend.GetRequiredSize (SizeConstraint widthConstraint)
{
return OnGetRequiredSize (widthConstraint);
}
ApplicationContext ICanvasCellViewFrontend.ApplicationContext {
get { return new ApplicationContext (BackendHost.ToolkitEngine); }
}
#endregion
protected bool IsHighlighted {
get { return ((ICanvasCellViewBackend)BackendHost.Backend).IsHighlighted; }
}
}
}
| 28.34188 | 82 | 0.736429 | [
"MIT"
] | Bert1974/xwt | Xwt/Xwt/CanvasCellView.cs | 3,316 | C# |
using Hora.Core.Enums;
using Hora.Core.Queues;
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace Hora.Core
{
public class BackgroundJob
{
private static MemoryQueue _memoryQueue;
public static void Enqueue(Action p, JobType jobType = JobType.Memory,
int retryCount = 0, [CallerMemberName] string callerName = null)
{
try
{
var job = new Job(p, callerName, retryCount);
switch (jobType)
{
case JobType.Memory:
EnqueueMemoryJob(job);
break;
}
}
catch (ArgumentNullException e)
{
throw;
}
}
private static void EnqueueMemoryJob(Job job)
{
if (_memoryQueue is null)
_memoryQueue = new MemoryQueue();
Task.Run(() => _memoryQueue.Enqueue(job));
}
}
}
| 25.487805 | 79 | 0.504306 | [
"MIT"
] | vnwonah/Hora | src/Hora.Core/BackgroundJob.cs | 1,047 | C# |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Reflection;
using DSerfozo.RpcBindings.Castle.DynamicProxy.Generators.Emitters;
using DSerfozo.RpcBindings.Castle.DynamicProxy.Generators.Emitters.SimpleAST;
namespace DSerfozo.RpcBindings.Castle.DynamicProxy.Contributors
{
public delegate MethodEmitter OverrideMethodDelegate(
string name, MethodAttributes attributes, MethodInfo methodToOverride);
public delegate Expression GetTargetExpressionDelegate(ClassEmitter @class, MethodInfo method);
public delegate Reference GetTargetReferenceDelegate(ClassEmitter @class, MethodInfo method);
} | 44.333333 | 96 | 0.796992 | [
"MIT"
] | arsher/RpcBindings | src/DSerfozo.RpcBindings/DynamicProxy/Castle.DynamicProxy/Contributors/Delegates.cs | 1,197 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace BabylonExport.Entities
{
[DataContract]
public class BabylonNode : BabylonIAnimatable
{
[DataMember]
public string name { get; set; }
[DataMember]
public string id { get; set; }
[DataMember]
public string parentId { get; set; }
[DataMember]
public float[] position { get; set; }
virtual public float[] rotation { get; set; }
virtual public float[] scaling { get; set; }
virtual public float[] rotationQuaternion { get; set; }
[DataMember]
public BabylonAnimation[] animations { get; set; }
[DataMember]
public bool autoAnimate { get; set; }
[DataMember]
public int autoAnimateFrom { get; set; }
[DataMember]
public int autoAnimateTo { get; set; }
[DataMember]
public bool autoAnimateLoop { get; set; }
// Animations exported for glTF but not for Babylon
public List<BabylonAnimation> extraAnimations;
}
}
| 23.934783 | 63 | 0.604905 | [
"Apache-2.0"
] | FrozenBrain/Exporters | SharedProjects/BabylonExport.Entities/BabylonNode.cs | 1,103 | C# |
namespace Morsley.UK.People.Caching.Interfaces;
public interface IRedisContext
{
IDatabase GetDatabase();
} | 19.666667 | 49 | 0.754237 | [
"MIT"
] | john-morsley/Users | src/Infrastructure/Morsley.UK.People.Caching/Interfaces/IRedisContext.cs | 120 | C# |
/*
* 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;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.cas.Model.V20180813;
namespace Aliyun.Acs.cas.Transform.V20180813
{
public class DescribeCertificateBrandListResponseUnmarshaller
{
public static DescribeCertificateBrandListResponse Unmarshall(UnmarshallerContext context)
{
DescribeCertificateBrandListResponse describeCertificateBrandListResponse = new DescribeCertificateBrandListResponse();
describeCertificateBrandListResponse.HttpResponse = context.HttpResponse;
describeCertificateBrandListResponse.RequestId = context.StringValue("DescribeCertificateBrandList.RequestId");
List<DescribeCertificateBrandListResponse.DescribeCertificateBrandList_Brand> describeCertificateBrandListResponse_brandList = new List<DescribeCertificateBrandListResponse.DescribeCertificateBrandList_Brand>();
for (int i = 0; i < context.Length("DescribeCertificateBrandList.BrandList.Length"); i++) {
DescribeCertificateBrandListResponse.DescribeCertificateBrandList_Brand brand = new DescribeCertificateBrandListResponse.DescribeCertificateBrandList_Brand();
brand.Id = context.LongValue("DescribeCertificateBrandList.BrandList["+ i +"].Id");
brand.Name = context.StringValue("DescribeCertificateBrandList.BrandList["+ i +"].Name");
describeCertificateBrandListResponse_brandList.Add(brand);
}
describeCertificateBrandListResponse.BrandList = describeCertificateBrandListResponse_brandList;
return describeCertificateBrandListResponse;
}
}
}
| 47.78 | 215 | 0.793219 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-cas/Cas/Transform/V20180813/DescribeCertificateBrandListResponseUnmarshaller.cs | 2,389 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
public class UIManagerEditor : EditorWindow {
static Texture headTexture;
static Texture skypeTexture;
static Texture emailTexture;
static Texture folderIcon;
static ItemDataBaseList itemDatabaseList = null;
static ItemAttributeList itemAttributeList = null;
[MenuItem("Inventory System/UIManager")]
static void Init() {
EditorWindow.GetWindow(typeof(UIManagerEditor));
headTexture = Resources.Load<Texture>("EditorWindowTextures/headTexture");
skypeTexture = Resources.Load<Texture>("EditorWindowTextures/skypeIcon");
emailTexture = Resources.Load<Texture>("EditorWindowTextures/emailIcon");
folderIcon = Resources.Load<Texture>("EditorWindowTextures/folderIcon");
Object itemDatabase = Resources.Load("ItemDataBase");
if (itemDatabase == null){
itemDatabaseList = CreateItemDataBase.createItemDatabase();
}else {
itemDatabaseList = (ItemDataBaseList)Resources.Load("ItemDatabase");
}
Object attributeDatabase = Resources.Load("AttributeDatabase");
if (attributeDatabase == null) {
itemAttributeList = CreateAttributeDatabase.createItemAttributeDatabase();
}else{
itemAttributeList = (ItemAttributeList)Resources.Load("AttributeDatabase");
}
//Object inputManager = Resources.Load("InputManager");
}
bool showInputManager;
bool showItemDataBase;
bool showBluePrintDataBase;
List<bool> manageItem = new List<bool>();
Vector2 scrollPosition;
static KeyCode test;
bool showItemAttributes;
string addAttributeName = "";
int attributeAmount = 0;
int newAttributeIndex = 0;
int newAttributeValue = 0;
int[] attributeName;
int[] attributeValue;
int[] attributeNamesManage = new int[100];
int[] attributeValueManage = new int[100];
int attributeAmountManage;
bool showItem;
public int toolbarInt = 0;
public string[] toolbarStrings = new string[] {"Create Item","Manage Items"};
void OnGUI()
{
Header();
if (GUILayout.Button("Input Manager")) {
showInputManager = !showInputManager;
showItemDataBase = false;
showBluePrintDataBase = false;
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Itemdatabase")) {
showInputManager = false;
showItemDataBase = !showItemDataBase;
showBluePrintDataBase = false;
}
if (GUILayout.Button("Blueprintdatabase")) {
showInputManager = false;
showItemDataBase = false;
showBluePrintDataBase = !showBluePrintDataBase;
}
EditorGUILayout.EndHorizontal();
if (showItemDataBase)
ItemDataBase();
}
void Header()
{
//S.1
GUILayout.BeginHorizontal();
{
if (headTexture == null || emailTexture == null || skypeTexture == null || folderIcon == null)
{
headTexture = Resources.Load<Texture>("EditorWindowTextures/headTexture");
if (headTexture == null) { Debug.Log("No headTexture"); }
skypeTexture = Resources.Load<Texture>("EditorWindowTextures/skypeIcon");
if (skypeTexture == null) { Debug.Log("No skypeTexture"); }
emailTexture = Resources.Load<Texture>("EditorWindowTextures/emailIcon");
if (emailTexture == null) { Debug.Log("No emailTexture"); }
folderIcon = Resources.Load<Texture>("EditorWindowTextures/folderIcon");
if (folderIcon == null) { Debug.Log("No folderIcon"); }
}
GUI.DrawTexture(new Rect(10, 10, 75, 75), headTexture);
GUILayout.Space(90);
GUILayout.BeginVertical();
{
GUILayout.Space(10);
GUILayout.BeginVertical("Box");
{
GUILayout.Label("「Informations」", EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
{
GUI.DrawTexture(new Rect(95, 35, 15, 15), emailTexture);
GUILayout.Space(25);
GUILayout.Label("zhuzhanhao1991@Gmail.com");
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
GUI.DrawTexture(new Rect(95, 52, 15, 15), skypeTexture);
GUILayout.Space(25);
GUILayout.Label("Wei,Zhu");
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
GUI.DrawTexture(new Rect(95, 71, 15, 15), folderIcon);
GUILayout.Space(25);
GUILayout.BeginHorizontal();
{
//if (GUILayout.Button("Documentation and API",GUIStyle.none)){
if (GUILayout.Button("Documentation and API")) {
Application.OpenURL("https://docs.unity3d.com/ScriptReference/");
}
if (GUILayout.Button("Unity Assets Store"))
{
Application.OpenURL("https://www.assetstore.unity3d.com/en/");
}
}
GUILayout.EndHorizontal();
}
GUILayout.EndHorizontal();
}
//E.1.1.1
GUILayout.EndVertical();
}
//E.1.1
GUILayout.EndVertical();
}
//E.1
GUILayout.EndHorizontal();
}
void ItemDataBase()
{
EditorGUILayout.BeginVertical("Box");
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
toolbarInt = GUILayout.Toolbar(toolbarInt, toolbarStrings, GUILayout.Width(position.width - 18));
}
GUILayout.EndHorizontal();
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
{
GUILayout.Space(10);
if (toolbarInt == 0) //Create Item
{
GUI.color = Color.green;
///https://docs.unity3d.com/ScriptReference/GUILayout.Width.html
if (GUILayout.Button("Add Item", GUILayout.Width(position.width - 23))) //position.width : the width of the rectangle, measured from the X position
{
AddItem();
showItem = true;
}
if (showItem)
{
GUI.color = Color.white;
GUILayout.BeginVertical("Box", GUILayout.Width(position.width - 23));
try {
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemName = EditorGUILayout.TextField("Item Name",itemDatabaseList.itemList[itemDatabaseList.itemList.Count -1].itemName,GUILayout.Width(position.width - 30));
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemID = itemDatabaseList.itemList.Count - 1;
GUILayout.BeginHorizontal();
{
GUILayout.Label("Item Description");
GUILayout.Space(47);
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemDesc = EditorGUILayout.TextArea(itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemDesc, GUILayout.Width(position.width - 180), GUILayout.Height(70));
}
GUILayout.EndHorizontal();
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemIcon = (Sprite)EditorGUILayout.ObjectField("Item Icon", itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemIcon, typeof(Sprite), false, GUILayout.Width(position.width - 33));
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemPrefab = (GameObject)EditorGUILayout.ObjectField("Item Prefab", itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemPrefab, typeof(GameObject),false,GUILayout.Width(position.width - 33));
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemType = (ItemType)EditorGUILayout.EnumPopup("Item Type", itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemType, GUILayout.Width(position.width -33));
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].rarity = EditorGUILayout.IntSlider("Rarity", itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].rarity,0,100);
GUILayout.BeginVertical("Box",GUILayout.Width(position.width -33));
{
showItemAttributes = EditorGUILayout.Foldout(showItemAttributes, "Item attributes");
if (showItemAttributes) {
GUILayout.BeginHorizontal();
{
addAttributeName = EditorGUILayout.TextField("Name", addAttributeName);
GUI.color = Color.green;
if (GUILayout.Button("Add"))
AddAttribute();
}
GUILayout.EndHorizontal();
GUILayout.Space(10);
GUI.color = Color.white;
{
EditorGUI.BeginChangeCheck();
attributeAmount = EditorGUILayout.IntSlider("Amount", attributeAmount, 0, 50);
if (EditorGUI.EndChangeCheck())
{
attributeName = new int[attributeAmount];
attributeValue = new int[attributeAmount];
}
}
string[] attributes = new string[itemAttributeList.itemAttributeList.Count];
for (int i = 0; i < attributes.Length; i++) {
attributes[i] = itemAttributeList.itemAttributeList[i].attributeName;
}
for (int k = 0; k < attributeAmount; k++)
{
EditorGUILayout.BeginHorizontal();
attributeName[k] = EditorGUILayout.Popup("Attribute " + (k + 1), attributeName[k], attributes, EditorStyles.popup);
attributeValue[k] = EditorGUILayout.IntField("Value",attributeValue[k]);
EditorGUILayout.EndHorizontal();
}
if (GUILayout.Button("Save")) {
List<ItemAttribute> iA = new List<ItemAttribute>();
for (int i = 0; i < attributeAmount; i++){
iA.Add(new ItemAttribute(attributes[attributeName[i]], attributeValue[i]));
}
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].itemAttributes = iA;
}
}
}
GUILayout.EndVertical();
itemDatabaseList.itemList[itemDatabaseList.itemList.Count - 1].indexItemInList = 999;
} catch{}
GUILayout.EndVertical();
}
}
if (toolbarInt == 1) //manage Item
{
if (itemDatabaseList == null) {
itemDatabaseList = (ItemDataBaseList)Resources.Load("ItemDatabase");
}
if (itemDatabaseList.itemList.Count < 1) {
GUILayout.Label("There is no Item in the Database!");
}else{
GUILayout.BeginVertical();
{
for (int i = 0; i < itemDatabaseList.itemList.Count; i++)
{
try
{
manageItem.Add(false);
GUILayout.BeginVertical("Box");
{
manageItem[i] = EditorGUILayout.Foldout(manageItem[i], "" + itemDatabaseList.itemList[i].itemName);
if (manageItem[i]) {
EditorUtility.SetDirty(itemDatabaseList);
GUI.color = Color.red;
if (GUILayout.Button("Delete Item")) {
itemDatabaseList.itemList.RemoveAt(i);
EditorUtility.SetDirty(itemDatabaseList);
}
GUI.color = Color.white;
itemDatabaseList.itemList[i].itemName = EditorGUILayout.TextField("Item Name", itemDatabaseList.itemList[i].itemName, GUILayout.Width(position.width - 45));
itemDatabaseList.itemList[i].itemID = i;
GUILayout.BeginHorizontal();
{
GUILayout.Label("Item ID");
GUILayout.Label(" " + i);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
GUILayout.Label("Item Description");
GUILayout.Space(47);
itemDatabaseList.itemList[i].itemDesc = EditorGUILayout.TextArea(itemDatabaseList.itemList[i].itemDesc, GUILayout.Width(position.width - 195), GUILayout.Height(70));
}
GUILayout.EndHorizontal();
itemDatabaseList.itemList[i].itemIcon = (Sprite)EditorGUILayout.ObjectField("Item Icon", itemDatabaseList.itemList[i].itemIcon, typeof(Sprite), false, GUILayout.Width(position.width - 45));
itemDatabaseList.itemList[i].itemPrefab = (GameObject)EditorGUILayout.ObjectField("Item Model", itemDatabaseList.itemList[i].itemPrefab, typeof(GameObject), false, GUILayout.Width(position.width - 45));
itemDatabaseList.itemList[i].itemType = (ItemType)EditorGUILayout.EnumPopup("Item Type", itemDatabaseList.itemList[i].itemType, GUILayout.Width(position.width - 45));
itemDatabaseList.itemList[i].rarity = EditorGUILayout.IntSlider("Rarity", itemDatabaseList.itemList[i].rarity, 0, 100);
GUILayout.BeginVertical("Box", GUILayout.Width(position.width - 45));
{
showItemAttributes = EditorGUILayout.Foldout(showItemAttributes, "Item Attributes");
if (showItemAttributes) {
int iaCount = itemDatabaseList.itemList[i].itemAttributes.Count;
string[] attributes = new string[iaCount];
string[] allAtributes = new string[itemAttributeList.itemAttributeList.Count];
for (int ii = 0; ii < itemAttributeList.itemAttributeList.Count; ii ++) {
allAtributes[ii] = itemAttributeList.itemAttributeList[ii].attributeName;
}
for (int t = 0; t < attributes.Length; t++) {
attributes[t] = itemDatabaseList.itemList[i].itemAttributes[t].attributeName;
attributeNamesManage[t] = t;
attributeValueManage[t] = itemDatabaseList.itemList[i].itemAttributes[t].attributeValue;
}
for (int z = 0; z < iaCount; z++){
EditorGUILayout.BeginHorizontal();
{
GUI.color = Color.red;
if (GUILayout.Button("-")) {
itemDatabaseList.itemList[i].itemAttributes.RemoveAt(z);
}
GUI.color = Color.white;
attributeNamesManage[z] = EditorGUILayout.Popup(attributeNamesManage[z], attributes, EditorStyles.popup);
itemDatabaseList.itemList[i].itemAttributes[z].attributeValue = EditorGUILayout.IntField("Value", itemDatabaseList.itemList[i].itemAttributes[z].attributeValue);
}
EditorGUILayout.EndHorizontal();
}
newAttributeIndex = EditorGUILayout.Popup(newAttributeIndex, allAtributes, EditorStyles.popup);
newAttributeValue = EditorGUILayout.IntField("Value:", newAttributeValue);
GUI.color = Color.green;
if (GUILayout.Button("+"))
{
string newAttributeName = itemAttributeList.itemAttributeList[newAttributeIndex].attributeName;
itemDatabaseList.itemList[i].itemAttributes.Add(new ItemAttribute(newAttributeName, newAttributeValue));
}
GUI.color = Color.white;
if (GUILayout.Button("Save"))
{
List<ItemAttribute> iA = new List<ItemAttribute>();
for (int k = 0; k < itemDatabaseList.itemList[i].itemAttributes.Count; k++) {
iA.Add(new ItemAttribute(attributes[attributeNamesManage[k]], attributeValueManage[k]));
}
itemDatabaseList.itemList[i].itemAttributes = iA;
GameObject[] items = GameObject.FindGameObjectsWithTag("Item");
for (int z = 0; z < items.Length; z++) {
ItemHandleOnGUI itemhandle = items[z].GetComponent<ItemHandleOnGUI>();
if (itemhandle.item.itemID == itemDatabaseList.itemList[i].itemID) {
itemhandle.item = itemDatabaseList.itemList[i];
Debug.Log("Reset");
}
}
manageItem[i] = false;
}
}
}
GUILayout.EndVertical();
EditorUtility.SetDirty(itemDatabaseList);
}
}
GUILayout.EndVertical();
}
catch { }
}
}
GUILayout.EndVertical();
}
}
}
EditorGUILayout.EndScrollView();
EditorGUILayout.EndVertical();
}
void AddItem() {
EditorUtility.SetDirty(itemDatabaseList);
Item newItem = new Item();
newItem.itemName = "New Item";
itemDatabaseList.itemList.Add(newItem);
EditorUtility.SetDirty(itemDatabaseList);
}
void AddAttribute()
{
EditorUtility.SetDirty(itemAttributeList);
ItemAttribute newAttribute = new ItemAttribute();
newAttribute.attributeName = addAttributeName;
itemAttributeList.itemAttributeList.Add(newAttribute);
addAttributeName = "";
EditorUtility.SetDirty(itemAttributeList);
}
}
| 52.785203 | 293 | 0.471628 | [
"MIT"
] | Visin1991/VRPG-Core | VRPG/Assets/VFrameWork/ItemSystem/Editor/InventoryEditor/UIManagerEditor.cs | 22,123 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Analyzer.Mocking.Api.Models
{
public interface IPosition
{
IProduct Product { get; }
decimal Size { get; }
decimal UnitCost { get; }
}
}
| 19.75 | 38 | 0.639241 | [
"MIT"
] | mastercs999/strategy-player | src/Analyzer/Mocking/Api/Models/IPosition.cs | 318 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("Engine.IO_Client.Java")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Engine.IO-Client.Java")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[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 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")]
| 34.806452 | 84 | 0.741427 | [
"MIT"
] | mattleibow/Socket.IO.Client | binding/Engine.IO-Client.Java/Properties/AssemblyInfo.cs | 1,082 | C# |
//
// Copyright 2018-2021 Dynatrace LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Collections.Generic;
namespace Dynatrace.OpenKit.Core.Objects
{
/// <summary>
/// This interface represents a <see cref="OpenKitComposite"/> which is internally used.
///
/// <para>
/// The main purpose of this interface is to make components which require a <see cref="OpenKitComposite"/> to be
/// more easily testable.
/// </para>
/// </summary>
internal interface IOpenKitComposite
{
/// <summary>
/// Adds a child object to the list of this <see cref="IOpenKitComposite"/>'s children.
/// </summary>
///
/// <param name="childObject">the <see cref="IOpenKitObject">child object</see> to add.</param>
void StoreChildInList(IOpenKitObject childObject);
/// <summary>
/// Remove a child object from the list of this <see cref="IOpenKitComposite"/>'s children.
/// </summary>
///
/// <param name="childObject">the <see cref="IOpenKitComposite">child object</see> to remove.</param>
///
/// <returns>
/// <code>true</code> if the given <code>childObject</code> was successfully removed,
/// <code>false</code> otherwise.
/// </returns>
bool RemoveChildFromList(IOpenKitObject childObject);
/// <summary>
/// Returns a shallow copy of the <see cref="IOpenKitObject"/> child objects
/// </summary>
/// <returns>shallow copy of the child objects</returns>
IList<IOpenKitObject> GetCopyOfChildObjects();
/// <summary>
/// Returns the current number of children held by this composite.
/// </summary>
int GetChildCount();
/// <summary>
/// Abstract method to notify the composite about closing/ending a child object.
///
/// <para>
/// The implementing class is fully responsible to handle the implementation.
/// In most cases removing the child from the container <see cref="RemoveChildFromList"/> is sufficient.
/// </para>
/// </summary>
/// <param name="childObject"></param>
void OnChildClosed(IOpenKitObject childObject);
/// <summary>
/// Returns the action ID of this composite or <code>0</code> if the composite is not an action.
///
/// <para>
/// The default implementation returns <code>0</code>.
/// Action related composites need to override this method and return the appropriate value.
/// </para>
/// </summary>
int ActionId { get; }
}
} | 39.02439 | 117 | 0.620938 | [
"Apache-2.0"
] | Dynatrace/openkit-dotnet | src/Dynatrace.OpenKit/Core/Objects/IOpenKitComposite.cs | 3,200 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the elasticloadbalancingv2-2015-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ElasticLoadBalancingV2.Model
{
/// <summary>
/// The health of the specified targets could not be retrieved due to an internal error.
/// </summary>
#if !NETSTANDARD
[Serializable]
#endif
public partial class HealthUnavailableException : AmazonElasticLoadBalancingV2Exception
{
/// <summary>
/// Constructs a new HealthUnavailableException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public HealthUnavailableException(string message)
: base(message) {}
/// <summary>
/// Construct instance of HealthUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public HealthUnavailableException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of HealthUnavailableException
/// </summary>
/// <param name="innerException"></param>
public HealthUnavailableException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of HealthUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public HealthUnavailableException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of HealthUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public HealthUnavailableException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !NETSTANDARD
/// <summary>
/// Constructs a new instance of the HealthUnavailableException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected HealthUnavailableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception>
#if BCL35
[System.Security.Permissions.SecurityPermission(
System.Security.Permissions.SecurityAction.LinkDemand,
Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)]
#endif
[System.Security.SecurityCritical]
// These FxCop rules are giving false-positives for this method
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
}
#endif
}
} | 47.895161 | 178 | 0.68429 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/ElasticLoadBalancingV2/Generated/Model/HealthUnavailableException.cs | 5,939 | C# |
// Copyright (c) Lex Li. All rights reserved.
//
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace JexusManager.Features.Asp
{
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using JexusManager.Services;
using Microsoft.Web.Management.Client;
using Microsoft.Web.Management.Client.Win32;
using Microsoft.Web.Management.Server;
internal partial class AspPage : ModulePropertiesPage
{
private sealed class PageTaskList : ShowHelpTaskList
{
private readonly AspPage _owner;
public PageTaskList(AspPage owner)
{
_owner = owner;
}
[Obfuscation(Exclude = true)]
public override void ShowHelp()
{
_owner.ShowHelp();
}
}
private AspFeature _feature;
private bool _hasChanges;
private bool _initialized;
private TaskList _taskList;
public AspPage()
{
InitializeComponent();
}
protected override void Initialize(object navigationData)
{
var service = (IConfigurationService)GetService(typeof(IConfigurationService));
pictureBox1.Image = service.Scope.GetImage();
_feature = new AspFeature(Module);
_feature.AspSettingsUpdated = Refresh;
_feature.Load();
base.Initialize(navigationData);
}
protected override bool ShowHelp()
{
return _feature.ShowHelp();
}
private void SplitContainer1SplitterMoved(object sender, SplitterEventArgs e)
{
if (splitContainer1.Panel2.Width > 500)
{
splitContainer1.SplitterDistance = splitContainer1.Width - 500;
}
}
protected override bool ApplyChanges()
{
try
{
if (!_feature.ApplyChanges())
{
return false;
}
}
catch (COMException ex)
{
ShowError(ex, false);
return true;
}
ClearChanges();
return true;
}
protected override void CancelChanges()
{
_initialized = false;
_hasChanges = false;
_feature.CancelChanges();
ClearChanges();
}
protected override bool HasChanges
{
get { return _hasChanges; }
}
protected override bool CanApplyChanges
{
get { return true; }
}
private void InformChanges()
{
if (!_initialized)
{
return;
}
_hasChanges = true;
Refresh();
}
private void ClearChanges()
{
_hasChanges = false;
Refresh();
}
protected override TaskListCollection Tasks
{
get
{
if (_taskList == null)
{
_taskList = new PageTaskList(this);
}
base.Tasks.Add(_feature.GetTaskList());
base.Tasks.Add(_taskList);
return base.Tasks;
}
}
protected override void OnRefresh()
{
if (!_hasChanges)
{
pgASP.SelectedObject = _feature.PropertyGridObject;
_initialized = true;
}
Tasks.Fill(tsActionPanel, cmsActionPanel);
}
private void PgAspPropertyValueChanged(object s, PropertyValueChangedEventArgs e)
{
InformChanges();
}
protected override PropertyBag GetProperties()
{
return null;
}
protected override PropertyBag UpdateProperties(out bool updateSuccessful)
{
updateSuccessful = false;
return null;
}
protected override void ProcessProperties(PropertyBag properties)
{
}
}
}
| 25.011834 | 101 | 0.519517 | [
"MIT"
] | jexuswebserver/JexusManager | JexusManager.Features.Asp/AspPage.cs | 4,229 | C# |
using System.Windows;
using NUnit.Framework;
namespace DeltaEngine.Editor.ContentManager.Tests
{
[RequiresSTA]
public class ContentManagerViewTests
{
//ncrunch: no coverage start
[Test, Category("Slow"), Category("WPF")]
public void ShowMaterialEditorInWindow()
{
var window = new Window
{
Title = "My User Control Dialog",
Content = new ContentManagerView()
};
window.ShowDialog();
}
}
}
| 20.272727 | 50 | 0.668161 | [
"Apache-2.0"
] | DeltaEngine/DeltaEngine | Editor/ContentManager/Tests/ContentManagerViewTests.cs | 448 | C# |
using System;
namespace Skender.Stock.Indicators
{
[Serializable]
public class HeikinAshiResult : ResultBase
{
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
public decimal Volume { get; set; }
}
}
| 23 | 46 | 0.602899 | [
"Apache-2.0"
] | BlankaKorvo/Stock.Indicators | src/e-k/HeikinAshi/HeikinAshi.Models.cs | 347 | C# |
namespace Cedar.Example.Tests
{
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Cedar.ProcessManagers;
using Cedar.Testing;
using ScenarioAttribute = Cedar.Testing.Xunit.ScenarioAttribute;
public class starbucks_should
{
private readonly Guid _customerId = Guid.NewGuid();
private readonly Guid _orderId = Guid.NewGuid();
public class DrinkOrderPlaced
{
public Guid CustomerId { get; set; }
public Guid OrderId { get; set; }
public DrinkType Drink { get; set; }
public override string ToString()
{
return "Ordered a " + Drink;
}
}
public class DrinkPrepared
{
public Guid OrderId { get; set; }
public DrinkType Drink { get; set; }
public override string ToString()
{
return "Prepared a " + Drink;
}
}
public class PaymentReceived
{
public Guid OrderId { get; set; }
public decimal Amount { get; set; }
public override string ToString()
{
return "Payment of " + Amount + " received";
}
}
public class DrinkReceived
{
public Guid OrderId { get; set; }
public override string ToString()
{
return "My god, it's full of stars!";
}
}
public class PaymentRefunded
{
public Guid OrderId { get; set; }
public decimal Amount { get; set; }
public override string ToString()
{
return "Payment of " + Amount + " refunded";
}
}
public class PrepareDrink
{
public DrinkType Drink { get; set; }
public Guid OrderId { get; set; }
public override string ToString()
{
return "Preparing a " + Drink;
}
}
public class GiveCustomerDrink
{
public Guid CustomerId { get; set; }
public Guid OrderId { get; set; }
public override string ToString()
{
return "Order released.";
}
}
public class RefundPayment
{
public Guid CustomerId { get; set; }
public decimal Amount { get; set; }
public override string ToString()
{
return "Refunding " + Amount;
}
}
public enum DrinkType
{
Americano,
Cappucino,
Latte,
Frappucino
}
public class StarbucksProcess : ObservableProcessManager
{
protected StarbucksProcess(string id, string correlationId)
: base(id, correlationId)
{
var orderPlaced = OnEvent<DrinkOrderPlaced>();
var drinkPrepared = OnEvent<DrinkPrepared>();
var paymentReceived = OnEvent<PaymentReceived>();
var drinkReceived = OnEvent<DrinkReceived>();
var paymentRefunded = OnEvent<PaymentRefunded>();
var orderReady = (from order in orderPlaced
from drink in drinkPrepared
from payment in paymentReceived
select new
{
OrderedDrink = order.Drink,
payment.Amount,
order.CustomerId,
PreparedDrink = drink.Drink,
order.OrderId
}).Distinct();
var orderRuined = orderReady.Where(e => e.OrderedDrink != e.PreparedDrink);
var orderCompleted = orderReady.Where(e => e.OrderedDrink == e.PreparedDrink);
When(orderPlaced, e => new PrepareDrink { Drink = e.Drink, OrderId = e.OrderId });
When(orderCompleted, e => new GiveCustomerDrink { OrderId = e.OrderId, CustomerId = e.CustomerId });
When(orderRuined, e => new RefundPayment { CustomerId = e.CustomerId, Amount = e.Amount });
CompleteWhen(drinkReceived);
CompleteWhen(paymentRefunded);
}
}
[Scenario]
public async Task<ScenarioResult> prepare_a_drink_when_an_order_is_placed()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given()
.When(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
}).Then(new PrepareDrink {Drink = DrinkType.Latte, OrderId = _orderId});
}
[Scenario]
public async Task<ScenarioResult> release_the_order_when_payment_is_received_and_drink_is_prepared()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
}, new DrinkPrepared {Drink = DrinkType.Latte, OrderId = _orderId})
.When(new PaymentReceived {Amount = 10m, OrderId = _orderId})
.Then(new GiveCustomerDrink {OrderId = _orderId, CustomerId = _customerId});
}
[Scenario]
public async Task<ScenarioResult> not_release_the_order_when_payment_is_received_and_drink_is_not_prepared()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
})
.When(new PaymentReceived {Amount = 10m, OrderId = _orderId})
.ThenNothingWasSent();
}
[Scenario]
public async Task<ScenarioResult> not_release_the_order_when_payment_is_not_received_and_drink_is_prepared()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
})
.When(new DrinkPrepared { Drink = DrinkType.Latte, OrderId = _orderId })
.ThenNothingWasSent();
}
[Scenario]
public async Task<ScenarioResult> refund_the_payment_when_the_drink_is_ruined()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
}, new PaymentReceived {Amount = 10m, OrderId = _orderId})
.When(new DrinkPrepared { Drink = DrinkType.Frappucino, OrderId = _orderId })
.Then(new RefundPayment{Amount = 10m, CustomerId = _customerId});
}
[Scenario]
public async Task<ScenarioResult> complete_the_process_when_the_customer_receives_drink()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
}, new PaymentReceived {Amount = 10m, OrderId = _orderId},
new DrinkPrepared {Drink = DrinkType.Latte, OrderId = _orderId})
.When(new DrinkReceived {OrderId = _orderId})
.ThenCompletes();
}
[Scenario]
public async Task<ScenarioResult> complete_the_process_when_the_customer_receives_a_refund()
{
return await Scenario.ForProcess<StarbucksProcess>()
.Given(new DrinkOrderPlaced
{
CustomerId = _customerId,
Drink = DrinkType.Latte,
OrderId = _orderId
}, new PaymentReceived { Amount = 10m, OrderId = _orderId },
new DrinkPrepared { Drink = DrinkType.Frappucino, OrderId = _orderId })
.When(new PaymentRefunded { OrderId = _orderId, Amount = 10m})
.ThenCompletes();
}
}
} | 35.930328 | 116 | 0.516824 | [
"MIT"
] | mat-mcloughlin/Cedar | src/Cedar.Example.Tests/starbucks_should.cs | 8,769 | C# |
using System;
using Backtrace.Model;
using Backtrace.Interfaces;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using Backtrace.Common;
using System.Collections.Generic;
using Backtrace.Extensions;
#if !NET35
using System.Threading.Tasks;
using System.Net.Http;
#endif
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("DynamicProxyGenAssembly2")]
namespace Backtrace.Services
{
/// <summary>
/// Backtrace Api class that allows to send a diagnostic data to server
/// </summary>
internal class BacktraceApi : IBacktraceApi
{
/// <summary>
/// User custom request method
/// </summary>
public Func<string, string, BacktraceData, BacktraceResult> RequestHandler { get; set; } = null;
/// <summary>
/// Event triggered when server is unvailable
/// </summary>
public Action<Exception> OnServerError { get; set; } = null;
/// <summary>
/// Event triggered when server respond to diagnostic data
/// </summary>
public Action<BacktraceResult> OnServerResponse { get; set; }
internal readonly ReportLimitWatcher reportLimitWatcher;
/// <summary>
/// Url to server
/// </summary>
private readonly Uri _serverurl;
/// <summary>
/// Create a new instance of Backtrace API
/// </summary>
/// <param name="credentials">API credentials</param>
public BacktraceApi(BacktraceCredentials credentials, uint reportPerMin = 3)
{
if (credentials == null)
{
throw new ArgumentException($"{nameof(BacktraceCredentials)} cannot be null");
}
_serverurl = credentials.GetSubmissionUrl();
reportLimitWatcher = new ReportLimitWatcher(reportPerMin);
#if !NET35
InitializeHttpClient(credentials.Proxy);
#endif
}
#region asyncRequest
#if !NET35
/// <summary>
/// The http client.
/// </summary>
internal HttpClient HttpClient;
private void InitializeHttpClient(WebProxy proxy)
{
if (proxy != null)
{
HttpClient = new HttpClient(new HttpClientHandler() { Proxy = proxy }, true);
}
else
{
HttpClient = new HttpClient();
}
}
public async Task<BacktraceResult> SendAsync(BacktraceData data)
{
//check rate limiting
bool watcherValidation = reportLimitWatcher.WatchReport(data.Report);
if (!watcherValidation)
{
return BacktraceResult.OnLimitReached(data.Report);
}
// execute user custom request handler
if (RequestHandler != null)
{
return RequestHandler?.Invoke(_serverurl.ToString(), FormDataHelper.GetContentTypeWithBoundary(Guid.NewGuid()), data);
}
//get a json from diagnostic object
var json = JsonConvert.SerializeObject(data, JsonSerializerSettings);
return await SendAsync(Guid.NewGuid(), json, data.Attachments, data.Report, data.Deduplication);
}
internal async Task<BacktraceResult> SendAsync(Guid requestId, string json, List<string> attachments, BacktraceReport report, int deduplication = 0)
{
string contentType = FormDataHelper.GetContentTypeWithBoundary(requestId);
string boundary = FormDataHelper.GetBoundary(requestId);
using (var content = new MultipartFormDataContent(boundary))
{
var requestUrl = _serverurl.ToString();
if (deduplication > 0)
{
requestUrl += $"&_mod_duplicate={deduplication}";
}
var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
content.AddJson("upload_file.json", json);
content.AddFiles(attachments);
//// clear and add content type with boundary tag
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", contentType);
request.Content = content;
try
{
using (var response = await HttpClient.SendAsync(request))
{
var fullResponse = await response.Content.ReadAsStringAsync();
if (response.StatusCode != HttpStatusCode.OK)
{
var err = new WebException(response.ReasonPhrase);
System.Diagnostics.Trace.WriteLine(fullResponse);
OnServerError?.Invoke(err);
return BacktraceResult.OnError(report, err);
}
var result = JsonConvert.DeserializeObject<BacktraceResult>(fullResponse);
result.BacktraceReport = report;
OnServerResponse?.Invoke(result);
return result;
}
}
catch (Exception exception)
{
System.Diagnostics.Trace.WriteLine($"Backtrace - Server error: {exception.ToString()}");
OnServerError?.Invoke(exception);
return BacktraceResult.OnError(report, exception);
}
}
}
#endif
#endregion
#region synchronousRequest
/// <summary>
/// Sending a diagnostic report data to server API.
/// </summary>
/// <param name="data">Diagnostic data</param>
/// <returns>Server response</returns>
public BacktraceResult Send(BacktraceData data)
{
#if !NET35
return Task.Run(() => SendAsync(data)).Result;
#else
//check rate limiting
bool watcherValidation = reportLimitWatcher.WatchReport(data.Report);
if (!watcherValidation)
{
return BacktraceResult.OnLimitReached(data.Report);
}
// execute user custom request handler
if (RequestHandler != null)
{
return RequestHandler?.Invoke(_serverurl.ToString(), FormDataHelper.GetContentTypeWithBoundary(Guid.NewGuid()), data);
}
//set submission data
string json = JsonConvert.SerializeObject(data);
return Send(Guid.NewGuid(), json, data.Report?.AttachmentPaths ?? new List<string>(), data.Report, data.Deduplication);
}
private BacktraceResult Send(Guid requestId, string json, List<string> attachments, BacktraceReport report, int deduplication = 0)
{
var requestUrl = _serverurl.ToString();
if (deduplication > 0)
{
requestUrl += $"&_mod_duplicate={deduplication}";
}
var formData = FormDataHelper.GetFormData(json, attachments, requestId);
string contentType = FormDataHelper.GetContentTypeWithBoundary(requestId);
var request = WebRequest.Create(requestUrl) as HttpWebRequest;
//Set up the request properties.
request.Method = "POST";
request.ContentType = contentType;
request.ContentLength = formData.Length;
try
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(formData, 0, formData.Length);
requestStream.Close();
}
return ReadServerResponse(request, report);
}
catch (Exception exception)
{
OnServerError?.Invoke(exception);
return BacktraceResult.OnError(report, exception);
}
#endif
}
/// <summary>
/// Handle server respond for synchronous request
/// </summary>
/// <param name="request">Current HttpWebRequest</param>
private BacktraceResult ReadServerResponse(HttpWebRequest request, BacktraceReport report)
{
using (WebResponse webResponse = request.GetResponse() as HttpWebResponse)
{
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();
var response = JsonConvert.DeserializeObject<BacktraceResult>(fullResponse);
response.BacktraceReport = report;
OnServerResponse?.Invoke(response);
return response;
}
}
#endregion
/// <summary>
/// Get serialization settings
/// </summary>
/// <returns></returns>
private JsonSerializerSettings JsonSerializerSettings { get; } = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
#region dispose
private bool _disposed = false; // To detect redundant calls
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
#if !NET35
HttpClient.Dispose();
#endif
}
_disposed = true;
}
}
~BacktraceApi()
{
Dispose(false);
}
#endregion
public void SetClientRateLimitEvent(Action<BacktraceReport> onClientReportLimitReached)
{
reportLimitWatcher.OnClientReportLimitReached = onClientReportLimitReached;
}
public void SetClientRateLimit(uint rateLimit)
{
reportLimitWatcher.SetClientReportLimit(rateLimit);
}
}
} | 37.161765 | 156 | 0.569747 | [
"MIT"
] | TechSmith/backtrace-csharp | Backtrace/Services/BacktraceApi.cs | 10,110 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using BuildXL.Cache.ContentStore.Hashing;
using BuildXL.Cache.ContentStore.Interfaces.Results;
using BuildXL.Cache.ContentStore.Interfaces.Sessions;
using BuildXL.Cache.Interfaces;
using BuildXL.Cache.MemoizationStore.Interfaces.Results;
using BuildXL.Cache.MemoizationStore.Interfaces.Sessions;
using BuildXL.Storage;
using BuildXL.Storage.Fingerprints;
using BuildXL.Utilities;
using CacheDeterminism = BuildXL.Cache.MemoizationStore.Interfaces.Sessions.CacheDeterminism;
namespace BuildXL.Cache.MemoizationStoreAdapter
{
internal static class ConversionExtensions
{
public static ContentHash ToMemoization(in this CasHash hash)
{
return ContentHashingUtilities.CreateFrom(hash.ToArray());
}
public static Fingerprint ToMemoization(in this WeakFingerprintHash weak)
{
return weak.FingerprintHash.RawHash;
}
public static ContentHashListWithDeterminism ToMemoization(in this CasEntries hashes)
{
return new ContentHashListWithDeterminism(
new ContentHashList(hashes.Select(hash => hash.ToMemoization()).ToArray()),
hashes.Determinism.ToMemoization());
}
internal static CacheDeterminism ToMemoization(in this BuildXL.Cache.Interfaces.CacheDeterminism determinism)
{
if (determinism.IsDeterministicTool)
{
return CacheDeterminism.Tool;
}
if (determinism.IsSinglePhaseNonDeterministic)
{
return CacheDeterminism.SinglePhaseNonDeterministic;
}
// May not be necessary ?
if (!determinism.IsDeterministic)
{
return CacheDeterminism.None;
}
return CacheDeterminism.ViaCache(determinism.Guid, determinism.ExpirationUtc);
}
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static Possible<string, Failure> FromMemoization(this PinResult result, CasHash hash, string cacheId)
{
switch (result.Code)
{
case PinResult.ResultCode.Success:
return cacheId;
case PinResult.ResultCode.ContentNotFound:
return new NoCasEntryFailure(cacheId, hash);
case PinResult.ResultCode.Error:
return new CacheFailure(result.ErrorMessage);
default:
return new CacheFailure("Unrecognized PinResult code: " + result.Code + ", error message: " + (result.ErrorMessage ?? string.Empty));
}
}
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly")]
public static FileRealizationMode ToMemoization(this FileState fileState)
{
switch (fileState)
{
case FileState.Writeable:
return FileRealizationMode.CopyNoVerify;
case FileState.ReadOnly:
return FileRealizationMode.Any;
default:
throw new NotImplementedException("Unrecognized FileState: " + fileState);
}
}
public static CasHash FromMemoization(in this ContentHash hash)
{
return new CasHash(new Hash(hash));
}
public static CasEntries FromMemoization(in this ContentHashListWithDeterminism contentHashListWithDeterminism)
{
return new CasEntries(
contentHashListWithDeterminism.ContentHashList.Hashes.Select(contentHash => contentHash.FromMemoization()),
contentHashListWithDeterminism.Determinism.FromMemoization());
}
internal static BuildXL.Cache.Interfaces.CacheDeterminism FromMemoization(in this CacheDeterminism determinism)
{
if (determinism.IsDeterministicTool)
{
return BuildXL.Cache.Interfaces.CacheDeterminism.Tool;
}
if (determinism.IsSinglePhaseNonDeterministic)
{
return BuildXL.Cache.Interfaces.CacheDeterminism.SinglePhaseNonDeterministic;
}
// May not be necessary ?
if (!determinism.IsDeterministic)
{
return BuildXL.Cache.Interfaces.CacheDeterminism.None;
}
return BuildXL.Cache.Interfaces.CacheDeterminism.ViaCache(determinism.Guid, determinism.ExpirationUtc);
}
internal static Possible<BuildXL.Cache.Interfaces.StrongFingerprint, Failure> FromMemoization(
this GetSelectorResult selectorResult, WeakFingerprintHash weak, string cacheId)
{
if (selectorResult.Succeeded)
{
return new Possible<BuildXL.Cache.Interfaces.StrongFingerprint, Failure>(new BuildXL.Cache.Interfaces.StrongFingerprint(
weak,
selectorResult.Selector.ContentHash.FromMemoization(),
new Hash(FingerprintUtilities.CreateFrom(selectorResult.Selector.Output)),
cacheId));
}
else
{
return new Possible<BuildXL.Cache.Interfaces.StrongFingerprint, Failure>(new CacheFailure(selectorResult.ErrorMessage));
}
}
internal static BuildXL.Cache.Interfaces.StrongFingerprint FromMemoization(
in this BuildXL.Cache.MemoizationStore.Interfaces.Sessions.StrongFingerprint strongFingerprint,
string cacheId)
{
var weak = new WeakFingerprintHash(strongFingerprint.WeakFingerprint.ToByteArray());
return new BuildXL.Cache.Interfaces.StrongFingerprint(
weak,
strongFingerprint.Selector.ContentHash.FromMemoization(),
new Hash(FingerprintUtilities.CreateFrom(strongFingerprint.Selector.Output)),
cacheId);
}
}
}
| 41.764706 | 154 | 0.628326 | [
"MIT"
] | mmiller-msft/BuildXL | Public/Src/Cache/VerticalStore/MemoizationStoreAdapter/ConversionExtensions.cs | 6,390 | C# |
namespace MoogleEngine
{
public class Similitud
{
public float[,]? similitud;
public Similitud(Query query, Corpus corpus)
{
similitud = Cosin(query, corpus);
}
// Calcular IDF de cada palabra
public static void IDF(Dictionary<int, Info> documents, Dictionary<string, float> IDFs)
{
foreach (var pair in IDFs)
{
int count = 0;
for (int i = 0; i < documents.Count; i++)
{
if (documents[i].ContainsKey(pair.Key))
{
count++;
}
}
if (count == 0) return; // Retorna si la palabara no está en ningún documento
IDFs[pair.Key] = (float)Math.Log((float)documents.Count/(count));
}
Similitud.Modulo(documents, IDFs); // Calclula el peso de cada palabra y el modulo de los documentos
}
// Llama a clacular el modulo de cada documento
public static void Modulo(Dictionary<int, Info> documents, Dictionary<string, float> IDFs)
{
for (int i = 0; i < documents.Count; i++)
{
documents[i].Modulo(IDFs);
}
}
// Guarda los indices de las palabras asociadas a operadores de inclusion y exclusion
private static List<int>[] SeparateWords(List<int>[] operators)
{
List<int>[] a = new List<int>[2];
a[0] = new List<int>();
a[1] = new List<int>();
for (int i = 0; i < operators[1].Count; i++)
{
if (operators[1][i] == 0)
{
a[0].Add(i);
}
else if (operators[1][i] == 1)
{
a[1].Add(i);
}
else
{
continue;
}
}
return a;
}
private static bool ContainsWord(Info info, List<int> index, List<string> words)
{
foreach (int number in index)
{
if (info.ContainsKey(words[number]))
{
return true;
}
}
return false;
}
// Calculo de array similitud
private static float[,] Cosin(Query query, Corpus corpus)
{
float[,] similitud = new float[3, corpus.documents.Count];
List<int>[] separatewords = SeparateWords(query.operators);
float mq = query.info[0].modulo;
float mr = query.info[1].modulo;
float ms = query.info[2].modulo;
for (int i = 0; i < similitud.GetLength(1); i++)
{
if (ContainsWord(corpus.documents[i], separatewords[1], query.list[0])) continue;
if (separatewords[0].Count > 0 && !ContainsWord(corpus.documents[i], separatewords[0], query.list[0])) continue;
float prodvectq = VectorialProduct(query, corpus.documents, i, 0);
float prodvectr = VectorialProduct(query, corpus.documents, i, 1);
float prodvects = VectorialProduct(query, corpus.documents, i, 2);
float mi = corpus.documents[i].modulo;
if (mi == 0) continue;
if (mq != 0) similitud[0,i] = prodvectq / (mq * mi);
if (mr != 0) similitud[1,i] = prodvectr / (float)(Math.Pow(Math.E, 3) * mr * mi);
if (ms != 0) similitud[2,i] = prodvects / (float)(Math.Pow(Math.E, 5) * ms * mi);
}
return SortedDocuments(AuxMethods.Closeness(Sum(similitud), query, corpus));
}
// Suma todos los elementos de cada columna de un array bidimensional y devuelve una sola fila de elementos
private static float[] Sum(float[,] array)
{
float[] newarray = new float[array.GetLength(1)];
for (int i = 0; i < newarray.Length; i++)
{
newarray[i] = array[0,i] + array[1,i] + array[2,i];
}
return newarray;
}
// Calcula el producto vectorial
private static float VectorialProduct(Query query, Dictionary<int, Info> documents, int a, int j)
{
float prodvect = 0;
for (int i = 0; i < query.list[j].Count; i++)
{
if (!documents[a].weigths.ContainsKey(query.list[j][i])) continue;
prodvect += documents[a].weigths[query.list[j][i]]*query.info[j].weigths[query.list[j][i]];
}
return prodvect;
}
// Devuelve los documentos en orden de importancia
private static float[,] SortedDocuments(float[] score)
{
float[] originalscores = new float[score.Length];
for (int i = 0; i < score.Length; i++)
{
originalscores[i] = score[i];
}
// Ordenar el array de scores
Array.Sort(score);
Array.Reverse(score);
// Este array deberá guardar las posiciones iniciales de los docuementos antes de ordenarlos
int[] originalplaces = new int[score.Length];
bool[] pased = new bool[score.Length];
for (int i = 0; i < score.Length; i++)
{
int k = Index(originalscores, score[i]);
while (pased[k])
{
float[] scorei = new float[score.Length-k-1];
for (int j = 0; j < scorei.Length; j++)
{
scorei[j] = originalscores[k+j+1];
}
k += 1 + Index(scorei, score[i]);
}
originalplaces[i] = k;
pased[k] = true;
}
return MixArrays(score, originalplaces);
}
// Indice de un elemento en un array
private static int Index(float[] array, float value)
{
for (int i = 0; i < array.Length; i++)
{
if (array[i] == value)
{
return i;
}
}
return 1;
}
// Une dos filas
private static float[,] MixArrays(float[] a1, int[] a2)
{
float[,] mixarrays = new float[2, a1.Length];
for (int i = 0; i < a1.Length; i++)
{
mixarrays[0,i] = a1[i];
mixarrays[1,i] = a2[i];
}
return mixarrays;
}
// Calcula el peso total de una palabra entre todos los docs
public static float TotalWeight(string word, Corpus corpus)
{
float totalweight = 0;
for (int i = 0; i < corpus.documents.Count; i++)
{
totalweight += (corpus.documents[i].weigths.ContainsKey(word))? corpus.documents[i].weigths[word] : 0;
}
return totalweight;
}
// En una lista de palabras seleciiona la mejor relativa al cuerpo de docuementos
public static string BestWord(List<string> list, Corpus corpus)
{
if (list.Count == 0) return "";
string bestword = "";
for (int i = 0; i < list.Count; i++)
{
if (!corpus.IDFs.ContainsKey(list[i])) continue;
bestword = TotalWeight(bestword, corpus) < TotalWeight(list[i], corpus)? list[i] : bestword;
}
return bestword;
}
}
} | 34.44 | 128 | 0.47219 | [
"MIT"
] | asciber45/moogle-2021 | MoogleEngine/Similitud.cs | 7,752 | C# |
using System;
using System.Linq;
using System.Reflection;
using HarmonyLib;
using RimWorld;
using Verse;
namespace Adrenaline
{
[StaticConstructorOnStartup]
public static class HarmonyPatches
{
static HarmonyPatches()
{
Adrenaline.HarmonyInstance.PatchAll();
try
{
// PawnInventoryGenerator.GiveCombatEnhancingDrugs source predicate
Patch_PawnInventoryGenerator.ManualPatch_GiveCombatEnhancingDrugs_source_predicate.predicateType =
typeof(PawnInventoryGenerator).GetNestedTypes(BindingFlags.NonPublic | BindingFlags.Instance)
.First(t => t.Name.Contains("GiveCombatEnhancingDrugs"));
Adrenaline.HarmonyInstance.Patch(
Patch_PawnInventoryGenerator.ManualPatch_GiveCombatEnhancingDrugs_source_predicate.predicateType
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.First(m => m.ReturnType == typeof(bool)),
transpiler: new HarmonyMethod(
typeof(Patch_PawnInventoryGenerator.ManualPatch_GiveCombatEnhancingDrugs_source_predicate),
"Transpiler"));
}
catch (Exception exception)
{
if (Prefs.DevMode)
{
Log.Message(exception.ToString());
}
}
}
}
} | 36.04878 | 116 | 0.600135 | [
"MIT"
] | emipa606/XNDAdrenaline | Source/Adrenaline/HarmonyPatches/HarmonyPatches.cs | 1,480 | C# |
#if XENKO_GRAPHICS_API_OPENGLES
//------------------------------------------------------------------------------
// <auto-generated>
// Xenko Effect Compiler File Generated:
// Effect [EmissiveSpriteEffect]
//
// Command Line: D:\Xenko\sources\engine\Xenko.Graphics\Shaders.Bytecodes\..\..\..\..\sources\assets\Xenko.Core.Assets.CompilerApp\bin\Release\net472\Xenko.Core.Assets.CompilerApp.exe --platform=Windows --property:RuntimeIdentifier=win-opengles --output-path=D:\Xenko\sources\engine\Xenko.Graphics\Shaders.Bytecodes\obj\app_data --build-path=D:\Xenko\sources\engine\Xenko.Graphics\Shaders.Bytecodes\obj\build_app_data --package-file=Graphics.xkpkg
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Xenko.Graphics
{
public partial class EmissiveSpriteEffect
{
private static readonly byte[] binaryBytecode = new byte[] {
7, 192, 254, 239, 0, 0, 9, 0, 0, 0, 0, 0, 22, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 80, 111, 105, 110, 116, 83, 97, 109, 112, 108, 101, 114, 0, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 23, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 76, 105, 110, 101, 97, 114, 83, 97, 109, 112, 108, 101, 114, 21, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0,
0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 29, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 76, 105, 110, 101, 97, 114, 66, 111, 114, 100, 101, 114, 83, 97, 109,
112, 108, 101, 114, 21, 0, 0, 0, 4, 0, 0, 0, 4, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 44, 84, 101, 120, 116, 117,
114, 105, 110, 103, 46, 76, 105, 110, 101, 97, 114, 67, 108, 97, 109, 112, 67, 111, 109, 112, 97, 114, 101, 76, 101, 115, 115, 69, 113, 117, 97, 108, 83, 97, 109, 112, 108, 101, 114, 148, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 4,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 28, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 65, 110, 105, 115, 111, 116, 114, 111, 112, 105, 99, 83, 97, 109, 112, 108, 101, 114, 85, 0, 0, 0, 3, 0,
0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 34, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 65, 110, 105, 115, 111,
116, 114, 111, 112, 105, 99, 82, 101, 112, 101, 97, 116, 83, 97, 109, 112, 108, 101, 114, 85, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
255, 127, 255, 255, 255, 127, 127, 0, 0, 28, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 80, 111, 105, 110, 116, 82, 101, 112, 101, 97, 116, 83, 97, 109, 112, 108, 101, 114, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 29, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 76, 105, 110, 101, 97, 114, 82, 101, 112, 101, 97, 116, 83, 97, 109, 112, 108, 101, 114, 21, 0, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 0, 23, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 82, 101, 112, 101, 97,
116, 83, 97, 109, 112, 108, 101, 114, 21, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 255, 127, 255, 255, 255, 127, 127, 0, 6, 0, 0,
0, 0, 7, 80, 101, 114, 68, 114, 97, 119, 10, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 7, 80, 101, 114, 68, 114, 97, 119, 0, 7, 80, 101, 114, 68, 114, 97, 119, 1, 0,
0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 1, 0, 7, 71, 108, 111, 98, 97, 108, 115, 10, 0, 0, 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 7, 71, 108, 111, 98, 97, 108, 115, 0,
7, 71, 108, 111, 98, 97, 108, 115, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 1, 0, 18, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 48, 9, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 13, 84, 101, 120, 116, 117, 114, 101, 48, 95, 105, 100, 49, 52, 1, 5, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 1, 0, 17, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 83, 97, 109, 112, 108, 101, 114, 8, 0, 0, 0, 10,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 12, 83, 97, 109, 112, 108, 101, 114, 95, 105, 100, 52, 50, 1, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 1, 0, 38, 69, 109, 105, 115, 115,
105, 118, 101, 83, 112, 114, 105, 116, 101, 69, 102, 102, 101, 99, 116, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101, 120, 116, 117, 114, 101, 49, 9, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 22, 73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101, 120, 116, 117, 114, 101, 49, 95, 105, 100, 55, 56, 1, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 1, 0, 38, 69, 109, 105, 115, 115, 105, 118, 101, 83, 112, 114, 105, 116, 101, 69, 102, 102, 101, 99, 116, 46,
73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101, 120, 116, 117, 114, 101, 50, 9, 0, 0, 0, 7, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 22, 73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101,
120, 116, 117, 114, 101, 50, 95, 105, 100, 55, 57, 1, 1, 0, 0, 0, 255, 255, 255, 255, 1, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 7, 80, 101, 114, 68, 114, 97, 119, 64, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0,
0, 4, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 1, 1, 0, 26, 83, 112, 114, 105, 116, 101, 66, 97, 115, 101, 46, 77, 97, 116, 114, 105, 120, 84, 114, 97, 110, 115, 102, 111, 114, 109, 0, 20, 77, 97, 116, 114, 105, 120, 84, 114, 97, 110, 115, 102, 111, 114, 109, 95, 105, 100, 55,
51, 0, 0, 0, 0, 64, 0, 0, 0, 1, 1, 0, 0, 7, 71, 108, 111, 98, 97, 108, 115, 112, 0, 0, 0, 1, 0, 0, 0, 0, 14, 0, 0, 0, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101,
120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 48, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 48, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 53, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3,
0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 49, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 49, 84, 101, 120, 101,
108, 83, 105, 122, 101, 95, 105, 100, 49, 55, 8, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114,
101, 50, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 50, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 57, 16, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,
0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 51, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 51, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 49, 24, 0, 0, 0,
8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 52, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84,
101, 120, 116, 117, 114, 101, 52, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 51, 32, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117,
114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 53, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 53, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 53, 40, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0,
1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 54, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 54, 84, 101, 120, 101, 108, 83, 105,
122, 101, 95, 105, 100, 50, 55, 48, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 55, 84,
101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 55, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 57, 56, 0, 0, 0, 8, 0, 0, 0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0,
0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 56, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116, 117, 114, 101, 56, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 51, 49, 64, 0, 0, 0, 8, 0, 0,
0, 1, 1, 1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 27, 84, 101, 120, 116, 117, 114, 105, 110, 103, 46, 84, 101, 120, 116, 117, 114, 101, 57, 84, 101, 120, 101, 108, 83, 105, 122, 101, 0, 22, 84, 101, 120, 116,
117, 114, 101, 57, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 51, 51, 72, 0, 0, 0, 8, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 1, 0, 33, 69, 109, 105, 115, 115, 105, 118, 101,
83, 112, 114, 105, 116, 101, 69, 102, 102, 101, 99, 116, 46, 85, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 0, 17, 85, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 53, 80, 0, 0, 0, 4, 0, 0, 0, 1, 1, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 1, 0, 34, 69, 109, 105, 115, 115, 105, 118, 101, 83, 112, 114, 105, 116, 101, 69, 102, 102, 101, 99, 116, 46, 66, 97, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 0, 18, 66, 97, 115, 101, 73, 110, 116, 101, 110, 115,
105, 116, 121, 95, 105, 100, 55, 54, 84, 0, 0, 0, 4, 0, 0, 0, 1, 1, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 1, 0, 40, 69, 109, 105, 115, 115, 105, 118, 101, 83, 112, 114, 105, 116, 101, 69, 102, 102, 101,
99, 116, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 77, 117, 108, 116, 105, 112, 108, 105, 101, 114, 0, 24, 73, 110, 116, 101, 110, 115, 105, 116, 121, 77, 117, 108, 116, 105, 112, 108, 105, 101, 114, 95, 105, 100, 55, 55, 88, 0, 0, 0, 4, 0, 0, 0, 1, 1, 13, 0, 0, 0, 3, 0,
0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 1, 1, 0, 26, 69, 109, 105, 115, 115, 105, 118, 101, 83, 112, 114, 105, 116, 101, 69, 102, 102, 101, 99, 116, 46, 67, 111, 108, 111, 114, 0, 10, 67, 111, 108, 111, 114, 95, 105, 100, 56, 48, 96, 0, 0, 0,
16, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 8, 80, 79, 83, 73, 84, 73, 79, 78, 0, 0, 0, 0, 0, 8, 84, 69, 88, 67, 79, 79, 82, 68, 0, 0, 0, 0, 0, 5, 0, 0, 0, 20, 69, 109, 105, 115, 115, 105, 118, 101, 83,
112, 114, 105, 116, 101, 69, 102, 102, 101, 99, 116, 1, 248, 176, 92, 226, 252, 142, 97, 84, 239, 182, 249, 8, 216, 138, 53, 53, 10, 83, 112, 114, 105, 116, 101, 66, 97, 115, 101, 1, 227, 25, 196, 119, 122, 150, 76, 62, 187, 143, 130, 89, 14, 78, 39, 241, 10, 83, 104, 97, 100, 101, 114, 66,
97, 115, 101, 1, 172, 190, 61, 77, 68, 160, 70, 238, 222, 135, 17, 118, 190, 233, 199, 84, 16, 83, 104, 97, 100, 101, 114, 66, 97, 115, 101, 83, 116, 114, 101, 97, 109, 1, 163, 165, 191, 129, 133, 242, 163, 216, 153, 114, 41, 63, 128, 100, 48, 211, 9, 84, 101, 120, 116, 117, 114, 105, 110, 103,
1, 230, 218, 239, 13, 217, 10, 85, 249, 84, 156, 111, 93, 41, 30, 97, 165, 0, 2, 0, 0, 0, 0, 1, 0, 0, 0, 1, 195, 245, 175, 193, 17, 253, 179, 158, 4, 12, 134, 71, 13, 81, 23, 99, 0, 0, 16, 0, 0, 0, 184, 22, 35, 118, 101, 114, 115, 105, 111, 110, 32, 51, 48, 48,
32, 101, 115, 13, 10, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 104, 105, 103, 104, 112, 32, 102, 108, 111, 97, 116, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 104, 105, 103, 104, 112, 32, 105, 110, 116, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108,
111, 119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 51, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 67, 117, 98, 101, 83, 104, 97, 100, 111, 119, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119,
112, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 83, 104, 97, 100, 111, 119, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111,
119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 83, 104, 97, 100, 111, 119, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 105, 115, 97, 109, 112, 108, 101, 114, 50, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32,
108, 111, 119, 112, 32, 105, 115, 97, 109, 112, 108, 101, 114, 51, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 105, 115, 97, 109, 112, 108, 101, 114, 67, 117, 98, 101, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 105,
115, 97, 109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112, 108, 101, 114, 50, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109,
112, 108, 101, 114, 51, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112, 108, 101, 114, 67, 117, 98, 101, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112, 108, 101, 114, 50, 68,
65, 114, 114, 97, 121, 59, 13, 10, 13, 10, 35, 100, 101, 102, 105, 110, 101, 32, 116, 101, 120, 101, 108, 70, 101, 116, 99, 104, 66, 117, 102, 102, 101, 114, 80, 108, 97, 99, 101, 104, 111, 108, 100, 101, 114, 13, 10, 115, 116, 114, 117, 99, 116, 32, 86, 83, 95, 83, 84, 82, 69, 65, 77, 83,
32, 13, 10, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 55, 50, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52,
32, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 48, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 59, 13, 10, 125, 59, 13, 10, 115, 116, 114, 117, 99, 116, 32, 86, 83, 95, 79,
85, 84, 80, 85, 84, 32, 13, 10, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 48, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55,
52, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 125, 59, 13, 10, 115, 116, 114, 117, 99, 116, 32, 86, 83, 95, 73, 78, 80, 85, 84, 32, 13, 10, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 80,
111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 55, 50, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 125, 59, 13, 10, 108, 97, 121, 111, 117, 116, 40, 115, 116, 100, 49, 52, 48, 41, 32, 32, 117, 110, 105, 102,
111, 114, 109, 32, 80, 101, 114, 68, 114, 97, 119, 32, 123, 13, 10, 32, 32, 32, 32, 109, 97, 116, 52, 32, 77, 97, 116, 114, 105, 120, 84, 114, 97, 110, 115, 102, 111, 114, 109, 95, 105, 100, 55, 51, 59, 13, 10, 125, 59, 13, 10, 108, 97, 121, 111, 117, 116, 40, 115, 116, 100, 49, 52, 48,
41, 32, 32, 117, 110, 105, 102, 111, 114, 109, 32, 71, 108, 111, 98, 97, 108, 115, 32, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 48, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 53, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50,
32, 84, 101, 120, 116, 117, 114, 101, 49, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 55, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 50, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 57, 59, 13, 10, 32, 32, 32, 32,
118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 51, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 49, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 52, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 51, 59, 13, 10,
32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 53, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 53, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 54, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50,
55, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 55, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 57, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 56, 84, 101, 120, 101, 108, 83, 105, 122, 101,
95, 105, 100, 51, 49, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 57, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 51, 51, 59, 13, 10, 32, 32, 32, 32, 98, 111, 111, 108, 32, 85, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95,
105, 100, 55, 53, 59, 13, 10, 32, 32, 32, 32, 102, 108, 111, 97, 116, 32, 66, 97, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 54, 59, 13, 10, 32, 32, 32, 32, 102, 108, 111, 97, 116, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 77, 117, 108, 116, 105, 112, 108,
105, 101, 114, 95, 105, 100, 55, 55, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 67, 111, 108, 111, 114, 95, 105, 100, 56, 48, 59, 13, 10, 125, 59, 13, 10, 117, 110, 105, 102, 111, 114, 109, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121,
84, 101, 120, 116, 117, 114, 101, 49, 95, 105, 100, 55, 56, 95, 83, 97, 109, 112, 108, 101, 114, 95, 105, 100, 52, 50, 59, 13, 10, 117, 110, 105, 102, 111, 114, 109, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101, 120, 116, 117, 114, 101, 50,
95, 105, 100, 55, 57, 95, 83, 97, 109, 112, 108, 101, 114, 95, 105, 100, 52, 50, 59, 13, 10, 111, 117, 116, 32, 118, 101, 99, 52, 32, 118, 95, 73, 78, 84, 69, 78, 83, 73, 84, 89, 95, 73, 68, 55, 52, 59, 13, 10, 111, 117, 116, 32, 118, 101, 99, 50, 32, 118, 95, 84, 69, 88, 67,
79, 79, 82, 68, 48, 59, 13, 10, 105, 110, 32, 118, 101, 99, 52, 32, 97, 95, 80, 79, 83, 73, 84, 73, 79, 78, 48, 59, 13, 10, 105, 110, 32, 118, 101, 99, 50, 32, 97, 95, 84, 69, 88, 67, 79, 79, 82, 68, 48, 59, 13, 10, 118, 111, 105, 100, 32, 86, 83, 77, 97, 105, 110, 95,
105, 100, 50, 40, 105, 110, 111, 117, 116, 32, 86, 83, 95, 83, 84, 82, 69, 65, 77, 83, 32, 115, 116, 114, 101, 97, 109, 115, 41, 13, 10, 123, 13, 10, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100,
48, 32, 61, 32, 40, 115, 116, 114, 101, 97, 109, 115, 46, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 55, 50, 32, 42, 32, 77, 97, 116, 114, 105, 120, 84, 114, 97, 110, 115, 102, 111, 114, 109, 95, 105, 100, 55, 51, 41, 59, 13, 10, 125, 13, 10, 118, 111, 105, 100, 32, 109, 97, 105,
110, 40, 41, 13, 10, 123, 13, 10, 32, 32, 32, 32, 86, 83, 95, 73, 78, 80, 85, 84, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 59, 13, 10, 32, 32, 32, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 32, 61, 32, 97,
95, 84, 69, 88, 67, 79, 79, 82, 68, 48, 59, 13, 10, 32, 32, 32, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 55, 50, 32, 61, 32, 97, 95, 80, 79, 83, 73, 84, 73, 79, 78, 48, 59, 13, 10, 32, 32, 32, 32, 86, 83, 95,
83, 84, 82, 69, 65, 77, 83, 32, 115, 116, 114, 101, 97, 109, 115, 59, 13, 10, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 55, 50, 32, 61, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 80, 111, 115, 105, 116, 105, 111, 110,
95, 105, 100, 55, 50, 59, 13, 10, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 32, 61, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 32, 32,
32, 32, 86, 83, 77, 97, 105, 110, 95, 105, 100, 50, 40, 115, 116, 114, 101, 97, 109, 115, 41, 59, 13, 10, 32, 32, 32, 32, 105, 102, 32, 40, 85, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 53, 41, 13, 10, 32, 32, 32, 32, 123, 13, 10, 32, 32, 32, 32, 32,
32, 32, 32, 118, 101, 99, 51, 32, 97, 118, 103, 32, 61, 32, 40, 116, 101, 120, 116, 117, 114, 101, 76, 111, 100, 40, 73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101, 120, 116, 117, 114, 101, 49, 95, 105, 100, 55, 56, 95, 83, 97, 109, 112, 108, 101, 114, 95, 105, 100, 52, 50, 44, 32, 118,
101, 99, 50, 40, 48, 46, 48, 44, 32, 48, 46, 48, 41, 44, 32, 49, 54, 46, 48, 41, 46, 114, 103, 98, 32, 43, 32, 116, 101, 120, 116, 117, 114, 101, 76, 111, 100, 40, 73, 110, 116, 101, 110, 115, 105, 116, 121, 84, 101, 120, 116, 117, 114, 101, 50, 95, 105, 100, 55, 57, 95, 83, 97, 109,
112, 108, 101, 114, 95, 105, 100, 52, 50, 44, 32, 118, 101, 99, 50, 40, 48, 46, 48, 44, 32, 48, 46, 48, 41, 44, 32, 49, 54, 46, 48, 41, 46, 114, 103, 98, 41, 32, 42, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 77, 117, 108, 116, 105, 112, 108, 105, 101, 114, 95, 105, 100, 55, 55,
59, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 32, 61, 32, 118, 101, 99, 52, 40, 109, 105, 110, 40, 49, 46, 48, 44, 32, 97, 118, 103, 46, 114, 32, 43, 32, 66, 97, 115, 101, 73, 110,
116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 54, 41, 44, 32, 109, 105, 110, 40, 49, 46, 48, 44, 32, 97, 118, 103, 46, 103, 32, 43, 32, 66, 97, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 54, 41, 44, 32, 109, 105, 110, 40, 49, 46, 48, 44, 32, 97, 118,
103, 46, 98, 32, 43, 32, 66, 97, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 54, 41, 44, 32, 49, 46, 48, 41, 59, 13, 10, 32, 32, 32, 32, 125, 13, 10, 32, 32, 32, 32, 86, 83, 95, 79, 85, 84, 80, 85, 84, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95,
48, 59, 13, 10, 32, 32, 32, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 48, 32, 61, 32, 115, 116, 114, 101, 97, 109, 115, 46, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110,
95, 105, 100, 48, 59, 13, 10, 32, 32, 32, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 32, 61, 32, 115, 116, 114, 101, 97, 109, 115, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 59, 13, 10,
32, 32, 32, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 32, 61, 32, 115, 116, 114, 101, 97, 109, 115, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 32, 32, 32, 32, 103, 108, 95, 80, 111,
115, 105, 116, 105, 111, 110, 32, 61, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 48, 59, 13, 10, 32, 32, 32, 32, 118, 95, 73, 78, 84, 69, 78, 83, 73, 84, 89, 95, 73, 68, 55, 52, 32, 61,
32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 59, 13, 10, 32, 32, 32, 32, 118, 95, 84, 69, 88, 67, 79, 79, 82, 68, 48, 32, 61, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 84, 101, 120, 67, 111, 111,
114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 32, 32, 32, 32, 103, 108, 95, 80, 111, 115, 105, 116, 105, 111, 110, 46, 122, 32, 61, 32, 103, 108, 95, 80, 111, 115, 105, 116, 105, 111, 110, 46, 122, 32, 42, 32, 50, 46, 48, 32, 45, 32, 103, 108, 95, 80, 111, 115, 105, 116, 105, 111, 110, 46,
119, 59, 13, 10, 32, 32, 32, 32, 103, 108, 95, 80, 111, 115, 105, 116, 105, 111, 110, 46, 121, 32, 61, 32, 45, 103, 108, 95, 80, 111, 115, 105, 116, 105, 111, 110, 46, 121, 59, 13, 10, 125, 13, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 1, 235, 226, 193, 144, 198, 162, 238, 205, 8,
48, 95, 95, 95, 82, 116, 123, 0, 0, 16, 0, 0, 0, 150, 18, 35, 118, 101, 114, 115, 105, 111, 110, 32, 51, 48, 48, 32, 101, 115, 13, 10, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 104, 105, 103, 104, 112, 32, 102, 108, 111, 97, 116, 59, 13, 10, 112, 114, 101, 99, 105, 115,
105, 111, 110, 32, 104, 105, 103, 104, 112, 32, 105, 110, 116, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 51, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97, 109, 112, 108, 101,
114, 67, 117, 98, 101, 83, 104, 97, 100, 111, 119, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 83, 104, 97, 100, 111, 119, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97,
109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 83, 104, 97, 100, 111, 119, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108,
111, 119, 112, 32, 105, 115, 97, 109, 112, 108, 101, 114, 50, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 105, 115, 97, 109, 112, 108, 101, 114, 51, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 105, 115, 97, 109,
112, 108, 101, 114, 67, 117, 98, 101, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 105, 115, 97, 109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112,
108, 101, 114, 50, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112, 108, 101, 114, 51, 68, 59, 13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112, 108, 101, 114, 67, 117, 98, 101, 59,
13, 10, 112, 114, 101, 99, 105, 115, 105, 111, 110, 32, 108, 111, 119, 112, 32, 117, 115, 97, 109, 112, 108, 101, 114, 50, 68, 65, 114, 114, 97, 121, 59, 13, 10, 13, 10, 35, 100, 101, 102, 105, 110, 101, 32, 116, 101, 120, 101, 108, 70, 101, 116, 99, 104, 66, 117, 102, 102, 101, 114, 80, 108, 97,
99, 101, 104, 111, 108, 100, 101, 114, 13, 10, 115, 116, 114, 117, 99, 116, 32, 80, 83, 95, 83, 84, 82, 69, 65, 77, 83, 32, 13, 10, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 32, 32, 32, 32, 118, 101,
99, 52, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105, 100, 50, 59, 13, 10, 125, 59, 13, 10, 115, 116, 114, 117, 99, 116, 32, 80, 83, 95, 79, 85, 84,
80, 85, 84, 32, 13, 10, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105, 100, 50, 59, 13, 10, 125, 59, 13, 10, 115, 116, 114, 117, 99, 116, 32, 80, 83, 95, 73, 78, 80, 85, 84, 32, 13, 10, 123, 13, 10, 32, 32, 32,
32, 118, 101, 99, 52, 32, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 48, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84,
101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 125, 59, 13, 10, 108, 97, 121, 111, 117, 116, 40, 115, 116, 100, 49, 52, 48, 41, 32, 32, 117, 110, 105, 102, 111, 114, 109, 32, 71, 108, 111, 98, 97, 108, 115, 32, 123, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84,
101, 120, 116, 117, 114, 101, 48, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 53, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 49, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 55, 59, 13, 10, 32, 32, 32, 32, 118, 101,
99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 50, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 49, 57, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 51, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 49, 59, 13, 10, 32, 32,
32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 52, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 51, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 53, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 53, 59,
13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 54, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 50, 55, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 55, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105,
100, 50, 57, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 56, 84, 101, 120, 101, 108, 83, 105, 122, 101, 95, 105, 100, 51, 49, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 50, 32, 84, 101, 120, 116, 117, 114, 101, 57, 84, 101, 120, 101, 108, 83, 105,
122, 101, 95, 105, 100, 51, 51, 59, 13, 10, 32, 32, 32, 32, 98, 111, 111, 108, 32, 85, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 53, 59, 13, 10, 32, 32, 32, 32, 102, 108, 111, 97, 116, 32, 66, 97, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105,
100, 55, 54, 59, 13, 10, 32, 32, 32, 32, 102, 108, 111, 97, 116, 32, 73, 110, 116, 101, 110, 115, 105, 116, 121, 77, 117, 108, 116, 105, 112, 108, 105, 101, 114, 95, 105, 100, 55, 55, 59, 13, 10, 32, 32, 32, 32, 118, 101, 99, 52, 32, 67, 111, 108, 111, 114, 95, 105, 100, 56, 48, 59, 13,
10, 125, 59, 13, 10, 117, 110, 105, 102, 111, 114, 109, 32, 115, 97, 109, 112, 108, 101, 114, 50, 68, 32, 84, 101, 120, 116, 117, 114, 101, 48, 95, 105, 100, 49, 52, 95, 83, 97, 109, 112, 108, 101, 114, 95, 105, 100, 52, 50, 59, 13, 10, 108, 97, 121, 111, 117, 116, 40, 108, 111, 99, 97, 116,
105, 111, 110, 32, 61, 32, 48, 41, 32, 32, 111, 117, 116, 32, 118, 101, 99, 52, 32, 111, 117, 116, 95, 103, 108, 95, 102, 114, 97, 103, 100, 97, 116, 97, 95, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105, 100, 50, 59, 13, 10, 105, 110, 32, 118, 101, 99, 52, 32, 118, 95, 73,
78, 84, 69, 78, 83, 73, 84, 89, 95, 73, 68, 55, 52, 59, 13, 10, 105, 110, 32, 118, 101, 99, 50, 32, 118, 95, 84, 69, 88, 67, 79, 79, 82, 68, 48, 59, 13, 10, 118, 101, 99, 52, 32, 83, 104, 97, 100, 105, 110, 103, 95, 105, 100, 51, 40, 105, 110, 111, 117, 116, 32, 80, 83, 95,
83, 84, 82, 69, 65, 77, 83, 32, 115, 116, 114, 101, 97, 109, 115, 41, 13, 10, 123, 13, 10, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110, 32, 116, 101, 120, 116, 117, 114, 101, 40, 84, 101, 120, 116, 117, 114, 101, 48, 95, 105, 100, 49, 52, 95, 83, 97, 109, 112, 108, 101, 114, 95, 105, 100,
52, 50, 44, 32, 115, 116, 114, 101, 97, 109, 115, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 41, 59, 13, 10, 125, 13, 10, 118, 101, 99, 52, 32, 83, 104, 97, 100, 105, 110, 103, 95, 105, 100, 52, 40, 105, 110, 111, 117, 116, 32, 80, 83, 95, 83, 84, 82, 69, 65, 77,
83, 32, 115, 116, 114, 101, 97, 109, 115, 41, 13, 10, 123, 13, 10, 32, 32, 32, 32, 105, 102, 32, 40, 85, 115, 101, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 53, 41, 13, 10, 32, 32, 32, 32, 123, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110,
32, 83, 104, 97, 100, 105, 110, 103, 95, 105, 100, 51, 40, 115, 116, 114, 101, 97, 109, 115, 41, 32, 42, 32, 115, 116, 114, 101, 97, 109, 115, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 32, 42, 32, 67, 111, 108, 111, 114, 95, 105, 100, 56, 48, 59, 13, 10, 32, 32,
32, 32, 125, 13, 10, 32, 32, 32, 32, 101, 108, 115, 101, 13, 10, 32, 32, 32, 32, 123, 13, 10, 32, 32, 32, 32, 32, 32, 32, 32, 114, 101, 116, 117, 114, 110, 32, 83, 104, 97, 100, 105, 110, 103, 95, 105, 100, 51, 40, 115, 116, 114, 101, 97, 109, 115, 41, 32, 42, 32, 67, 111, 108, 111,
114, 95, 105, 100, 56, 48, 59, 13, 10, 32, 32, 32, 32, 125, 13, 10, 125, 13, 10, 118, 111, 105, 100, 32, 109, 97, 105, 110, 40, 41, 13, 10, 123, 13, 10, 32, 32, 32, 32, 80, 83, 95, 73, 78, 80, 85, 84, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 59, 13, 10, 32, 32, 32, 32,
95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 32, 61, 32, 118, 95, 84, 69, 88, 67, 79, 79, 82, 68, 48, 59, 13, 10, 32, 32, 32, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95,
105, 100, 55, 52, 32, 61, 32, 118, 95, 73, 78, 84, 69, 78, 83, 73, 84, 89, 95, 73, 68, 55, 52, 59, 13, 10, 32, 32, 32, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 83, 104, 97, 100, 105, 110, 103, 80, 111, 115, 105, 116, 105, 111, 110, 95, 105, 100, 48, 32, 61, 32, 103, 108,
95, 70, 114, 97, 103, 67, 111, 111, 114, 100, 59, 13, 10, 32, 32, 32, 32, 80, 83, 95, 83, 84, 82, 69, 65, 77, 83, 32, 115, 116, 114, 101, 97, 109, 115, 59, 13, 10, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52,
32, 61, 32, 95, 48, 105, 110, 112, 117, 116, 95, 48, 46, 73, 110, 116, 101, 110, 115, 105, 116, 121, 95, 105, 100, 55, 52, 59, 13, 10, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 32, 61, 32, 95, 48, 105, 110, 112, 117,
116, 95, 48, 46, 84, 101, 120, 67, 111, 111, 114, 100, 95, 105, 100, 54, 50, 59, 13, 10, 32, 32, 32, 32, 115, 116, 114, 101, 97, 109, 115, 46, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105, 100, 50, 32, 61, 32, 83, 104, 97, 100, 105, 110, 103, 95, 105, 100, 52, 40, 115, 116,
114, 101, 97, 109, 115, 41, 59, 13, 10, 32, 32, 32, 32, 80, 83, 95, 79, 85, 84, 80, 85, 84, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 59, 13, 10, 32, 32, 32, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105,
100, 50, 32, 61, 32, 115, 116, 114, 101, 97, 109, 115, 46, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105, 100, 50, 59, 13, 10, 32, 32, 32, 32, 111, 117, 116, 95, 103, 108, 95, 102, 114, 97, 103, 100, 97, 116, 97, 95, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105,
100, 50, 32, 61, 32, 95, 48, 111, 117, 116, 112, 117, 116, 95, 48, 46, 67, 111, 108, 111, 114, 84, 97, 114, 103, 101, 116, 95, 105, 100, 50, 59, 13, 10, 125, 13, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
}
}
#endif
| 229.639594 | 451 | 0.494485 | [
"MIT"
] | guygodin/xenko | sources/engine/Xenko.Graphics/Shaders.Bytecodes/EmissiveSpriteEffect.bytecode.OpenGLES.Level_11_0.cs | 45,241 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Grpc.Core;
namespace Anno.Rpc.Client
{
public static class GrpcExtensions
{
public static CallOptions GetCallOptions(this double timeOut) {
var callOption = new CallOptions();
callOption.WithDeadline(DateTime.Now.AddMilliseconds(timeOut));
return callOption;
}
public static CallOptions GetCallOptions(this int timeOut)
{
var callOption = new CallOptions();
callOption.WithDeadline(DateTime.Now.AddMilliseconds(timeOut));
return callOption;
}
}
}
| 28.043478 | 75 | 0.654264 | [
"Apache-2.0"
] | jl632541832/Anno.Core | src/Core/Grpc/Anno.Rpc.Client/GrpcExtensions.cs | 647 | C# |
namespace FkThat.Mockables
{
/// <summary>
/// Wrapper to the <c cref="Console"/> class implementing the <c cref="IConsole"/> interface.
/// </summary>
public class ConsoleAdapter : IConsole
{
/// <summary>
/// Gets the standard output stream.
/// </summary>
public TextWriter Out => Console.Out;
/// <summary>
/// Gets the standard error stream.
/// </summary>
public TextWriter Error => Console.Error;
/// <summary>
/// Gets the standard input stream.
/// </summary>
public TextReader In => Console.In;
}
}
| 26.291667 | 97 | 0.549921 | [
"MIT"
] | fkthat/FkThat.Mockables | src/FkThat.Mockables/ConsoleAdapter.cs | 631 | C# |
using Microsoft.EntityFrameworkCore;
namespace RPGGen.CharacterService.Domain.Services
{
public interface ICharacterService
{
Task<IEnumerable<Character>> GetCharacters();
Task<Character> GetCharacter(Guid characterId);
Task AddCharacter(Character value);
Task UpdateCharacter(Guid id, Character value);
Task DeleteCharacter(Guid id);
}
public class CharacterService : ICharacterService
{
private readonly IAppDbContext _context;
public CharacterService(IAppDbContext context)
{
_context = context;
}
public async Task AddCharacter(Character value)
{
_context.Characters.Add(value);
await _context.SaveChangesAsync();
}
public async Task DeleteCharacter(Guid id)
{
var item = await _context.Characters.FirstAsync();
_context.Characters.Remove(item);
await _context.SaveChangesAsync();
}
public async Task<IEnumerable<Character>> GetCharacters() => await _context.Characters.ToListAsync();
public async Task<Character> GetCharacter(Guid characterId)
{
var character = await _context.Characters
.Where(c => c.CharacterId == characterId)
.Include("InventoryItems.Item")
.FirstAsync();
return character;
}
public async Task UpdateCharacter(Guid id, Character updatedItem)
{
var item = await _context.Characters.FirstAsync(x=> x.CharacterId == id);
item.FirstName = updatedItem.FirstName;
item.LastName = updatedItem.LastName;
item.Strength = updatedItem.Strength;
item.Dexterity = updatedItem.Dexterity;
item.Constitution = updatedItem.Constitution;
item.Intelligence = updatedItem.Intelligence;
item.Wisdom = updatedItem.Wisdom;
item.Charisma = updatedItem.Charisma;
item.Backstory = updatedItem.Backstory;
await _context.SaveChangesAsync();
}
}
}
| 32.955224 | 110 | 0.602808 | [
"MIT"
] | DustinEwers/rpg-encounter-generator | src/character-service/RPGGen.CharacterService.Domain/Services/CharacterService.cs | 2,210 | C# |
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Edison.Core.Common;
using Edison.Core.Common.Models;
using Edison.Api.Helpers;
namespace Edison.Api.Controllers
{
/// <summary>
/// Controller to handle CRUD operation on Action Plans
/// </summary>
[ApiController]
[Route("api/ActionPlans")]
public class ActionPlansController : ControllerBase
{
private readonly ActionPlanDataManager _actionPlanDataManager;
/// <summary>
/// DI Constructor
/// </summary>
public ActionPlansController(ActionPlanDataManager actionPlanDataManager)
{
_actionPlanDataManager = actionPlanDataManager;
}
/// <summary>
/// Get action plan from an action plan Id
/// </summary>
/// <param name="actionPlanId">Action Plan Id</param>
/// <returns>ActionPlanModel</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureADAndB2C, Policy = AuthenticationRoles.Consumer)]
[HttpGet("{actionPlanId}")]
[Produces(typeof(ActionPlanModel))]
public async Task<IActionResult> GetActionPlan(Guid actionPlanId)
{
ActionPlanModel actionObj = await _actionPlanDataManager.GetActionPlan(actionPlanId);
return Ok(actionObj);
}
/// <summary>
/// Get all the actions plans
/// </summary>
/// <returns>List of Action Plans</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureADAndB2C, Policy = AuthenticationRoles.Consumer)]
[HttpGet]
[Produces(typeof(IEnumerable<ActionPlanListModel>))]
public async Task<IActionResult> GetActionPlans()
{
IEnumerable<ActionPlanListModel> actionObjs = await _actionPlanDataManager.GetActionPlans();
return Ok(actionObjs);
}
/// <summary>
/// Update an action plan
/// </summary>
/// <param name="actionPlanObj">ActionPlanUpdateModel</param>
/// <returns>ActionPlanModel</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpPut]
[Produces(typeof(ActionPlanModel))]
public async Task<IActionResult> UpdateActionPlan(ActionPlanUpdateModel actionPlanObj)
{
var result = await _actionPlanDataManager.UpdateActionPlan(actionPlanObj);
return Ok(result);
}
/// <summary>
/// Create an action plan
/// </summary>
/// <param name="actionPlanObj">ActionPlanCreationModel</param>
/// <returns>ActionPlanModel</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpPost]
[Produces(typeof(ActionPlanModel))]
public async Task<IActionResult> CreationActionPlan(ActionPlanCreationModel actionPlanObj)
{
var result = await _actionPlanDataManager.CreationActionPlan(actionPlanObj);
return Ok(result);
}
/// <summary>
/// Delete an action plan
/// </summary>
/// <param name="actionPlanId">Id of the action plan</param>
/// <returns>True if the action plan was removed</returns>
[Authorize(AuthenticationSchemes = AuthenticationBearers.AzureAD, Policy = AuthenticationRoles.Admin)]
[HttpDelete]
[Produces(typeof(HttpStatusCode))]
public async Task<IActionResult> DeleteActionPlan(Guid actionPlanId)
{
var result = await _actionPlanDataManager.DeleteActionPlan(actionPlanId);
return Ok(result);
}
}
}
| 38.21 | 119 | 0.656111 | [
"MIT"
] | Mahesh1998/ProjectEdison | Edison.Web/Edison.Api/Controllers/ActionPlansController.cs | 3,823 | C# |
using System;
using EventStore.Projections.Core.Messages;
using EventStore.Projections.Core.Messages.Persisted.Responses;
using EventStore.Projections.Core.Services.Management;
using EventStore.Projections.Core.Services.Processing;
using NUnit.Framework;
namespace EventStore.Projections.Core.Tests.Services.projection_core_service_response_writer
{
[TestFixture]
class when_handling_result_report_message : specification_with_projection_core_service_response_writer
{
private Guid _projectionId;
private string _result;
private string _partition;
private Guid _correlationId;
private CheckpointTag _position;
protected override void Given()
{
_correlationId = Guid.NewGuid();
_projectionId = Guid.NewGuid();
_result = "{\"a\":1}";
_partition = "partition";
_position = CheckpointTag.FromStreamPosition(1, "stream", 10);
}
protected override void When()
{
_sut.Handle(
new CoreProjectionStatusMessage.ResultReport(
_correlationId,
_projectionId,
_partition,
_result,
_position));
}
[Test]
public void publishes_result_report_response()
{
var command = AssertParsedSingleCommand<ResultReport>("$result");
Assert.AreEqual(_projectionId.ToString("N"), command.Id);
Assert.AreEqual(_correlationId.ToString("N"), command.CorrelationId);
Assert.AreEqual(_result, command.Result);
Assert.AreEqual(_partition, command.Partition);
Assert.AreEqual(_position, command.Position);
}
}
} | 35.48 | 106 | 0.637542 | [
"Apache-2.0",
"CC0-1.0"
] | BertschiAG/EventStore | src/EventStore.Projections.Core.Tests/Services/projection_core_service_response_writer/when_handling_result_report_message.cs | 1,776 | C# |
using System;
namespace Tema2
{
class Program
{
static void Main(string[] args) {
Studio studio = new Studio(25000m,20, 1985,"Str.Salciilor,nr.2");
Console.WriteLine("Studio price:{0} and commission:{1} Address of studio:{2} .",studio.calculate_price(),studio.calculate_commission(),studio.address);
Apartment apartment = new Apartment(65000m,45, 1990, "Str.Vamesilor, nr.5");
Console.WriteLine("Apartment price:" + apartment.calculate_price() + " and commission: " + apartment.calculate_commission());
House house = new House(70000m, 70, 2014,"Str.Lalelelor, Horpaz",3);
Console.WriteLine("House price:" + house.calculate_price() + " and commission: " + house.calculate_commission());
House house1 = new House(45000m, 50, 1975,"Str. Alexandru Ioan Cuza, Valea Adanca",1);
Console.WriteLine("House price:" + house1.calculate_price() + " and commission: " + house1.calculate_commission());
Land land = new Land(40000m,"urban",1245, 1005000);
Console.WriteLine("Land price:" + land.calculate_price() + " and commission: " + land.calculate_commission());
}
}
}
| 54.954545 | 163 | 0.645161 | [
"MIT"
] | DragosAlexa/tap2020-t01 | DragosAlexa/Tema1/Tema1/Program.cs | 1,211 | C# |
using UnityEngine;
using System.Collections;
public class SpawnPoint : MonoBehaviour
{
void OnDrawGizmos()
{
Gizmos.DrawIcon(transform.position, "flag.png");
}
}
| 16.818182 | 56 | 0.681081 | [
"BSD-2-Clause"
] | Megapop/Norad-Eduapp4syria | Ressi/ressi/Assets/Common/Mechanics/Triggers/SpawnPoint.cs | 187 | C# |
using System;
using System.Reflection;
using System.Windows.Forms;
namespace GPSoft.Tools.ReaderMe.Forms
{
partial class AboutBox : Form
{
public AboutBox()
{
InitializeComponent();
this.Text = String.Format("关于 {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format("版本 {0}", AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.llblCompanyName.Text = "作品主页: " + AssemblyCompany;
this.llblCompanyName.LinkArea = new LinkArea(5, this.llblCompanyName.Text.Length - 5);
this.textBoxDescription.Text = AssemblyDescription + "文本阅读器\r\n作者邮箱:gaoyunpeng1982@gmail.com";
}
#region 程序集属性访问器
public string AssemblyTitle
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
if (attributes.Length > 0)
{
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
if (titleAttribute.Title != "")
{
return titleAttribute.Title;
}
}
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public string AssemblyDescription
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
public string AssemblyProduct
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public string AssemblyCopyright
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public string AssemblyCompany
{
get
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
if (attributes.Length == 0)
{
return "";
}
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
private void llblCompanyName_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
VisitLink();
}
catch (Exception ex)
{
MessageBox.Show("Unable to open link that was clicked.");
}
}
private void VisitLink()
{
// Change the color of the link text by setting LinkVisited
// to true.
llblCompanyName.LinkVisited = true;
//Call the Process.Start method to open the default browser
//with a URL:
System.Diagnostics.Process.Start("http://www.cnblogs.com/gaoyunpeng/");
}
}
}
| 33.412698 | 136 | 0.508551 | [
"MIT"
] | MuteG/readerme | ReaderMe/Forms/AboutBox.cs | 4,266 | C# |
/*
Copyright 2017 Coin Foundry (coinfoundry.org)
Authors: Oliver Weichhold (oliver@weichhold.com)
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;
namespace MiningCore.Blockchain
{
public class ShareBase : IShare
{
public string PoolId { get; set; }
public string Miner { get; set; }
public string Worker { get; set; }
public string PayoutInfo { get; set; }
public string UserAgent { get; set; }
public string IpAddress { get; set; }
public double StratumDifficulty { get; set; }
public double StratumDifficultyBase { get; set; }
public double NetworkDifficulty { get; set; }
public long BlockHeight { get; set; }
public decimal BlockReward { get; set; }
public bool IsBlockCandidate { get; set; }
public string TransactionConfirmationData { get; set; }
public DateTime Created { get; set; }
}
}
| 44.767442 | 104 | 0.723636 | [
"MIT"
] | AltcoinCoop/PoolMiningEngine | src/MiningCore/Blockchain/ShareBase.cs | 1,927 | C# |
/*
* 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;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.Green.Model.V20170823
{
public class MarkAuditContentResponse : AcsResponse
{
private string requestId;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
}
}
| 26.395349 | 63 | 0.718062 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-green/Green/Model/V20170823/MarkAuditContentResponse.cs | 1,135 | C# |
using ExpressWalker.Visitors;
using FizzWare.NBuilder;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ExpressWalker.Test
{
[TestClass]
public class StressTest
{
[TestMethod]
public void TypeWalker_StressTest_ComplexCircularReference_Build()
{
//Arrange
var watch = new Stopwatch();
//Act
watch.Start();
var visitor1 = TypeWalker<Document>.Create().ForProperty<DateTime>((x, m) => DateTime.Now).Build(10, new PropertyGuard(), false);
watch.Stop();
//Assert
Assert.IsTrue(watch.ElapsedMilliseconds <= 1000);
}
[TestMethod]
public void TypeWalker_StressTest_ComplexCircularReference_Visit()
{
//Arrange
var watch = new Stopwatch();
var visitor = TypeWalker<Document>.Create().ForProperty<DateTime>((x, m) => DateTime.Now.AddYears(10)).Build(10, new PropertyGuard(), false);
var values = new HashSet<PropertyValue>();
var document = GetComplexSample();
//Act
watch.Start();
visitor.Visit(document, depth:10, guard:new InstanceGuard(), values:values);
watch.Stop();
//Assert
Assert.IsTrue(values.Count == 90 && values.All(x => ((DateTime)x.NewValue).Year == DateTime.Now.Year + 10));
}
[TestMethod]
public void TypeWalker_StressTest_AllowedHierarchy_Visit()
{
//Arrange
var visitor = TypeWalker<AllowedHierarchy>.Create().ForProperty<DateTime>((x, m) => DateTime.Now.AddYears(10)).Build(10, new PropertyGuard());
var hierarchy = Builder<AllowedHierarchy>.CreateListOfSize(10).BuildHierarchy(new HierarchySpec<AllowedHierarchy>
{
Depth = 5,
MaximumChildren = 1,
MinimumChildren = 1,
NumberOfRoots = 1,
AddMethod = (x1, x2) => x1.Child = x2
}).First();
var values = new HashSet<PropertyValue>();
//Act
visitor.Visit(hierarchy, depth: 10, guard: new InstanceGuard(), values: values);
//Assert
Assert.AreEqual(6, values.Count);
}
[TestMethod]
public void TypeWalker_StressTest_SuppressedHierarchy_Visit()
{
//Arrange
var visitor = TypeWalker<SuppressedHierarchy>.Create().ForProperty<DateTime>((x, m) => DateTime.Now.AddYears(10)).Build(10, new PropertyGuard());
var hierarchy = Builder<SuppressedHierarchy>.CreateListOfSize(10).BuildHierarchy(new HierarchySpec<SuppressedHierarchy>
{
Depth = 5,
MaximumChildren = 1,
MinimumChildren = 1,
NumberOfRoots = 1,
AddMethod = (x1, x2) => x1.Child = x2
}).First();
var values = new HashSet<PropertyValue>();
//Act
visitor.Visit(hierarchy, depth: 10, guard: new InstanceGuard(), values: values);
//Assert
Assert.AreEqual(3, values.Count);
}
private Document GetComplexSample()
{
var document = Builder<Document>.CreateNew()
.With(x => x.DocumentDefaultUser1, Builder<User>.CreateNew()
.With(x => x.User_UserToRole, Builder<UserToRole>.CreateNew()
.With(y => y.UserToRole_User, Builder<User>.CreateNew().Build())
.With(x => x.UserToRole_Role, Builder<Role>.CreateNew().Build())
.Build())
.Build())
.With(x => x.DocumentDefaultRole1, Builder<Role>.CreateNew()
.With(x => x.Role_UserToRoleList, Builder<UserToRole>.CreateListOfSize(2).All()
.With(x => x.UserToRole_User, Builder<User>.CreateNew()
.Build())
.Build())
.With(x => x.Role_Profile, Builder<Profile>.CreateNew()
.With(x => x.Profile_OperationsList, Builder<OperationToProfile>.CreateListOfSize(5).All()
.With(x => x.OperationToProfile_Operation, Builder<Operation>.CreateNew().Build())
.Build())
.Build())
.Build())
.With(x => x.DocumentDefaultUnit1, Builder<Unit>.CreateNew()
.With(x => x.Unit_Roles, Builder<Role>.CreateListOfSize(2).All()
.With(x => x.Role_UserToRoleList, Builder<UserToRole>.CreateListOfSize(1).All()
.With(x => x.UserToRole_User, Builder<User>.CreateNew()
.Build())
.Build())
.Build())
.Build())
.With(x => x.DocumentDefaultUnit2, Builder<Unit>.CreateListOfSize(10).BuildHierarchy(new HierarchySpec<Unit>
{
Depth = 5,
MaximumChildren = 1,
MinimumChildren = 1,
NumberOfRoots = 1,
AddMethod = (x1, x2) => x1.Unit_ParentUnit = x2
}).First())
.Build();
return document;
}
}
public class Document
{
public User DocumentDefaultUser1 { get; set; }
public Role DocumentDefaultRole1 { get; set; }
public Unit DocumentDefaultUnit1 { get; set; }
public User DocumentDefaultUser2 { get; set; }
public Role DocumentDefaultRole2 { get; set; }
public Unit DocumentDefaultUnit2 { get; set; }
public DateTime TestDocumentDateTime1 { get; set; }
public DateTime TestDocumentDateTime2 { get; set; }
public DateTime TestDocumentDateTime3 { get; set; }
public DateTime TestDocumentDateTime4 { get; set; }
public DateTime TestDocumentDateTime5 { get; set; }
public IList<CollectionItem> Items { get; set; }
}
public class CollectionItem
{
}
public class User
{
public string TestUserString1 { get; set; }
public string TestUserString2 { get; set; }
public string TestUserString3 { get; set; }
public string TestUserString4 { get; set; }
public string TestUserString5 { get; set; }
public DateTime TestUserDateTime1 { get; set; }
public DateTime TestUserDateTime2 { get; set; }
public DateTime TestUserDateTime3 { get; set; }
public DateTime TestUserDateTime4 { get; set; }
public DateTime TestUserDateTime5 { get; set; }
public int TestUserInt1 { get; set; }
public int TestUserInt2 { get; set; }
public int TestUserInt3 { get; set; }
public int TestUserInt4 { get; set; }
public int TestUserInt5 { get; set; }
public UserToRole User_UserToRole { get; set; }
}
public class Role
{
public string TestRoleString1 { get; set; }
public string TestRoleString2 { get; set; }
public string TestRoleString3 { get; set; }
public string TestRoleString4 { get; set; }
public string TestRoleString5 { get; set; }
public DateTime TestRoleDateTime1 { get; set; }
public DateTime TestRoleDateTime2 { get; set; }
public DateTime TestRoleDateTime3 { get; set; }
public DateTime TestRoleDateTime4 { get; set; }
public DateTime TestRoleDateTime5 { get; set; }
public int TestRoleInt1 { get; set; }
public int TestRoleInt2 { get; set; }
public int TestRoleInt3 { get; set; }
public int TestRoleInt4 { get; set; }
public int TestRoleInt5 { get; set; }
public IList<UserToRole> Role_UserToRoleList { get; set; }
public Profile Role_Profile { get; set; }
}
public class Unit
{
public string TestUnitString1 { get; set; }
public string TestUnitString2 { get; set; }
public string TestUnitString3 { get; set; }
public string TestUnitString4 { get; set; }
public string TestUnitString5 { get; set; }
public DateTime TestUnitDateTime1 { get; set; }
public DateTime TestUnitDateTime2 { get; set; }
public DateTime TestUnitDateTime3 { get; set; }
public DateTime TestUnitDateTime4 { get; set; }
public DateTime TestUnitDateTime5 { get; set; }
public int TestUnitInt1 { get; set; }
public int TestUnitInt2 { get; set; }
public int TestUnitInt3 { get; set; }
public int TestUnitInt4 { get; set; }
public int TestUnitInt5 { get; set; }
[VisitorHierarchy]
public Unit Unit_ParentUnit { get; set; }
public IList<Role> Unit_Roles { get; set; }
}
public class Profile
{
public string TestProfileString1 { get; set; }
public string TestProfileString2 { get; set; }
public string TestProfileString3 { get; set; }
public string TestProfileString4 { get; set; }
public string TestProfileString5 { get; set; }
public DateTime TestProfileDateTime1 { get; set; }
public DateTime TestProfileDateTime2 { get; set; }
public DateTime TestProfileDateTime3 { get; set; }
public DateTime TestProfileDateTime4 { get; set; }
public DateTime TestProfileDateTime5 { get; set; }
public int TestProfileInt1 { get; set; }
public int TestProfileInt2 { get; set; }
public int TestProfileInt3 { get; set; }
public int TestProfileInt4 { get; set; }
public int TestProfileInt5 { get; set; }
public IList<OperationToProfile> Profile_OperationsList { get; set; }
}
public class UserToRole
{
public User UserToRole_User { get; set; }
public Role UserToRole_Role { get; set; }
}
public class RoleToProfile
{
public Role UserToRole_Role { get; set; }
public Profile UserToRole_Profile { get; set; }
}
public class Operation
{
public string TestOperationString1 { get; set; }
public string TestOperationString2 { get; set; }
public string TestOperationString3 { get; set; }
public string TestOperationString4 { get; set; }
public string TestOperationString5 { get; set; }
public DateTime TestOperationDateTime1 { get; set; }
public DateTime TestOperationDateTime2 { get; set; }
public DateTime TestOperationDateTime3 { get; set; }
public DateTime TestOperationDateTime4 { get; set; }
public DateTime TestOperationDateTime5 { get; set; }
public int TestOperationInt1 { get; set; }
public int TestOperationInt2 { get; set; }
public int TestOperationInt3 { get; set; }
public int TestOperationInt4 { get; set; }
public int TestOperationInt5 { get; set; }
}
public class OperationToProfile
{
public Operation OperationToProfile_Operation { get; set; }
public Profile OperationToProfile_Profile { get; set; }
}
public class AllowedHierarchy
{
public DateTime DateTime1 { get; set; }
[VisitorHierarchy]
public AllowedHierarchy Child { get; set; }
}
public class SuppressedHierarchy
{
public DateTime DateTime1 { get; set; }
//[VisitorHierarchy]
public SuppressedHierarchy Child { get; set; }
}
}
| 39.371951 | 190 | 0.527257 | [
"MIT"
] | kopalite/ExpressWalker | ExpressWalker.Test/StressTest.cs | 12,916 | C# |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Datastream.V1Alpha1.Snippets
{
// [START datastream_v1alpha1_generated_Datastream_ListConnectionProfiles_sync_flattened]
using Google.Api.Gax;
using Google.Cloud.Datastream.V1Alpha1;
using System;
public sealed partial class GeneratedDatastreamClientSnippets
{
/// <summary>Snippet for ListConnectionProfiles</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListConnectionProfiles()
{
// Create client
DatastreamClient datastreamClient = DatastreamClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListConnectionProfilesResponse, ConnectionProfile> response = datastreamClient.ListConnectionProfiles(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (ConnectionProfile item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListConnectionProfilesResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ConnectionProfile item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ConnectionProfile> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ConnectionProfile item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
// [END datastream_v1alpha1_generated_Datastream_ListConnectionProfiles_sync_flattened]
}
| 42.786667 | 138 | 0.645061 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Datastream.V1Alpha1/Google.Cloud.Datastream.V1Alpha1.GeneratedSnippets/DatastreamClient.ListConnectionProfilesSnippet.g.cs | 3,209 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace TweetSchedulerClient
{
//Code take from: http://stackoverflow.com/questions/442704/how-do-you-handle-multiple-submit-buttons-in-asp-net-mvc-framework
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
} | 35.590909 | 130 | 0.731801 | [
"MIT"
] | aj100/TweetScheduler | TweetSchedulerClient/Attributes/HttpParamActionAttribute.cs | 785 | C# |
//MIT, 2019-present, WinterDev
using System;
using System.Collections.Generic;
using Typography.OpenFont;
namespace PixelFarm.CpuBlit.BitmapAtlas
{
class GlyphBitmap
{
public MemBitmap Bitmap { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public int ImageStartX { get; set; } //in the case Bitmap is an Atlas,
public int ImageStartY { get; set; } //in the case Bitmap is an Atlas,
}
class GlyphBitmapList : IDisposable
{
Dictionary<ushort, GlyphBitmap> _dic = new Dictionary<ushort, GlyphBitmap>();
public void RegisterBitmap(ushort glyphIndex, GlyphBitmap bmp)
{
_dic.Add(glyphIndex, bmp);
}
public bool TryGetBitmap(ushort glyphIndex, out GlyphBitmap bmp)
{
return _dic.TryGetValue(glyphIndex, out bmp);
}
public void Dispose()
{
foreach (GlyphBitmap glyphBmp in _dic.Values)
{
if (glyphBmp.Bitmap != null)
{
glyphBmp.Bitmap.Dispose();
glyphBmp.Bitmap = null;
}
}
_dic.Clear();
}
}
class GlyphBitmapStore
{
Typeface _currentTypeface;
GlyphBitmapList _bitmapList;
Dictionary<Typeface, GlyphBitmapList> _cachedBmpList = new Dictionary<Typeface, GlyphBitmapList>();
public void SetCurrentTypeface(Typeface typeface)
{
_currentTypeface = typeface;
if (_cachedBmpList.TryGetValue(typeface, out _bitmapList))
{
return;
}
//TODO: you can scale down to proper img size
//or create a single texture atlas.
//if not create a new one
_bitmapList = new GlyphBitmapList();
_cachedBmpList.Add(typeface, _bitmapList);
int glyphCount = typeface.GlyphCount;
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
for (ushort i = 0; i < glyphCount; ++i)
{
ms.SetLength(0);
Glyph glyph = typeface.GetGlyph(i);
typeface.ReadBitmapContent(glyph, ms);
GlyphBitmap glyphBitmap = new GlyphBitmap();
glyphBitmap.Width = glyph.MaxX - glyph.MinX;
glyphBitmap.Height = glyph.MaxY - glyph.MinY;
//glyphBitmap.Bitmap = ...
glyphBitmap.Bitmap = MemBitmap.LoadBitmap(ms);
//MemBitmapExtensions.SaveImage(glyphBitmap.Bitmap, "testGlyphBmp_" + i + ".png");
_bitmapList.RegisterBitmap(glyph.GlyphIndex, glyphBitmap);
}
}
}
public GlyphBitmap GetGlyphBitmap(ushort glyphIndex)
{
_bitmapList.TryGetBitmap(glyphIndex, out GlyphBitmap found);
return found;
}
}
} | 33.195652 | 107 | 0.545514 | [
"MIT"
] | Ferdowsur/Typography | PixelFarm.Typography/2_CpuBlit_BitmapAtlas/GlyphBitmapStore.cs | 3,056 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace RiotApi.Net.RestClient.Dto.League
{
[DataContract]
public class LeagueDto : RiotDto
{
/// <summary>
/// The requested league entries.
/// </summary>
[DataMember(Name = "entries")]
public IEnumerable<LeagueEntryDto> Entries { get; set; }
/// <summary>
/// This name is an internal place-holder name only. Display and localization of names in the game client are handled client-side.
/// </summary>
[DataMember(Name = "name")]
public string Name { get; set; }
/// <summary>
/// Specifies the relevant participant that is a member of this league (i.e., a requested summoner ID, a requested team ID, or the ID of a team to which one of the requested summoners belongs). Only present when full league is requested so that participant's entry can be identified. Not present when individual entry is requested.
/// </summary>
[DataMember(Name = "participantId")]
public string ParticipantId { get; set; }
/// <summary>
/// The league's queue type. (Legal values: RANKED_SOLO_5x5, RANKED_TEAM_3x3, RANKED_TEAM_5x5)
/// </summary>
[DataMember(Name = "queue")]
public Helpers.Enums.GameQueueType Queue { get; set; }
/// <summary>
/// The league's tier. (Legal values: CHALLENGER, MASTER, DIAMOND, PLATINUM, GOLD, SILVER, BRONZE)
/// </summary>
[DataMember(Name = "tier")]
public Helpers.Enums.Tier Tier { get; set; }
/// <summary>
/// This object contains league participant information representing a summoner or team.
/// </summary>
[DataContract]
public class LeagueEntryDto
{
/// <summary>
/// The league division of the participant.
/// </summary>
[DataMember(Name = "division")]
public string Division { get; set; }
/// <summary>
/// Specifies if the participant is fresh blood.
/// </summary>
[DataMember(Name = "isFreshBlood")]
public bool IsFreshBlood { get; set; }
/// <summary>
/// Specifies if the participant is on a hot streak.
/// </summary>
[DataMember(Name = "isHotStreak")]
public bool IsHotStreak { get; set; }
/// <summary>
/// Specifies if the participant is on a hot streak.
/// </summary>
[DataMember(Name = "isInactive")]
public bool IsInactive { get; set; }
/// <summary>
/// Specifies if the participant is a veteran.
/// </summary>
[DataMember(Name = "isVeteran")]
public bool IsVeteran { get; set; }
/// <summary>
/// The league points of the participant.
/// </summary>
[DataMember(Name = "leaguePoints")]
public int LeaguePoints { get; set; }
/// <summary>
/// The number of losses for the participant.
/// </summary>
[DataMember(Name = "losses")]
public int Losses { get; set; }
/// <summary>
/// Mini series data for the participant. Only present if the participant is currently in a mini series.
/// </summary>
[DataMember(Name = "miniSeries")]
public MiniSeriesDto MiniSeries { get; set; }
/// <summary>
/// The ID of the participant (i.e., summoner or team) represented by this entry.
/// </summary>
[DataMember(Name = "playerOrTeamId")]
public string PlayerOrTeamId { get; set; }
/// <summary>
/// The name of the the participant (i.e., summoner or team) represented by this entry.
/// </summary>
[DataMember(Name = "playerOrTeamName")]
public string PlayerOrTeamName { get; set; }
/// <summary>
/// The number of wins for the participant.
/// </summary>
[DataMember(Name = "wins")]
public int Wins { get; set; }
/// <summary>
/// This object contains mini series information.
/// </summary>
[DataContract]
public class MiniSeriesDto
{
/// <summary>
/// Number of current losses in the mini series.
/// </summary>
[DataMember(Name = "losses")]
public int Losses { get; set; }
/// <summary>
/// String showing the current, sequential mini series progress where 'W' represents a win, 'L' represents a loss, and 'N' represents a game that hasn't been played yet.
/// </summary>
[DataMember(Name = "progress")]
public string Progress { get; set; }
/// <summary>
/// Number of wins required for promotion.
/// </summary>
[DataMember(Name = "target")]
public int Target { get; set; }
/// <summary>
/// Number of current wins in the mini series.
/// </summary>
[DataMember(Name = "wins")]
public int Wins { get; set; }
}
}
}
}
| 38.076389 | 339 | 0.526901 | [
"MIT"
] | Nayls/RiotApi.NET | RiotApi.Net.RestClient/Dto/League/LeagueDto.cs | 5,485 | C# |
using System;
using System.Collections.Generic;
using Content.Shared.Chemistry;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization;
using Robust.Shared.ViewVariables;
namespace Content.Shared.GameObjects.Components.Chemistry
{
public class SolutionComponent : Component
{
#pragma warning disable 649
[Dependency] private readonly IPrototypeManager _prototypeManager;
#pragma warning restore 649
[ViewVariables]
protected Solution _containedSolution = new Solution();
protected int _maxVolume;
private SolutionCaps _capabilities;
/// <summary>
/// Triggered when the solution contents change.
/// </summary>
public event Action SolutionChanged;
/// <summary>
/// The maximum volume of the container.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public int MaxVolume
{
get => _maxVolume;
set => _maxVolume = value; // Note that the contents won't spill out if the capacity is reduced.
}
/// <summary>
/// The total volume of all the of the reagents in the container.
/// </summary>
[ViewVariables]
public int CurrentVolume => _containedSolution.TotalVolume;
/// <summary>
/// The volume without reagents remaining in the container.
/// </summary>
[ViewVariables]
public int EmptyVolume => MaxVolume - CurrentVolume;
/// <summary>
/// The current blended color of all the reagents in the container.
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public Color SubstanceColor { get; private set; }
/// <summary>
/// The current capabilities of this container (is the top open to pour? can I inject it into another object?).
/// </summary>
[ViewVariables(VVAccess.ReadWrite)]
public SolutionCaps Capabilities
{
get => _capabilities;
set => _capabilities = value;
}
public IReadOnlyList<Solution.ReagentQuantity> ReagentList => _containedSolution.Contents;
/// <summary>
/// Shortcut for Capabilities PourIn flag to avoid binary operators.
/// </summary>
public bool CanPourIn => (Capabilities & SolutionCaps.PourIn) != 0;
/// <summary>
/// Shortcut for Capabilities PourOut flag to avoid binary operators.
/// </summary>
public bool CanPourOut => (Capabilities & SolutionCaps.PourOut) != 0;
/// <inheritdoc />
public override string Name => "Solution";
/// <inheritdoc />
public sealed override uint? NetID => ContentNetIDs.SOLUTION;
/// <inheritdoc />
public override void ExposeData(ObjectSerializer serializer)
{
base.ExposeData(serializer);
serializer.DataField(ref _maxVolume, "maxVol", 0);
serializer.DataField(ref _containedSolution, "contents", _containedSolution);
serializer.DataField(ref _capabilities, "caps", SolutionCaps.None);
}
/// <inheritdoc />
protected override void Startup()
{
base.Startup();
RecalculateColor();
}
/// <inheritdoc />
protected override void Shutdown()
{
base.Shutdown();
_containedSolution.RemoveAllSolution();
_containedSolution = new Solution();
}
public void RemoveAllSolution()
{
_containedSolution.RemoveAllSolution();
OnSolutionChanged();
}
public bool TryRemoveReagent(string reagentId, int quantity)
{
if (!ContainsReagent(reagentId, out var currentQuantity)) return false;
_containedSolution.RemoveReagent(reagentId, quantity);
OnSolutionChanged();
return true;
}
/// <summary>
/// Attempt to remove the specified quantity from this solution
/// </summary>
/// <param name="quantity">Quantity of this solution to remove</param>
/// <param name="removedSolution">Out arg. The removed solution. Useful for adding removed solution
/// into other solutions. For example, when pouring from one container to another.</param>
/// <returns>Whether or not the solution was successfully removed</returns>
public bool TryRemoveSolution(int quantity, out Solution removedSolution)
{
removedSolution = new Solution();
if (CurrentVolume == 0)
return false;
_containedSolution.RemoveSolution(quantity, out removedSolution);
OnSolutionChanged();
return true;
}
public Solution SplitSolution(int quantity)
{
var solutionSplit = _containedSolution.SplitSolution(quantity);
OnSolutionChanged();
return solutionSplit;
}
protected void RecalculateColor()
{
if(_containedSolution.TotalVolume == 0)
SubstanceColor = Color.White;
Color mixColor = default;
float runningTotalQuantity = 0;
foreach (var reagent in _containedSolution)
{
runningTotalQuantity += reagent.Quantity;
if(!_prototypeManager.TryIndex(reagent.ReagentId, out ReagentPrototype proto))
continue;
if (mixColor == default)
mixColor = proto.SubstanceColor;
mixColor = BlendRGB(mixColor, proto.SubstanceColor, reagent.Quantity / runningTotalQuantity);
}
}
private Color BlendRGB(Color rgb1, Color rgb2, float amount)
{
var r = (float)Math.Round(rgb1.R + (rgb2.R - rgb1.R) * amount, 1);
var g = (float)Math.Round(rgb1.G + (rgb2.G - rgb1.G) * amount, 1);
var b = (float)Math.Round(rgb1.B + (rgb2.B - rgb1.B) * amount, 1);
var alpha = (float)Math.Round(rgb1.A + (rgb2.A - rgb1.A) * amount, 1);
return new Color(r, g, b, alpha);
}
/// <inheritdoc />
public override ComponentState GetComponentState()
{
return new SolutionComponentState();
}
/// <inheritdoc />
public override void HandleComponentState(ComponentState curState, ComponentState nextState)
{
base.HandleComponentState(curState, nextState);
if(curState == null)
return;
var compState = (SolutionComponentState)curState;
//TODO: Make me work!
}
[Serializable, NetSerializable]
public class SolutionComponentState : ComponentState
{
public SolutionComponentState() : base(ContentNetIDs.SOLUTION) { }
}
/// <summary>
/// Check if the solution contains the specified reagent.
/// </summary>
/// <param name="reagentId">The reagent to check for.</param>
/// <param name="quantity">Output the quantity of the reagent if it is contained, 0 if it isn't.</param>
/// <returns>Return true if the solution contains the reagent.</returns>
public bool ContainsReagent(string reagentId, out int quantity)
{
foreach (var reagent in _containedSolution.Contents)
{
if (reagent.ReagentId == reagentId)
{
quantity = reagent.Quantity;
return true;
}
}
quantity = 0;
return false;
}
protected virtual void OnSolutionChanged()
{
SolutionChanged?.Invoke();
}
}
}
| 33.884615 | 123 | 0.587464 | [
"MIT"
] | Moneyl/space-station-14 | Content.Shared/GameObjects/Components/Chemistry/SolutionComponent.cs | 7,931 | C# |
using ITE.Catalog.API.Configuration;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ITE.Catalog.API
{
public class StartupTests
{
public StartupTests(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddApiConfiguration(Configuration);
services.AddDependencyConfiguration(Configuration);
services.AddSwaggerConfiguration();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseApiConfiguration(env);
app.UseSwaggerConfiguration();
}
}
}
| 25.514286 | 79 | 0.683091 | [
"MIT"
] | AdsHan/core-integration-testing | src/ITE.Catalog.API/StartupTests.cs | 893 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.Management.Compute.Models
{
public partial class UpgradeOperationHistoricalStatusInfo
{
internal static UpgradeOperationHistoricalStatusInfo DeserializeUpgradeOperationHistoricalStatusInfo(JsonElement element)
{
UpgradeOperationHistoricalStatusInfoProperties properties = default;
string type = default;
string location = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("properties"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
properties = UpgradeOperationHistoricalStatusInfoProperties.DeserializeUpgradeOperationHistoricalStatusInfoProperties(property.Value);
continue;
}
if (property.NameEquals("type"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
type = property.Value.GetString();
continue;
}
if (property.NameEquals("location"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
location = property.Value.GetString();
continue;
}
}
return new UpgradeOperationHistoricalStatusInfo(properties, type, location);
}
}
}
| 34.462963 | 154 | 0.529285 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/testcommon/Azure.Management.Compute.2019_12/src/Generated/Models/UpgradeOperationHistoricalStatusInfo.Serialization.cs | 1,861 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
namespace PeefyLeetCode.RangeAdditionII
{
public class Solution
{
public int MaxCount(int m, int n, int[,] ops)
{
int minA = m, minB = n;
for (int i = 0; i < ops.GetLength(0); i++)
{
if (minA > ops[i, 0])
minA = ops[i, 0];
if (minB > ops[i, 1])
minB = ops[i, 1];
}
return minA * minB;
}
}
}
| 20.384615 | 54 | 0.437736 | [
"Apache-2.0"
] | Peefy/PeefyLeetCode | src/CSharp/501-600/598.RangeAdditionII.cs | 530 | C# |
namespace OpenQA.Selenium.DevTools.Console
{
using Newtonsoft.Json;
/// <summary>
/// Enables console domain, sends the messages collected so far to the client by means of the
/// `messageAdded` notification.
/// </summary>
public sealed class EnableCommandSettings : ICommand
{
private const string DevToolsRemoteInterface_CommandName = "Console.enable";
[JsonIgnore]
public string CommandName
{
get { return DevToolsRemoteInterface_CommandName; }
}
}
public sealed class EnableCommandResponse : ICommandResponse<EnableCommandSettings>
{
}
} | 27.083333 | 97 | 0.664615 | [
"Apache-2.0"
] | 418sec/selenium | dotnet/src/webdriver/DevTools/AutoGenerated/Console/EnableCommand.cs | 650 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace QuillAnim {
public abstract class SingletonObject<T> : MonoBehaviour where T : MonoBehaviour {
private static object threadLock = new object();
private static T _instance;
protected static void CreateIfNotInstantiated() {
if(!_instance) {
var singleton_root = GameObject.Find("SingletonContainer");
if(!singleton_root) {
singleton_root = new GameObject("SingletonContainer");
}
var obj = new GameObject(typeof(T).ToString());
obj.transform.parent = singleton_root.transform;
_instance = obj.AddComponent<T>();
}
}
public static void EnsureExists() {
lock(threadLock) {
CreateIfNotInstantiated();
}
}
public static T instance {
get {
lock(threadLock) {
CreateIfNotInstantiated();
return _instance;
}
}
}
}
}
| 23.051282 | 83 | 0.686318 | [
"MIT"
] | kanzwataru/UnityQuillFBXAnim | Scripts/Singleton.cs | 901 | C# |
using System.Reflection;
namespace ATCommon.Aspect.Contracts.Interception
{
public class BeforeMethodArgs : InterceptionArgs
{
public BeforeMethodArgs(MethodInfo methodInfo, object[] arguments)
: base(methodInfo, arguments)
{
}
public BeforeMethodArgs(InterceptionArgs interceptionArgs) : base(interceptionArgs) { }
}
}
| 24.6875 | 96 | 0.663291 | [
"MIT"
] | ahmettugur/dotnet-core-webapi | src/ATCommon.Aspect.Contracts/Interception/BeforeMethodArgs.cs | 397 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SageMaker.Model
{
/// <summary>
/// Describes the S3 data source.
/// </summary>
public partial class S3DataSource
{
private List<string> _attributeNames = new List<string>();
private S3DataDistribution _s3DataDistributionType;
private S3DataType _s3DataType;
private string _s3Uri;
/// <summary>
/// Gets and sets the property AttributeNames.
/// <para>
/// A list of one or more attribute names to use that are found in a specified augmented
/// manifest file.
/// </para>
/// </summary>
public List<string> AttributeNames
{
get { return this._attributeNames; }
set { this._attributeNames = value; }
}
// Check to see if AttributeNames property is set
internal bool IsSetAttributeNames()
{
return this._attributeNames != null && this._attributeNames.Count > 0;
}
/// <summary>
/// Gets and sets the property S3DataDistributionType.
/// <para>
/// If you want Amazon SageMaker to replicate the entire dataset on each ML compute instance
/// that is launched for model training, specify <code>FullyReplicated</code>.
/// </para>
///
/// <para>
/// If you want Amazon SageMaker to replicate a subset of data on each ML compute instance
/// that is launched for model training, specify <code>ShardedByS3Key</code>. If there
/// are <i>n</i> ML compute instances launched for a training job, each instance gets
/// approximately 1/<i>n</i> of the number of S3 objects. In this case, model training
/// on each machine uses only the subset of training data.
/// </para>
///
/// <para>
/// Don't choose more ML compute instances for training than available S3 objects. If
/// you do, some nodes won't get any data and you will pay for nodes that aren't getting
/// any training data. This applies in both File and Pipemodes. Keep this in mind when
/// developing algorithms.
/// </para>
///
/// <para>
/// In distributed training, where you use multiple ML compute EC2 instances, you might
/// choose <code>ShardedByS3Key</code>. If the algorithm requires copying training data
/// to the ML storage volume (when <code>TrainingInputMode</code> is set to <code>File</code>),
/// this copies 1/<i>n</i> of the number of objects.
/// </para>
/// </summary>
public S3DataDistribution S3DataDistributionType
{
get { return this._s3DataDistributionType; }
set { this._s3DataDistributionType = value; }
}
// Check to see if S3DataDistributionType property is set
internal bool IsSetS3DataDistributionType()
{
return this._s3DataDistributionType != null;
}
/// <summary>
/// Gets and sets the property S3DataType.
/// <para>
/// If you choose <code>S3Prefix</code>, <code>S3Uri</code> identifies a key name prefix.
/// Amazon SageMaker uses all objects that match the specified key name prefix for model
/// training.
/// </para>
///
/// <para>
/// If you choose <code>ManifestFile</code>, <code>S3Uri</code> identifies an object that
/// is a manifest file containing a list of object keys that you want Amazon SageMaker
/// to use for model training.
/// </para>
///
/// <para>
/// If you choose <code>AugmentedManifestFile</code>, S3Uri identifies an object that
/// is an augmented manifest file in JSON lines format. This file contains the data you
/// want to use for model training. <code>AugmentedManifestFile</code> can only be used
/// if the Channel's input mode is <code>Pipe</code>.
/// </para>
/// </summary>
public S3DataType S3DataType
{
get { return this._s3DataType; }
set { this._s3DataType = value; }
}
// Check to see if S3DataType property is set
internal bool IsSetS3DataType()
{
return this._s3DataType != null;
}
/// <summary>
/// Gets and sets the property S3Uri.
/// <para>
/// Depending on the value specified for the <code>S3DataType</code>, identifies either
/// a key name prefix or a manifest. For example:
/// </para>
/// <ul> <li>
/// <para>
/// A key name prefix might look like this: <code>s3://bucketname/exampleprefix</code>.
///
/// </para>
/// </li> <li>
/// <para>
/// A manifest might look like this: <code>s3://bucketname/example.manifest</code>
/// </para>
///
/// <para>
/// The manifest is an S3 object which is a JSON file with the following format:
/// </para>
///
/// <para>
/// <code>[</code>
/// </para>
///
/// <para>
/// <code> {"prefix": "s3://customer_bucket/some/prefix/"},</code>
/// </para>
///
/// <para>
/// <code> "relative/path/to/custdata-1",</code>
/// </para>
///
/// <para>
/// <code> "relative/path/custdata-2",</code>
/// </para>
///
/// <para>
/// <code> ...</code>
/// </para>
///
/// <para>
/// <code> ]</code>
/// </para>
///
/// <para>
/// The preceding JSON matches the following <code>s3Uris</code>:
/// </para>
///
/// <para>
/// <code>s3://customer_bucket/some/prefix/relative/path/to/custdata-1</code>
/// </para>
///
/// <para>
/// <code>s3://customer_bucket/some/prefix/relative/path/custdata-1</code>
/// </para>
///
/// <para>
/// <code>...</code>
/// </para>
///
/// <para>
/// The complete set of <code>s3uris</code> in this manifest is the input data for the
/// channel for this datasource. The object that each <code>s3uris</code> points to must
/// be readable by the IAM role that Amazon SageMaker uses to perform tasks on your behalf.
///
/// </para>
/// </li> </ul>
/// </summary>
public string S3Uri
{
get { return this._s3Uri; }
set { this._s3Uri = value; }
}
// Check to see if S3Uri property is set
internal bool IsSetS3Uri()
{
return this._s3Uri != null;
}
}
} | 36.196262 | 107 | 0.557191 | [
"Apache-2.0"
] | DalavanCloud/aws-sdk-net | sdk/src/Services/SageMaker/Generated/Model/S3DataSource.cs | 7,746 | C# |
using FluentValidation;
using Microsoft.Extensions.Localization;
namespace Application.Users.Queries.FindUser
{
public class FindUserQueryValidator : AbstractValidator<FindUserQuery>
{
public FindUserQueryValidator(IStringLocalizer<UsersResource> userResource)
{
var errorInfo = userResource["UserNameNull"];
RuleFor(v => v.UserName)
.Must(u => !string.IsNullOrWhiteSpace(u))
.WithMessage(errorInfo);
}
}
} | 29.470588 | 83 | 0.662675 | [
"MIT"
] | Nachyn/blog-api | src/Application/Users/Queries/FindUser/FindUserQueryValidator.cs | 503 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Muebles_JJ.Infrastructure.Data;
using Muebles_JJ.Infrastructure;
namespace Muebles_JJ.Web.Controllers
{
public class PedidoController : Controller
{
private readonly Muebles_JJDbContext _context;
public PedidoController(Muebles_JJDbContext context)
{
_context = context;
}
//GET: Pedido
public async Task<IActionResult> Index()
{
var listado = await _context.Pedido.ToListAsync();
return View(listado);
}
// GET: Pedido/Details/
public async Task<IActionResult> Details(int? IdPedido)
{
if (IdPedido == null)
{
return NotFound();
}
Pedido model = await _context.Pedido
.FirstOrDefaultAsync(m => m.IdPedido == IdPedido);
if (model == null)
{
return NotFound();
}
return View(model);
}
//GET: Pedido/Create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Pedido Pedido)
{
if (ModelState.IsValid)
{
_context.Add(Pedido);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(Pedido);
}
[HttpGet]
// GET: Pedido/Edit
public async Task<IActionResult> Edit(int? IdPedido)
{
if (IdPedido == null)
{
return NotFound();
}
Pedido model = await _context.Pedido.FindAsync(IdPedido);
if (model == null)
{
return NotFound();
}
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int IdPedido, Pedido Pedido)
{
if (IdPedido != Pedido.IdPedido)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(Pedido);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PedidoExists(Pedido.IdPedido))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(Pedido);
}
// GET: Pedido/Delete/5
public async Task<IActionResult> Delete(int? IdPedido)
{
if (IdPedido == null)
{
return NotFound();
}
Pedido model = await _context.Pedido
.FirstOrDefaultAsync(m => m.IdPedido == IdPedido);
if (model == null)
{
return NotFound();
}
return View(model);
}
// POST: Pedido/Delete
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int IdPedido)
{
Pedido model = await _context.Pedido.FindAsync(IdPedido);
_context.Pedido.Remove(model);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool PedidoExists(int IdPedido)
{
return _context.Pedido.Any(c => c.IdPedido == IdPedido);
}
}
}
| 26.357616 | 74 | 0.488693 | [
"MIT"
] | Juancholaya/Muebles_JJ | Muebles_JJ/src/Muebles_JJ.Web/Controllers/PedidoController.cs | 3,982 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class PlayerShip : MonoBehaviour {
[SerializeField] AudioClip deathSound = null;
[SerializeField] float shipSpeed = 1f;
[SerializeField] float padding = 1f;
[SerializeField] ParticleSystem deathFX = null;
[SerializeField] GameObject audioPlayer = null;
[Range(0, 40)] [SerializeField] float rollMaxAngel = 20f;
private PlayerStatController playerStatController;
private GameSceneManager sceneManager;
private Animator animator;
private Rect bounds;
void Start() {
sceneManager = FindObjectOfType<GameSceneManager>();
playerStatController = GetComponent<PlayerStatController>();
playerStatController.OnShieldValueChange += OnSheildValueChangeCheckForDeath;
animator = GetComponent<Animator>();
Camera gameCamera = Camera.main;
bounds = Rect.MinMaxRect(
gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x + padding,
gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y + padding,
gameCamera.ViewportToWorldPoint(new Vector3(1, 0, 0)).x - padding,
gameCamera.ViewportToWorldPoint(new Vector3(0, 1, 0)).y - padding);
}
void Update() {
MoveShip();
}
private void MoveShip() {
float inputX = CrossPlatformInputManager.GetAxis("Horizontal");
float inputY = CrossPlatformInputManager.GetAxis("Vertical");
float deltaX = inputX * Time.deltaTime * shipSpeed;
float deltaY = inputY * Time.deltaTime * shipSpeed;
float newPosX = Mathf.Clamp(transform.position.x + deltaX, bounds.xMin, bounds.xMax);
float newPosY = Mathf.Clamp(transform.position.y + deltaY, bounds.yMin, bounds.yMax);
transform.position = new Vector3(newPosX, newPosY);
float roll = rollMaxAngel * inputX;
transform.rotation = Quaternion.Euler(0, roll, 0);
}
private void OnTriggerEnter2D(Collider2D collision) {
DamangeDealer damangeDealer = collision.gameObject.GetComponent<DamangeDealer>();
if (damangeDealer) {
playerStatController.DecreaseShield(damangeDealer.DamangeAmount);
Destroy(collision.gameObject);
}
}
private void OnSheildValueChangeCheckForDeath(int shield) {
if (shield <= 0) {
sceneManager.LooseScreenDelayed();
Instantiate(deathFX, transform.position, Quaternion.identity);
var audioPlayerInstance = Instantiate(audioPlayer);
AudioSource audioSource = audioPlayerInstance.GetComponent<AudioSource>();
audioSource.clip = deathSound;
audioSource.Play();
Destroy(audioPlayerInstance, deathSound.length);
Destroy(gameObject);
} else {
animator.SetTrigger(PredefinedStrings.ANIMATION_SHIELD_ACTIVE);
}
}
}
| 37.275 | 93 | 0.681422 | [
"Apache-2.0"
] | vadym-vasilyev/star-rage | Assets/Scripts/Player/PlayerShip.cs | 2,984 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Network.V20210301.Outputs
{
/// <summary>
/// Nat Gateway resource.
/// </summary>
[OutputType]
public sealed class NatGatewayResponse
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
public readonly string Etag;
/// <summary>
/// Resource ID.
/// </summary>
public readonly string? Id;
/// <summary>
/// The idle timeout of the nat gateway.
/// </summary>
public readonly int? IdleTimeoutInMinutes;
/// <summary>
/// Resource location.
/// </summary>
public readonly string? Location;
/// <summary>
/// Resource name.
/// </summary>
public readonly string Name;
/// <summary>
/// The provisioning state of the NAT gateway resource.
/// </summary>
public readonly string ProvisioningState;
/// <summary>
/// An array of public ip addresses associated with the nat gateway resource.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> PublicIpAddresses;
/// <summary>
/// An array of public ip prefixes associated with the nat gateway resource.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> PublicIpPrefixes;
/// <summary>
/// The resource GUID property of the NAT gateway resource.
/// </summary>
public readonly string ResourceGuid;
/// <summary>
/// The nat gateway SKU.
/// </summary>
public readonly Outputs.NatGatewaySkuResponse? Sku;
/// <summary>
/// An array of references to the subnets using this nat gateway resource.
/// </summary>
public readonly ImmutableArray<Outputs.SubResourceResponse> Subnets;
/// <summary>
/// Resource tags.
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
/// <summary>
/// A list of availability zones denoting the zone in which Nat Gateway should be deployed.
/// </summary>
public readonly ImmutableArray<string> Zones;
[OutputConstructor]
private NatGatewayResponse(
string etag,
string? id,
int? idleTimeoutInMinutes,
string? location,
string name,
string provisioningState,
ImmutableArray<Outputs.SubResourceResponse> publicIpAddresses,
ImmutableArray<Outputs.SubResourceResponse> publicIpPrefixes,
string resourceGuid,
Outputs.NatGatewaySkuResponse? sku,
ImmutableArray<Outputs.SubResourceResponse> subnets,
ImmutableDictionary<string, string>? tags,
string type,
ImmutableArray<string> zones)
{
Etag = etag;
Id = id;
IdleTimeoutInMinutes = idleTimeoutInMinutes;
Location = location;
Name = name;
ProvisioningState = provisioningState;
PublicIpAddresses = publicIpAddresses;
PublicIpPrefixes = publicIpPrefixes;
ResourceGuid = resourceGuid;
Sku = sku;
Subnets = subnets;
Tags = tags;
Type = type;
Zones = zones;
}
}
}
| 31.414634 | 99 | 0.587992 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Network/V20210301/Outputs/NatGatewayResponse.cs | 3,864 | C# |
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Calamari.CloudAccounts;
using Calamari.Common.Plumbing;
using Calamari.Common.Plumbing.FileSystem;
using Calamari.Common.Plumbing.Logging;
using Calamari.Common.Plumbing.Retry;
using Calamari.Terraform;
using Calamari.Tests.Helpers;
using Calamari.Tests.Shared;
using FluentAssertions;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using Sashimi.Server.Contracts.ActionHandlers;
using Sashimi.Terraform.ActionHandler;
using Sashimi.Tests.Shared.Server;
using KnownVariables = Sashimi.Server.Contracts.KnownVariables;
using TestEnvironment = Sashimi.Tests.Shared.TestEnvironment;
namespace Sashimi.Terraform.Tests
{
[TestFixture]
public class ActionHandlersFixture
{
//This is the version of the Terraform CLI we bundle
const string TerraformVersion = BundledCliFixture.TerraformVersion;
string? customTerraformExecutable;
[OneTimeSetUp]
public async Task InstallTools()
{
static string GetTerraformFileName(string currentVersion)
{
if (CalamariEnvironment.IsRunningOnNix)
return $"terraform_{currentVersion}_linux_amd64.zip";
if (CalamariEnvironment.IsRunningOnMac)
return $"terraform_{currentVersion}_darwin_amd64.zip";
return $"terraform_{currentVersion}_windows_amd64.zip";
}
static async Task DownloadTerraform(string fileName,
HttpClient client,
string downloadBaseUrl,
string destination)
{
var zipPath = Path.Combine(Path.GetTempPath(), fileName);
using (new TemporaryFile(zipPath))
{
using (var fileStream =
new FileStream(zipPath, FileMode.Create, FileAccess.Write, FileShare.None))
using (var stream = await client.GetStreamAsync($"{downloadBaseUrl}{fileName}"))
{
await stream.CopyToAsync(fileStream);
}
ZipFile.ExtractToDirectory(zipPath, destination);
}
}
async Task DownloadCli(string destination)
{
Console.WriteLine("Downloading terraform cli...");
var retry = new RetryTracker(3, TimeSpan.MaxValue, new LimitedExponentialRetryInterval(1000, 30000, 2));
while (retry.Try())
{
try
{
using (var client = new HttpClient())
{
var downloadBaseUrl = $"https://releases.hashicorp.com/terraform/{TerraformVersion}/";
var fileName = GetTerraformFileName(TerraformVersion);
await DownloadTerraform(fileName, client, downloadBaseUrl, destination);
}
customTerraformExecutable = Directory.EnumerateFiles(destination).FirstOrDefault();
Console.WriteLine($"Downloaded terraform to {customTerraformExecutable}");
ExecutableHelper.AddExecutePermission(customTerraformExecutable);
break;
}
catch
{
if (!retry.CanRetry())
{
throw;
}
await Task.Delay(retry.Sleep());
}
}
}
var destinationDirectoryName = TestEnvironment.GetTestPath("TerraformCLIPath");
if (Directory.Exists(destinationDirectoryName))
{
var path = Directory.EnumerateFiles(destinationDirectoryName).FirstOrDefault();
if (path != null)
{
customTerraformExecutable = path;
Console.WriteLine($"Using existing terraform located in {customTerraformExecutable}");
return;
}
}
await DownloadCli(destinationDirectoryName);
}
[Test]
public void ExtraInitParametersAreSet()
{
var additionalParams = "-var-file=\"backend.tfvars\"";
ExecuteAndReturnLogOutput<TerraformPlanActionHandler>(_ =>
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.AdditionalInitParams, additionalParams),
"Simple")
.Should()
.Contain($"init -no-color -get-plugins=true {additionalParams}");
}
[Test]
public void AllowPluginDownloadsShouldBeDisabled()
{
ExecuteAndReturnLogOutput<TerraformPlanActionHandler>(
_ =>
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.AllowPluginDownloads,
false.ToString());
},
"Simple")
.Should()
.Contain("init -no-color -get-plugins=false");
}
[Test]
public void AttachLogFile()
{
ExecuteAndReturnLogOutput<TerraformPlanActionHandler>(_ =>
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.AttachLogFile, true.ToString()),
"Simple",
result =>
{
result.Artifacts.Count.Should().Be(1);
});
}
[Test]
[TestCase(typeof(TerraformPlanActionHandler), "plan -no-color -detailed-exitcode -var my_var=\"Hello world\"")]
[TestCase(typeof(TerraformApplyActionHandler), "apply -no-color -auto-approve -var my_var=\"Hello world\"")]
[TestCase(typeof(TerraformPlanDestroyActionHandler), "plan -no-color -detailed-exitcode -destroy -var my_var=\"Hello world\"")]
[TestCase(typeof(TerraformDestroyActionHandler), "destroy -force -no-color -var my_var=\"Hello world\"")]
public void AdditionalActionParams(Type commandType, string expected)
{
ExecuteAndReturnLogOutput(commandType, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.AdditionalActionParams, "-var my_var=\"Hello world\""); }, "AdditionalParams")
.Should()
.Contain(expected);
}
[Test]
[TestCase(typeof(TerraformPlanActionHandler), "plan -no-color -detailed-exitcode -var-file=\"example.tfvars\"")]
[TestCase(typeof(TerraformApplyActionHandler), "apply -no-color -auto-approve -var-file=\"example.tfvars\"")]
[TestCase(typeof(TerraformPlanDestroyActionHandler), "plan -no-color -detailed-exitcode -destroy -var-file=\"example.tfvars\"")]
[TestCase(typeof(TerraformDestroyActionHandler), "destroy -force -no-color -var-file=\"example.tfvars\"")]
public void VarFiles(Type commandType, string actual)
{
ExecuteAndReturnLogOutput(commandType, _ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars"); }, "WithVariables")
.Should()
.Contain(actual);
}
[Test]
public void WithOutputSensitiveVariables()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ => { },
"WithOutputSensitiveVariables",
result =>
{
result.OutputVariables.Values.Should().OnlyContain(variable => variable.IsSensitive);
});
}
[Test]
public void OutputAndSubstituteOctopusVariables()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.txt");
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "example.txt");
_.Variables.Add("Octopus.Action.StepName", "Step Name");
_.Variables.Add("Should_Be_Substituted", "Hello World");
_.Variables.Add("Should_Be_Substituted_in_txt", "Hello World from text");
},
"WithVariablesSubstitution",
result =>
{
result.OutputVariables
.ContainsKey("TerraformValueOutputs[my_output]")
.Should()
.BeTrue();
result.OutputVariables["TerraformValueOutputs[my_output]"]
.Value
.Should()
.Be("Hello World");
result.OutputVariables
.ContainsKey("TerraformValueOutputs[my_output_from_txt_file]")
.Should()
.BeTrue();
result.OutputVariables["TerraformValueOutputs[my_output_from_txt_file]"]
.Value
.Should()
.Be("Hello World from text");
});
}
[Test]
public void EnableNoMatchWarningIsNotSet()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(variables => { }, "Simple")
.Should()
.NotContain("No files were found that match the substitution target pattern");
}
[Test]
public void EnableNoMatchWarningIsNotSetWithAdditionSubstitution()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "doesNotExist.txt");
},
"Simple")
.Should()
.Contain("No files were found that match the substitution target pattern '**/*.tfvars.json'")
.And
.Contain("No files were found that match the substitution target pattern 'doesNotExist.txt'");
}
[Test]
public void EnableNoMatchWarningIsTrue()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "doesNotExist.txt");
_.Variables.Add(KnownVariables.Action.SubstituteInFiles.EnableNoMatchWarning, "true");
},
"Simple")
.Should()
.Contain("No files were found that match the substitution target pattern '**/*.tfvars.json'")
.And
.Contain("No files were found that match the substitution target pattern 'doesNotExist.txt'");
}
[Test]
public void EnableNoMatchWarningIsFalse()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "doesNotExist.txt");
_.Variables.Add(KnownVariables.Action.SubstituteInFiles.EnableNoMatchWarning, "False");
},
"Simple")
.Should()
.NotContain("No files were found that match the substitution target pattern");
}
[Test]
[TestCase(typeof(TerraformPlanActionHandler))]
[TestCase(typeof(TerraformPlanDestroyActionHandler))]
public void TerraformPlanOutput(Type commandType)
{
ExecuteAndReturnLogOutput(commandType,
_ => { _.Variables.Add("Octopus.Action.StepName", "Step Name"); },
"Simple",
result =>
{
result.OutputVariables
.ContainsKey("TerraformPlanOutput")
.Should()
.BeTrue();
});
}
[Test]
public void UsesWorkSpace()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.Workspace, "myspace"); }, "Simple")
.Should()
.Contain("workspace new \"myspace\"");
}
[Test]
public void UsesTemplateDirectory()
{
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ => { _.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateDirectory, "SubFolder"); }, "TemplateDirectory")
.Should()
.Contain($"SubFolder{Path.DirectorySeparatorChar}example.tf");
}
[Test]
public async Task AzureIntegration()
{
var random = Guid.NewGuid().ToString("N").Substring(0, 6);
var appName = $"cfe2e-{random}";
var expectedHostName = $"{appName}.azurewebsites.net";
using var temporaryFolder = TemporaryDirectory.Create();
CopyAllFiles(TestEnvironment.GetTestPath("Azure"), temporaryFolder.DirectoryPath);
void PopulateVariables(TestActionHandlerContext<Program> _)
{
_.Variables.Add(AzureAccountVariables.SubscriptionId, ExternalVariables.Get(ExternalVariable.AzureSubscriptionId));
_.Variables.Add(AzureAccountVariables.TenantId, ExternalVariables.Get(ExternalVariable.AzureSubscriptionTenantId));
_.Variables.Add(AzureAccountVariables.ClientId, ExternalVariables.Get(ExternalVariable.AzureSubscriptionClientId));
_.Variables.Add(AzureAccountVariables.Password, ExternalVariables.Get(ExternalVariable.AzureSubscriptionPassword));
_.Variables.Add("app_name", appName);
_.Variables.Add("random", random);
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars");
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.AzureManagedAccount, Boolean.TrueString);
_.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, temporaryFolder.DirectoryPath);
}
var output = ExecuteAndReturnResult(typeof(TerraformPlanActionHandler), PopulateVariables, "Azure");
output.OutputVariables.ContainsKey("TerraformPlanOutput").Should().BeTrue();
output = ExecuteAndReturnResult(typeof(TerraformApplyActionHandler), PopulateVariables, "Azure");
output.OutputVariables.ContainsKey("TerraformValueOutputs[url]").Should().BeTrue();
output.OutputVariables["TerraformValueOutputs[url]"].Value.Should().Be(expectedHostName);
await AssertRequestResponse(HttpStatusCode.Forbidden);
ExecuteAndReturnResult(typeof(TerraformDestroyActionHandler), PopulateVariables, "Azure");
await AssertResponseIsNotReachable();
async Task AssertResponseIsNotReachable()
{
//This will throw on some platforms and return "NotFound" on others
try
{
await AssertRequestResponse(HttpStatusCode.NotFound);
}
catch (HttpRequestException ex)
{
ex.Message.Should().BeOneOf(
"No such host is known.",
"Name or service not known", //Some Linux distros
"nodename nor servname provided, or not known" //Mac
);
}
}
async Task AssertRequestResponse(HttpStatusCode expectedStatusCode)
{
using var client = new HttpClient();
var response = await client.GetAsync($"https://{expectedHostName}").ConfigureAwait(false);
response.StatusCode.Should().Be(expectedStatusCode);
}
}
[Test]
public async Task AWSIntegration()
{
var bucketName = $"cfe2e-tf-{Guid.NewGuid().ToString("N").Substring(0, 6)}";
var expectedUrl = $"https://{bucketName}.s3.amazonaws.com/test.txt";
using var temporaryFolder = TemporaryDirectory.Create();
CopyAllFiles(TestEnvironment.GetTestPath("AWS"), temporaryFolder.DirectoryPath);
void PopulateVariables(TestActionHandlerContext<Program> _)
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.FileSubstitution, "test.txt");
_.Variables.Add("Octopus.Action.Amazon.AccessKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3AccessKey));
_.Variables.Add("Octopus.Action.Amazon.SecretKey", ExternalVariables.Get(ExternalVariable.AwsCloudFormationAndS3SecretKey));
_.Variables.Add("Octopus.Action.Aws.Region", "ap-southeast-1");
_.Variables.Add("Hello", "Hello World from AWS");
_.Variables.Add("bucket_name", bucketName);
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.VarFiles, "example.tfvars");
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.AWSManagedAccount, "AWS");
_.Variables.Add(KnownVariables.OriginalPackageDirectoryPath, temporaryFolder.DirectoryPath);
}
var output = ExecuteAndReturnResult(typeof(TerraformPlanActionHandler), PopulateVariables, "AWS");
output.OutputVariables.ContainsKey("TerraformPlanOutput").Should().BeTrue();
output = ExecuteAndReturnResult(typeof(TerraformApplyActionHandler), PopulateVariables, "AWS");
output.OutputVariables.ContainsKey("TerraformValueOutputs[url]").Should().BeTrue();
output.OutputVariables["TerraformValueOutputs[url]"].Value.Should().Be(expectedUrl);
string fileData;
using (var client = new HttpClient())
fileData = await client.GetStringAsync(expectedUrl).ConfigureAwait(false);
fileData.Should().Be("Hello World from AWS");
ExecuteAndReturnResult(typeof(TerraformDestroyActionHandler), PopulateVariables, "AWS");
using (var client = new HttpClient())
{
var response = await client.GetAsync(expectedUrl).ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
}
[Test]
public void PlanDetailedExitCode()
{
using var stateFileFolder = TemporaryDirectory.Create();
void PopulateVariables(TestActionHandlerContext<Program> _)
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.AdditionalActionParams,
$"-state=\"{Path.Combine(stateFileFolder.DirectoryPath, "terraform.tfstate")}\" -refresh=false");
}
var output = ExecuteAndReturnResult(typeof(TerraformPlanActionHandler), PopulateVariables, "PlanDetailedExitCode");
output.OutputVariables.ContainsKey("TerraformPlanDetailedExitCode").Should().BeTrue();
output.OutputVariables["TerraformPlanDetailedExitCode"].Value.Should().Be("2");
output = ExecuteAndReturnResult(typeof(TerraformApplyActionHandler), PopulateVariables, "PlanDetailedExitCode");
output.FullLog.Should()
.Contain("apply -no-color -auto-approve");
output = ExecuteAndReturnResult(typeof(TerraformPlanActionHandler), PopulateVariables, "PlanDetailedExitCode");
output.OutputVariables.ContainsKey("TerraformPlanDetailedExitCode").Should().BeTrue();
output.OutputVariables["TerraformPlanDetailedExitCode"].Value.Should().Be("0");
}
[Test]
public void InlineHclTemplateAndVariables()
{
const string variables =
"{\"stringvar\":\"default string\",\"images\":\"\",\"test2\":\"\",\"test3\":\"\",\"test4\":\"\"}";
const string template = @"variable stringvar {
type = ""string""
default = ""default string""
}
variable ""images"" {
type = ""map""
default = {
us-east-1 = ""image-1234""
us-west-2 = ""image-4567""
}
}
variable ""test2"" {
type = ""map""
default = {
val1 = [""hi""]
}
}
variable ""test3"" {
type = ""map""
default = {
val1 = {
val2 = ""#{RandomNumber}""
}
}
}
variable ""test4"" {
type = ""map""
default = {
val1 = {
val2 = [""hi""]
}
}
}
# Example of getting an element from a list in a map
output ""nestedlist"" {
value = ""${element(var.test2[""val1""], 0)}""
}
# Example of getting an element from a nested map
output ""nestedmap"" {
value = ""${lookup(var.test3[""val1""], ""val2"")}""
}";
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add("RandomNumber", new Random().Next().ToString());
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template);
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, variables);
_.Variables.Add(KnownVariables.Action.Script.ScriptSource,
KnownVariables.Action.Script.ScriptSourceOptions.Inline);
},
String.Empty,
_ =>
{
_.OutputVariables.ContainsKey("TerraformValueOutputs[nestedlist]").Should().BeTrue();
_.OutputVariables.ContainsKey("TerraformValueOutputs[nestedmap]").Should().BeTrue();
});
}
[Test]
public void InlineHclTemplateWithMultilineOutput()
{
const string expected = @"apiVersion: v1
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
data:
mapRoles: |
- rolearn: arbitrary text
username: system:node:username
groups:
- system:bootstrappers
- system:nodes";
string template = String.Format(@"locals {{
config-map-aws-auth = <<CONFIGMAPAWSAUTH
{0}
CONFIGMAPAWSAUTH
}}
output ""config-map-aws-auth"" {{
value = ""${{local.config-map-aws-auth}}""
}}",
expected);
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template);
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, "{}");
_.Variables.Add(KnownVariables.Action.Script.ScriptSource,
KnownVariables.Action.Script.ScriptSourceOptions.Inline);
},
String.Empty,
_ =>
{
_.OutputVariables.ContainsKey("TerraformValueOutputs[config-map-aws-auth]").Should().BeTrue();
_.OutputVariables["TerraformValueOutputs[config-map-aws-auth]"]
.Value?.TrimEnd().Should()
.Be($"{expected.Replace("\r\n", "\n")}");
});
}
[Test]
public void InlineJsonTemplateAndVariables()
{
const string variables =
"{\"ami\":\"new ami value\"}";
const string template = @"{
""variable"":{
""ami"":{
""type"":""string"",
""description"":""the AMI to use"",
""default"":""1234567890""
}
},
""output"":{
""test"":{
""value"":""hi there""
},
""test2"":{
""value"":[
""hi there"",
""hi again""
]
},
""test3"":{
""value"":""${map(\""a\"", \""hi\"")}""
},
""ami"":{
""value"":""${var.ami}""
},
""random"":{
""value"":""#{RandomNumber}""
}
}
}";
var randomNumber = new Random().Next().ToString();
ExecuteAndReturnLogOutput<TerraformApplyActionHandler>(_ =>
{
_.Variables.Add("RandomNumber", randomNumber);
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.Template, template);
_.Variables.Add(TerraformSpecialVariables.Action.Terraform.TemplateParameters, variables);
_.Variables.Add(KnownVariables.Action.Script.ScriptSource,
KnownVariables.Action.Script.ScriptSourceOptions.Inline);
},
String.Empty,
_ =>
{
_.OutputVariables.ContainsKey("TerraformValueOutputs[ami]").Should().BeTrue();
_.OutputVariables["TerraformValueOutputs[ami]"].Value.Should().Be("new ami value");
_.OutputVariables.ContainsKey("TerraformValueOutputs[random]").Should().BeTrue();
_.OutputVariables["TerraformValueOutputs[random]"].Value.Should().Be(randomNumber);
});
}
static void CopyAllFiles(string sourceFolderPath, string destinationFolderPath)
{
if (Directory.Exists(sourceFolderPath))
{
var filePaths = Directory.GetFiles(sourceFolderPath);
// Copy the files and overwrite destination files if they already exist.
foreach (var filePath in filePaths)
{
var fileName = Path.GetFileName(filePath);
var destFilePath = Path.Combine(destinationFolderPath, fileName);
File.Copy(filePath, destFilePath, true);
}
}
else
{
throw new Exception($"'{nameof(sourceFolderPath)}' ({sourceFolderPath}) does not exist!");
}
}
string ExecuteAndReturnLogOutput(Type commandType,
Action<TestActionHandlerContext<Program>> populateVariables,
string folderName,
Action<TestActionHandlerResult>? assert = null)
{
return ExecuteAndReturnResult(commandType, populateVariables, folderName, assert).FullLog;
}
string ExecuteAndReturnLogOutput<T>(Action<TestActionHandlerContext<Program>> populateVariables,
string folderName,
Action<TestActionHandlerResult>? assert = null) where T : IActionHandler
{
return ExecuteAndReturnLogOutput(typeof(T), populateVariables, folderName, assert);
}
TestActionHandlerResult ExecuteAndReturnResult(Type commandType, Action<TestActionHandlerContext<Program>> populateVariables, string folderName, Action<TestActionHandlerResult>? assert = null)
{
var assertResult = assert ?? (_ => { });
var terraformFiles = TestEnvironment.GetTestPath(folderName);
var result = ActionHandlerTestBuilder.CreateAsync<Program>(commandType)
.WithArrange(context =>
{
context.Variables.Add(KnownVariables.Action.Script.ScriptSource,
KnownVariables.Action.Script.ScriptSourceOptions.Package);
context.Variables.Add(KnownVariables.Action.Packages.PackageId, terraformFiles);
context.Variables.Add(TerraformSpecialVariables.Calamari.TerraformCliPath,
Path.GetDirectoryName(customTerraformExecutable));
context.Variables.Add(TerraformSpecialVariables.Action.Terraform.CustomTerraformExecutable,
customTerraformExecutable);
populateVariables(context);
if (!String.IsNullOrEmpty(folderName))
{
context.WithFilesToCopy(terraformFiles);
}
})
.Execute();
assertResult(result);
return result;
}
}
} | 53.182094 | 200 | 0.467144 | [
"Apache-2.0"
] | matt-richardson/Sashimi.Terraform | source/Sashimi.Tests/ActionHandlersFixture.cs | 35,047 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.System.RemoteSystems;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario1_Discovery : Page
{
private MainPage m_rootPage;
private RemoteSystemWatcher m_remoteSystemWatcher;
public Scenario1_Discovery()
{
this.InitializeComponent();
this.DataContext = this;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
m_rootPage = MainPage.Current;
m_rootPage.systemList = new ObservableCollection<RemoteSystem>();
m_rootPage.systemMap = new Dictionary<string, RemoteSystem>();
}
public ObservableCollection<RemoteSystem> SystemList => m_rootPage.systemList;
private async void Search_Clicked(object sender, RoutedEventArgs e)
{
// Disable the Search button while watcher is being started to avoid a potential
// race condition of having two RemoteSystemWatchers running in parallel.
Button searchButton = sender as Button;
searchButton.IsHitTestVisible = false;
// Cleaning up any existing systems from previous searches.
SearchCleanup();
// Verify access for Remote Systems.
// Note: RequestAccessAsync needs to called from the UI thread.
RemoteSystemAccessStatus accessStatus = await RemoteSystem.RequestAccessAsync();
if (accessStatus == RemoteSystemAccessStatus.Allowed)
{
if (HostNameSearch.IsChecked.Value)
{
await SearchByHostNameAsync();
}
else
{
SearchByRemoteSystemWatcher();
}
}
else
{
UpdateStatus("Access to Remote Systems is " + accessStatus.ToString(), NotifyType.ErrorMessage);
}
searchButton.IsHitTestVisible = true;
}
private async Task SearchByHostNameAsync()
{
if (!string.IsNullOrWhiteSpace(HostNameTextBox.Text))
{
// Build hostname object.
HostName hostName = new HostName(HostNameTextBox.Text);
// Get Remote System from HostName.
RemoteSystem remoteSystem = await RemoteSystem.FindByHostNameAsync(hostName);
if (remoteSystem != null)
{
m_rootPage.systemList.Add(remoteSystem);
SystemListBox.Visibility = Visibility.Visible;
UpdateStatus("Found system - " + remoteSystem.DisplayName, NotifyType.StatusMessage);
}
else
{
UpdateStatus("Unable to find the system.", NotifyType.ErrorMessage);
}
}
else
{
UpdateStatus("Enter a valid host name", NotifyType.ErrorMessage);
}
}
private void SearchByRemoteSystemWatcher()
{
if (FilterSearch.IsChecked.Value)
{
// Build a watcher to continuously monitor for filtered remote systems.
m_remoteSystemWatcher = RemoteSystem.CreateWatcher(BuildFilters());
}
else
{
// Build a watcher to continuously monitor for all remote systems.
m_remoteSystemWatcher = RemoteSystem.CreateWatcher();
}
// Subscribing to the event that will be raised when a new remote system is found by the watcher.
m_remoteSystemWatcher.RemoteSystemAdded += RemoteSystemWatcher_RemoteSystemAdded;
// Subscribing to the event that will be raised when a previously found remote system is no longer available.
m_remoteSystemWatcher.RemoteSystemRemoved += RemoteSystemWatcher_RemoteSystemRemoved;
// Subscribing to the event that will be raised when a previously found remote system is updated.
m_remoteSystemWatcher.RemoteSystemUpdated += RemoteSystemWatcher_RemoteSystemUpdated;
// Start the watcher.
m_remoteSystemWatcher.Start();
UpdateStatus("Searching for systems...", NotifyType.StatusMessage);
SystemListBox.Visibility = Visibility.Visible;
}
private async void RemoteSystemWatcher_RemoteSystemUpdated(RemoteSystemWatcher sender, RemoteSystemUpdatedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (m_rootPage.systemMap.ContainsKey(args.RemoteSystem.Id))
{
m_rootPage.systemList.Remove(m_rootPage.systemMap[args.RemoteSystem.Id]);
m_rootPage.systemMap.Remove(args.RemoteSystem.Id);
}
m_rootPage.systemList.Add(args.RemoteSystem);
m_rootPage.systemMap.Add(args.RemoteSystem.Id, args.RemoteSystem);
UpdateStatus("System updated with Id = " + args.RemoteSystem.Id, NotifyType.StatusMessage);
});
}
private async void RemoteSystemWatcher_RemoteSystemRemoved(RemoteSystemWatcher sender, RemoteSystemRemovedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (m_rootPage.systemMap.ContainsKey(args.RemoteSystemId))
{
m_rootPage.systemList.Remove(m_rootPage.systemMap[args.RemoteSystemId]);
UpdateStatus(m_rootPage.systemMap[args.RemoteSystemId].DisplayName + " removed.", NotifyType.StatusMessage);
m_rootPage.systemMap.Remove(args.RemoteSystemId);
}
});
}
private async void RemoteSystemWatcher_RemoteSystemAdded(RemoteSystemWatcher sender, RemoteSystemAddedEventArgs args)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
m_rootPage.systemList.Add(args.RemoteSystem);
m_rootPage.systemMap.Add(args.RemoteSystem.Id, args.RemoteSystem);
UpdateStatus(string.Format("Found {0} systems.", m_rootPage.systemList.Count), NotifyType.StatusMessage);
});
}
private List<IRemoteSystemFilter> BuildFilters()
{
List<IRemoteSystemFilter> filters = new List<IRemoteSystemFilter>();
RemoteSystemDiscoveryTypeFilter discoveryFilter;
RemoteSystemAuthorizationKindFilter authorizationKindFilter;
List<string> kinds = new List<string>();
RemoteSystemStatusTypeFilter statusFilter;
if (DiscoveryTypeOptions.IsChecked.Value)
{
// Build discovery type filters
if (ProximalRadioButton.IsChecked.Value)
{
discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.Proximal);
}
else if (CloudRadioButton.IsChecked.Value)
{
discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.Cloud);
}
else if (SpatiallyProximalRadioButton.IsChecked.Value)
{
discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.SpatiallyProximal);
}
else
{
discoveryFilter = new RemoteSystemDiscoveryTypeFilter(RemoteSystemDiscoveryType.Any);
}
filters.Add(discoveryFilter);
}
if (AuthorizationTypeOptions.IsChecked.Value)
{
// Build authorization type filters
if (AnonymousDiscoveryRadioButton.IsChecked.Value)
{
authorizationKindFilter = new RemoteSystemAuthorizationKindFilter(RemoteSystemAuthorizationKind.Anonymous);
}
else
{
authorizationKindFilter = new RemoteSystemAuthorizationKindFilter(RemoteSystemAuthorizationKind.SameUser);
}
filters.Add(authorizationKindFilter);
}
if (SystemTypeOptions.IsChecked.Value)
{
// Build system type filters
if (DesktopCheckBox.IsChecked.Value)
{
kinds.Add(RemoteSystemKinds.Desktop);
}
if (HolographicCheckBox.IsChecked.Value)
{
kinds.Add(RemoteSystemKinds.Holographic);
}
if (HubCheckBox.IsChecked.Value)
{
kinds.Add(RemoteSystemKinds.Hub);
}
if (PhoneCheckBox.IsChecked.Value)
{
kinds.Add(RemoteSystemKinds.Phone);
}
if (XboxCheckBox.IsChecked.Value)
{
kinds.Add(RemoteSystemKinds.Xbox);
}
if (kinds.Count == 0)
{
UpdateStatus("Select a system type filter.", NotifyType.ErrorMessage);
}
else
{
RemoteSystemKindFilter kindFilter = new RemoteSystemKindFilter(kinds);
filters.Add(kindFilter);
}
}
if (StatusTypeOptions.IsChecked.Value)
{
// Build status type filters
if (AvailableRadioButton.IsChecked.Value)
{
statusFilter = new RemoteSystemStatusTypeFilter(RemoteSystemStatusType.Available);
}
else
{
statusFilter = new RemoteSystemStatusTypeFilter(RemoteSystemStatusType.Any);
}
filters.Add(statusFilter);
}
return filters;
}
private void SearchCleanup()
{
if (m_remoteSystemWatcher != null)
{
m_remoteSystemWatcher.Stop();
m_remoteSystemWatcher = null;
}
m_rootPage.systemList.Clear();
m_rootPage.systemMap.Clear();
}
private void UpdateStatus(string status, NotifyType statusType)
{
m_rootPage.NotifyUser(status, statusType);
}
}
} | 40.660777 | 130 | 0.562353 | [
"MIT"
] | Flashyhundred/UWPSamples | Samples/RemoteSystems/cs/Scenario1_Discovery.xaml.cs | 11,225 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.461)
// Version 5.461.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
namespace ComponentFactory.Krypton.Toolkit
{
/// <summary>
/// Used to obscure an area of the screen to hide form changes underneath.
/// </summary>
[ToolboxItem(false)]
public class ScreenObscurer : IDisposable
{
#region ObscurerForm
private class ObscurerForm : Form
{
#region Identity
public ObscurerForm()
{
// Prevent automatic positioning of the window
StartPosition = FormStartPosition.Manual;
Location = new Point(-int.MaxValue, -int.MaxValue);
Size = Size.Empty;
// We do not want any window chrome
FormBorderStyle = FormBorderStyle.None;
// We do not want a taskbar entry for this temporary window
ShowInTaskbar = false;
}
#endregion
#region Public
public void ShowForm(Rectangle screenRect)
{
// Our initial position should overlay exactly the container
SetBounds(screenRect.X,
screenRect.Y,
screenRect.Width,
screenRect.Height);
// Show the window without activating it (i.e. do not take focus)
PI.ShowWindow(Handle, PI.ShowWindowCommands.SW_SHOWNOACTIVATE);
}
#endregion
#region Protected
/// <summary>
/// Raises the PaintBackground event.
/// </summary>
/// <param name="e">An PaintEventArgs containing the event data.</param>
protected override void OnPaintBackground(PaintEventArgs e)
{
// We do nothing, so the area underneath shows through
}
/// <summary>
/// Raises the Paint event.
/// </summary>
/// <param name="e">An PaintEventArgs containing the event data.</param>
protected override void OnPaint(PaintEventArgs e)
{
// We do nothing, so the area underneath shows through
}
#endregion
}
#endregion
#region Static Fields
private ObscurerForm _obscurer;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ControlObscurer class.
/// </summary>
public ScreenObscurer()
{
// First time needed, create the top level obscurer window
if (_obscurer == null)
{
_obscurer = new ObscurerForm();
}
}
/// <summary>
/// Initialize a new instance of the ControlObscurer class.
/// </summary>
/// <param name="f">Form to obscure.</param>
/// <param name="designMode">Is the source in design mode.</param>
public ScreenObscurer(Form f, bool designMode)
{
// Check the incoming form is valid
if ((f != null) && !f.IsDisposed && !designMode)
{
// First time needed, create the top level obscurer window
if (_obscurer == null)
{
_obscurer = new ObscurerForm();
}
// We need a control to work with!
if (f != null)
{
_obscurer.ShowForm(f.Bounds);
}
}
}
/// <summary>
/// Initialize a new instance of the ControlObscurer class.
/// </summary>
/// <param name="c">Control to obscure.</param>
/// <param name="designMode">Is the source in design mode.</param>
public ScreenObscurer(Control c, bool designMode)
{
// Check the incoming control is valid
if ((c != null) && !c.IsDisposed && !designMode)
{
// First time needed, create the top level obscurer window
if (_obscurer == null)
{
_obscurer = new ObscurerForm();
}
// We need a control to work with!
if (c != null)
{
_obscurer.ShowForm(c.RectangleToScreen(c.ClientRectangle));
}
}
}
/// <summary>
/// Use the obscurer to cover the provided control.
/// </summary>
/// <param name="f">Form to obscure.</param>
public void Cover(Form f)
{
// Check the incoming form is valid
if ((f != null) && !f.IsDisposed)
{
// Show over top of the provided form
_obscurer?.ShowForm(f.Bounds);
}
}
/// <summary>
/// Use the obscurer to cover the provided control.
/// </summary>
/// <param name="c">Control to obscure.</param>
public void Cover(Control c)
{
// Check the incoming control is valid
if ((c != null) && !c.IsDisposed)
{
// Show over top of the provided control
_obscurer?.ShowForm(c.RectangleToScreen(c.ClientRectangle));
}
}
/// <summary>
/// If covering an area then uncover it now.
/// </summary>
public void Uncover()
{
_obscurer?.Hide();
}
/// <summary>
/// Hide the obscurer from display.
/// </summary>
public void Dispose()
{
if (_obscurer != null)
{
_obscurer.Hide();
_obscurer.Dispose();
_obscurer = null;
}
}
#endregion
}
}
| 33.928571 | 157 | 0.502406 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.461 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/General/ControlObscurer.cs | 6,653 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Mvc
{
public class HttpNotFoundObjectResultTest
{
[Fact]
public void HttpNotFoundObjectResult_InitializesStatusCode()
{
// Arrange & act
var notFound = new NotFoundObjectResult(null);
// Assert
Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode);
}
[Fact]
public void HttpNotFoundObjectResult_InitializesStatusCodeAndResponseContent()
{
// Arrange & act
var notFound = new NotFoundObjectResult("Test Content");
// Assert
Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode);
Assert.Equal("Test Content", notFound.Value);
}
[Fact]
public async Task HttpNotFoundObjectResult_ExecuteSuccessful()
{
// Arrange
var httpContext = GetHttpContext();
var actionContext = new ActionContext()
{
HttpContext = httpContext,
};
var result = new NotFoundObjectResult("Test Content");
// Act
await result.ExecuteResultAsync(actionContext);
// Assert
Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode);
}
private static HttpContext GetHttpContext()
{
var httpContext = new DefaultHttpContext();
httpContext.Request.PathBase = new PathString("");
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = CreateServices();
return httpContext;
}
private static IServiceProvider CreateServices()
{
var options = Options.Create(new MvcOptions());
options.Value.OutputFormatters.Add(new StringOutputFormatter());
options.Value.OutputFormatters.Add(new SystemTextJsonOutputFormatter(new JsonOptions()));
var services = new ServiceCollection();
services.AddSingleton<IActionResultExecutor<ObjectResult>>(new ObjectResultExecutor(
new DefaultOutputFormatterSelector(options, NullLoggerFactory.Instance),
new TestHttpResponseStreamWriterFactory(),
NullLoggerFactory.Instance));
return services.BuildServiceProvider();
}
}
} | 34.807229 | 111 | 0.65109 | [
"Apache-2.0"
] | FluentGuru/AspNetCore | src/Mvc/Mvc.Core/test/HttpNotFoundObjectResultTest.cs | 2,889 | C# |
// This file contains auto-generated code.
namespace System
{
namespace IO
{
// Generated from `System.IO.DriveInfo` in `System.IO.FileSystem.DriveInfo, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public class DriveInfo : System.Runtime.Serialization.ISerializable
{
public System.Int64 AvailableFreeSpace { get => throw null; }
public string DriveFormat { get => throw null; }
public DriveInfo(string driveName) => throw null;
public System.IO.DriveType DriveType { get => throw null; }
public static System.IO.DriveInfo[] GetDrives() => throw null;
void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) => throw null;
public bool IsReady { get => throw null; }
public string Name { get => throw null; }
public System.IO.DirectoryInfo RootDirectory { get => throw null; }
public override string ToString() => throw null;
public System.Int64 TotalFreeSpace { get => throw null; }
public System.Int64 TotalSize { get => throw null; }
public string VolumeLabel { get => throw null; set => throw null; }
}
// Generated from `System.IO.DriveNotFoundException` in `System.IO.FileSystem.DriveInfo, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public class DriveNotFoundException : System.IO.IOException
{
public DriveNotFoundException(string message, System.Exception innerException) => throw null;
public DriveNotFoundException(string message) => throw null;
public DriveNotFoundException() => throw null;
protected DriveNotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) => throw null;
}
// Generated from `System.IO.DriveType` in `System.IO.FileSystem.DriveInfo, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a`
public enum DriveType
{
CDRom,
Fixed,
Network,
NoRootDirectory,
Ram,
Removable,
Unknown,
}
}
}
| 49.125 | 196 | 0.654792 | [
"MIT"
] | Bhagyanekraje/codeql | csharp/ql/test/resources/stubs/_frameworks/Microsoft.NETCore.App/System.IO.FileSystem.DriveInfo.cs | 2,358 | C# |
/*
* eZmax API Definition (Full)
*
* This API expose all the functionnalities for the eZmax and eZsign applications.
*
* The version of the OpenAPI document: 1.1.7
* Contact: support-api@ezmax.ca
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using Xunit;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using eZmaxApi.Api;
using eZmaxApi.Model;
using eZmaxApi.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace eZmaxApi.Test.Model
{
/// <summary>
/// Class for testing EzsigndocumentGetObjectV1Response
/// </summary>
/// <remarks>
/// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech).
/// Please update the test case below to test the model.
/// </remarks>
public class EzsigndocumentGetObjectV1ResponseTests : IDisposable
{
// TODO uncomment below to declare an instance variable for EzsigndocumentGetObjectV1Response
//private EzsigndocumentGetObjectV1Response instance;
public EzsigndocumentGetObjectV1ResponseTests()
{
// TODO uncomment below to create an instance of EzsigndocumentGetObjectV1Response
//instance = new EzsigndocumentGetObjectV1Response();
}
public void Dispose()
{
// Cleanup when everything is done.
}
/// <summary>
/// Test an instance of EzsigndocumentGetObjectV1Response
/// </summary>
[Fact]
public void EzsigndocumentGetObjectV1ResponseInstanceTest()
{
// TODO uncomment below to test "IsType" EzsigndocumentGetObjectV1Response
//Assert.IsType<EzsigndocumentGetObjectV1Response>(instance);
}
/// <summary>
/// Test the property 'MPayload'
/// </summary>
[Fact]
public void MPayloadTest()
{
// TODO unit test for the property 'MPayload'
}
/// <summary>
/// Test the property 'ObjDebugPayload'
/// </summary>
[Fact]
public void ObjDebugPayloadTest()
{
// TODO unit test for the property 'ObjDebugPayload'
}
/// <summary>
/// Test the property 'ObjDebug'
/// </summary>
[Fact]
public void ObjDebugTest()
{
// TODO unit test for the property 'ObjDebug'
}
}
}
| 27.806818 | 101 | 0.62689 | [
"MIT"
] | ezmaxinc/eZmax-SDK-csharp-netcore | src/eZmaxApi.Test/Model/EzsigndocumentGetObjectV1ResponseTests.cs | 2,447 | C# |
using System;
namespace Sexy.TodLib
{
public enum ParticleFlags
{
RandomLaunchSpin,
AlignLaunchSpin,
AlignToPixels,
SystemLoops,
ParticleLoops,
ParticlesDontFollow,
RandomStartTime,
DieIfOverloaded,
Additive,
Fullscreen,
SoftwareOnly,
HardwareOnly
}
}
| 17.238095 | 29 | 0.585635 | [
"MIT"
] | MeWnoJinsei/PlantsVsZombies.NET | Lawn_Shared/Sexy.TodLib/Particle/ParticleFlags.cs | 364 | C# |
namespace AutoParts.Core.Contracts.Orders.Requests
{
using MediatR;
using Models;
using Common.Models;
public class GetUserOrdersRequest : PaginationFilterModel, IRequest<PageModel<OrderModel>>
{
public long UserId { get; set; }
}
}
| 20.615385 | 94 | 0.69403 | [
"Apache-2.0"
] | antonbubel/auto-parts | Core/AutoParts.Core.Contracts/Orders/Requests/GetUserOrdersRequest.cs | 270 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Bitcoin3.Tests
{
public class pow_tests
{
[Fact]
[Trait("UnitTest", "UnitTest")]
public static void CanCalculatePowCorrectly()
{
ConcurrentChain chain = new ConcurrentChain(Network.Main);
EnsureDownloaded("MainChain.dat", "https://aois.blob.core.windows.net/public/MainChain.dat");
chain.Load(File.ReadAllBytes("MainChain.dat"), Network.Main);
foreach(var block in chain.EnumerateAfter(chain.Genesis))
{
var thisWork = block.GetWorkRequired(Network.Main);
var thisWork2 = block.Previous.GetNextWorkRequired(Network.Main);
Assert.Equal(thisWork, thisWork2);
Assert.True(block.CheckProofOfWorkAndTarget(Network.Main));
}
}
private static void EnsureDownloaded(string file, string url)
{
if(File.Exists(file))
return;
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(5);
var data = client.GetByteArrayAsync(url).GetAwaiter().GetResult();
File.WriteAllBytes(file, data);
}
}
}
| 27.5 | 96 | 0.735931 | [
"MIT"
] | frankvanbokhoven/Bitcoin-3 | Bitcoin3.Tests/pow_tests.cs | 1,157 | C# |
using NBitcoin;
using NBitcoin.Policy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using WalletWasabi.Blockchain.Analysis.Clustering;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Blockchain.TransactionBuilding;
using WalletWasabi.Blockchain.TransactionOutputs;
using WalletWasabi.Exceptions;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Models;
using WalletWasabi.Tor.Socks5.Exceptions;
using WalletWasabi.WebClients.PayJoin;
namespace WalletWasabi.Blockchain.Transactions
{
public class TransactionFactory
{
/// <param name="allowUnconfirmed">Allow to spend unconfirmed transactions, if necessary.</param>
public TransactionFactory(Network network, KeyManager keyManager, ICoinsView coins, AllTransactionStore transactionStore, string password = "", bool allowUnconfirmed = false)
{
Network = network;
KeyManager = keyManager;
Coins = coins;
TransactionStore = transactionStore;
Password = password;
AllowUnconfirmed = allowUnconfirmed;
}
public Network Network { get; }
public KeyManager KeyManager { get; }
public ICoinsView Coins { get; }
public string Password { get; }
public bool AllowUnconfirmed { get; }
private AllTransactionStore TransactionStore { get; }
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public BuildTransactionResult BuildTransaction(
PaymentIntent payments,
FeeRate feeRate,
IEnumerable<OutPoint>? allowedInputs = null,
IPayjoinClient? payjoinClient = null)
=> BuildTransaction(payments, () => feeRate, allowedInputs, () => LockTime.Zero, payjoinClient);
/// <exception cref="ArgumentException"></exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public BuildTransactionResult BuildTransaction(
PaymentIntent payments,
Func<FeeRate> feeRateFetcher,
IEnumerable<OutPoint>? allowedInputs = null,
Func<LockTime>? lockTimeSelector = null,
IPayjoinClient? payjoinClient = null)
{
lockTimeSelector ??= () => LockTime.Zero;
long totalAmount = payments.TotalAmount.Satoshi;
if (totalAmount is < 0 or > Constants.MaximumNumberOfSatoshis)
{
throw new ArgumentOutOfRangeException($"{nameof(payments)}.{nameof(payments.TotalAmount)} sum cannot be smaller than 0 or greater than {Constants.MaximumNumberOfSatoshis}.");
}
// Get allowed coins to spend.
var availableCoinsView = Coins.Unspent();
List<SmartCoin> allowedSmartCoinInputs = AllowUnconfirmed // Inputs that can be used to build the transaction.
? availableCoinsView.ToList()
: availableCoinsView.Confirmed().ToList();
if (allowedInputs is not null) // If allowedInputs are specified then select the coins from them.
{
if (!allowedInputs.Any())
{
throw new ArgumentException($"{nameof(allowedInputs)} is not null, but empty.");
}
allowedSmartCoinInputs = allowedSmartCoinInputs
.Where(x => allowedInputs.Any(y => y.Hash == x.TransactionId && y.N == x.Index))
.ToList();
// Add those that have the same script, because common ownership is already exposed.
// But only if the user didn't click the "max" button. In this case he'd send more money than what he'd think.
if (payments.ChangeStrategy != ChangeStrategy.AllRemainingCustom)
{
var allScripts = allowedSmartCoinInputs.Select(x => x.ScriptPubKey).ToHashSet();
foreach (var coin in availableCoinsView.Where(x => !allowedSmartCoinInputs.Any(y => x.TransactionId == y.TransactionId && x.Index == y.Index)))
{
if (!(AllowUnconfirmed || coin.Confirmed))
{
continue;
}
if (allScripts.Contains(coin.ScriptPubKey))
{
allowedSmartCoinInputs.Add(coin);
}
}
}
}
// Get and calculate fee
Logger.LogInfo("Calculating dynamic transaction fee...");
TransactionBuilder builder = Network.CreateTransactionBuilder();
builder.SetCoinSelector(new SmartCoinSelector(allowedSmartCoinInputs));
builder.AddCoins(allowedSmartCoinInputs.Select(c => c.Coin));
builder.SetLockTime(lockTimeSelector());
foreach (var request in payments.Requests.Where(x => x.Amount.Type == MoneyRequestType.Value))
{
var amountRequest = request.Amount;
builder.Send(request.Destination, amountRequest.Amount);
if (amountRequest.SubtractFee)
{
builder.SubtractFees();
}
}
HdPubKey? changeHdPubKey;
if (payments.TryGetCustomRequest(out DestinationRequest? custChange))
{
var changeScript = custChange.Destination.ScriptPubKey;
KeyManager.TryGetKeyForScriptPubKey(changeScript, out HdPubKey? hdPubKey);
changeHdPubKey = hdPubKey;
var changeStrategy = payments.ChangeStrategy;
if (changeStrategy == ChangeStrategy.Custom)
{
builder.SetChange(changeScript);
}
else if (changeStrategy == ChangeStrategy.AllRemainingCustom)
{
builder.SendAllRemaining(changeScript);
}
else
{
throw new NotSupportedException(payments.ChangeStrategy.ToString());
}
}
else
{
KeyManager.AssertCleanKeysIndexed(isInternal: true);
KeyManager.AssertLockedInternalKeysIndexed(14);
changeHdPubKey = KeyManager.GetKeys(KeyState.Clean, true).First();
builder.SetChange(changeHdPubKey.P2wpkhScript);
}
builder.OptInRBF = true;
FeeRate feeRate = feeRateFetcher();
builder.SendEstimatedFees(feeRate);
var psbt = builder.BuildPSBT(false);
var spentCoins = psbt.Inputs.Select(txin => allowedSmartCoinInputs.First(y => y.OutPoint == txin.PrevOut)).ToArray();
var realToSend = payments.Requests
.Select(t =>
(label: t.Label,
destination: t.Destination,
amount: psbt.Outputs.FirstOrDefault(o => o.ScriptPubKey == t.Destination.ScriptPubKey)?.Value))
.Where(i => i.amount is not null);
if (!psbt.TryGetFee(out var fee))
{
throw new InvalidOperationException("Impossible to get the fees of the PSBT, this should never happen.");
}
Logger.LogInfo($"Fee: {fee.Satoshi} Satoshi.");
var vSize = builder.EstimateSize(psbt.GetOriginalTransaction(), true);
Logger.LogInfo($"Estimated tx size: {vSize} vBytes.");
// Do some checks
Money totalSendAmountNoFee = realToSend.Sum(x => x.amount);
if (totalSendAmountNoFee == Money.Zero)
{
throw new InvalidOperationException("The amount after subtracting the fee is too small to be sent.");
}
Money totalOutgoingAmountNoFee;
if (changeHdPubKey is null)
{
totalOutgoingAmountNoFee = totalSendAmountNoFee;
}
else
{
totalOutgoingAmountNoFee = realToSend.Where(x => !changeHdPubKey.ContainsScript(x.destination.ScriptPubKey)).Sum(x => x.amount);
}
decimal totalOutgoingAmountNoFeeDecimal = totalOutgoingAmountNoFee.ToDecimal(MoneyUnit.BTC);
// Cannot divide by zero, so use the closest number we have to zero.
decimal totalOutgoingAmountNoFeeDecimalDivisor = totalOutgoingAmountNoFeeDecimal == 0 ? decimal.MinValue : totalOutgoingAmountNoFeeDecimal;
decimal feePc = 100 * fee.ToDecimal(MoneyUnit.BTC) / totalOutgoingAmountNoFeeDecimalDivisor;
if (feePc > 1)
{
Logger.LogInfo($"The transaction fee is {feePc:0.#}% of the sent amount.{Environment.NewLine}"
+ $"Sending:\t {totalOutgoingAmountNoFee.ToString(fplus: false, trimExcessZero: true)} BTC.{Environment.NewLine}"
+ $"Fee:\t\t {fee.Satoshi} Satoshi.");
}
if (feePc > 100)
{
throw new InvalidOperationException($"The transaction fee is more than the sent amount: {feePc:0.#}%.");
}
if (spentCoins.Any(u => !u.Confirmed))
{
Logger.LogInfo("Unconfirmed transaction is spent.");
}
// Build the transaction
Logger.LogInfo("Signing transaction...");
// It must be watch only, too, because if we have the key and also hardware wallet, we do not care we can sign.
psbt.AddKeyPaths(KeyManager);
psbt.AddPrevTxs(TransactionStore);
Transaction tx;
if (KeyManager.IsWatchOnly)
{
tx = psbt.GetGlobalTransaction();
}
else
{
IEnumerable<ExtKey> signingKeys = KeyManager.GetSecrets(Password, spentCoins.Select(x => x.ScriptPubKey).ToArray());
builder = builder.AddKeys(signingKeys.ToArray());
builder.SignPSBT(psbt);
var isPayjoin = false;
// Try to pay using payjoin
if (payjoinClient is not null)
{
psbt = TryNegotiatePayjoin(payjoinClient, builder, psbt, changeHdPubKey);
isPayjoin = true;
psbt.AddKeyPaths(KeyManager);
psbt.AddPrevTxs(TransactionStore);
}
psbt.Finalize();
tx = psbt.ExtractTransaction();
var checkResults = builder.Check(tx).ToList();
if (!psbt.TryGetEstimatedFeeRate(out var actualFeeRate))
{
throw new InvalidOperationException("Impossible to get the fee rate of the PSBT, this should never happen.");
}
if (!isPayjoin)
{
// Manually check the feerate, because some inaccuracy is possible.
var sb1 = feeRate.SatoshiPerByte;
var sb2 = actualFeeRate.SatoshiPerByte;
if (Math.Abs(sb1 - sb2) > 2) // 2s/b inaccuracy ok.
{
// So it'll generate a transactionpolicy error thrown below.
checkResults.Add(new NotEnoughFundsPolicyError("Fees different than expected"));
}
}
if (checkResults.Count > 0)
{
throw new InvalidTxException(tx, checkResults);
}
}
var smartTransaction = new SmartTransaction(tx, Height.Unknown, label: SmartLabel.Merge(payments.Requests.Select(x => x.Label)));
foreach (var coin in spentCoins)
{
smartTransaction.WalletInputs.Add(coin);
}
var label = SmartLabel.Merge(payments.Requests.Select(x => x.Label).Concat(smartTransaction.WalletInputs.Select(x => x.HdPubKey.Label)));
for (var i = 0U; i < tx.Outputs.Count; i++)
{
TxOut output = tx.Outputs[i];
if (KeyManager.TryGetKeyForScriptPubKey(output.ScriptPubKey, out HdPubKey? foundKey))
{
var smartCoin = new SmartCoin(smartTransaction, i, foundKey);
label = SmartLabel.Merge(label, smartCoin.HdPubKey.Label); // foundKey's label is already added to the coinlabel.
smartTransaction.WalletOutputs.Add(smartCoin);
}
}
foreach (var coin in smartTransaction.WalletOutputs)
{
var foundPaymentRequest = payments.Requests.FirstOrDefault(x => x.Destination.ScriptPubKey == coin.ScriptPubKey);
// If change then we concatenate all the labels.
// The foundkeylabel has already been added previously, so no need to concatenate.
if (foundPaymentRequest is null) // Then it's autochange.
{
coin.HdPubKey.SetLabel(label);
}
else
{
coin.HdPubKey.SetLabel(SmartLabel.Merge(coin.HdPubKey.Label, foundPaymentRequest.Label));
}
}
Logger.LogInfo($"Transaction is successfully built: {tx.GetHash()}.");
var sign = !KeyManager.IsWatchOnly;
return new BuildTransactionResult(smartTransaction, psbt, sign, fee, feePc);
}
private PSBT TryNegotiatePayjoin(IPayjoinClient payjoinClient, TransactionBuilder builder, PSBT psbt, HdPubKey changeHdPubKey)
{
try
{
Logger.LogInfo($"Negotiating payjoin payment with `{payjoinClient.PaymentUrl}`.");
psbt = payjoinClient.RequestPayjoin(
psbt,
KeyManager.ExtPubKey,
new RootedKeyPath(KeyManager.MasterFingerprint.Value, KeyManager.AccountKeyPath),
changeHdPubKey,
CancellationToken.None).GetAwaiter().GetResult(); // WTF??!
builder.SignPSBT(psbt);
Logger.LogInfo($"Payjoin payment was negotiated successfully.");
}
catch (HttpRequestException ex) when (ex.InnerException is TorConnectCommandFailedException innerEx)
{
if (innerEx.Message.Contains("HostUnreachable"))
{
Logger.LogWarning($"Payjoin server is not reachable. Ignoring...");
}
// Ignore.
}
catch (HttpRequestException e)
{
Logger.LogWarning($"Payjoin server responded with {e.ToTypeMessageString()}. Ignoring...");
}
catch (PayjoinException e)
{
Logger.LogWarning($"Payjoin server responded with {e.Message}. Ignoring...");
}
return psbt;
}
}
}
| 34.86 | 178 | 0.714941 | [
"MIT"
] | Happyfani/WalletWasabi | WalletWasabi/Blockchain/Transactions/TransactionFactory.cs | 12,201 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureAD.Outputs
{
[OutputType]
public sealed class ApplicationOptionalClaimsAccessToken
{
/// <summary>
/// List of additional properties of the claim. If a property exists in this list, it modifies the behaviour of the optional claim.
/// </summary>
public readonly ImmutableArray<string> AdditionalProperties;
/// <summary>
/// Whether the claim specified by the client is necessary to ensure a smooth authorization experience.
/// </summary>
public readonly bool? Essential;
/// <summary>
/// The name of the optional claim.
/// </summary>
public readonly string Name;
/// <summary>
/// The source of the claim. If `source` is absent, the claim is a predefined optional claim. If `source` is `user`, the value of `name` is the extension property from the user object.
/// </summary>
public readonly string? Source;
[OutputConstructor]
private ApplicationOptionalClaimsAccessToken(
ImmutableArray<string> additionalProperties,
bool? essential,
string name,
string? source)
{
AdditionalProperties = additionalProperties;
Essential = essential;
Name = name;
Source = source;
}
}
}
| 33.8 | 192 | 0.637278 | [
"ECL-2.0",
"Apache-2.0"
] | AaronFriel/pulumi-azuread | sdk/dotnet/Outputs/ApplicationOptionalClaimsAccessToken.cs | 1,690 | C# |
namespace DotNetToolkit.Wpf.Commands
{
using Common;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Input;
/// <summary>
/// An asynchronous command whose sole purpose is to relay its functionality to other objects by invoking delegates. The default return value for the CanExecute method is 'true'.
/// This class does not allow you to accept command parameters in the Execute and CanExecute callback methods.
/// </summary>
public class RelayCommandAsync : IAsyncCommand
{
#region Fields
private bool _isExecuting;
private readonly Func<Task> _execute;
private readonly Predicate<object> _canExecute;
private readonly IErrorHandler _errorHandler;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="RelayCommand" /> class.
/// </summary>
/// <param name="execute">The execute.</param>
/// <param name="canExecute">The can execute.</param>
/// <param name="errorHandler">The error handler for the asynchronous command.</param>
/// <exception cref="ArgumentNullException">execute</exception>
public RelayCommandAsync(Func<Task> execute, Predicate<object> canExecute = null, IErrorHandler errorHandler = null)
{
if (execute == null)
throw new ArgumentNullException(nameof(execute));
_execute = execute;
_canExecute = canExecute;
_errorHandler = errorHandler;
}
#endregion
#region ICommand Members
/// <summary>
/// Defines the method that determines whether the command can execute in its current state.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
/// <returns>
/// true if this command can be executed; otherwise, false.
/// </returns>
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return !_isExecuting && (_canExecute == null ? true : _canExecute(parameter));
}
/// <summary>
/// Occurs when changes occur that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
void ICommand.Execute(object parameter)
{
ExecuteAsync(parameter).FireAndForgetSafeAsync(_errorHandler);
}
#endregion
#region Implementations of IAsyncCommand
/// <summary>
/// Asynchronously defines the method to be called when the command is invoked.
/// </summary>
/// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
public async Task ExecuteAsync(object parameter)
{
if (CanExecute(parameter) && _execute != null)
{
try
{
_isExecuting = true;
await _execute();
}
finally
{
_isExecuting = false;
}
}
}
#endregion
#region Public Methods
/// <summary>
/// Raises the <see cref="CanExecuteChanged"/> event to indicate that the return value of the <see cref="CanExecute"/>
/// method has changed.
/// </summary>
public void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
#endregion
}
}
| 35.381356 | 182 | 0.596647 | [
"MIT"
] | johelvisguzman/DotNetToolkit.Wpf | src/DotNetToolkit.Wpf/Commands/RelayCommandAsync.cs | 4,177 | C# |
//-----------------------------------------------------------------------
// Copyright 2014 Tobii Technology AB. All rights reserved.
//-----------------------------------------------------------------------
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
using Tobii.GameIntegration;
using Tobii.GameIntegration.Net;
using UnityEngine;
using Vector3 = UnityEngine.Vector3;
namespace Tobii.Gaming.Internal
{
/// <summary>
/// Provider of head pose data. When the provider has been started it
/// will continuously update the Last property with the latest gaze point
/// value received from Tobii Engine.
/// </summary>
internal class HeadPoseDataProvider : DataProviderBase<HeadPose>
{
/// <summary>
/// Creates a new instance.
/// Note: don't create instances of this class directly. Use the <see cref="TobiiHost.GetGazePointDataProvider"/> method instead.
/// </summary>
public HeadPoseDataProvider()
{
Last = HeadPose.Invalid;
}
protected override void UpdateData()
{
var headPoses = TobiiGameIntegrationApi.GetHeadPoses();
foreach (var headPose in headPoses)
{
OnHeadPose(headPose);
}
}
private void OnHeadPose(Tobii.GameIntegration.Net.HeadPose headPose)
{
long eyetrackerCurrentUs = headPose.TimeStampMicroSeconds; // TODO awaiting new API from tgi
float timeStampUnityUnscaled = Time.unscaledTime - ((eyetrackerCurrentUs - headPose.TimeStampMicroSeconds) / 1000000f);
var rotation = Quaternion.Euler(-headPose.Rotation.Pitch * Mathf.Rad2Deg,
headPose.Rotation.Yaw * Mathf.Rad2Deg,
-headPose.Rotation.Roll * Mathf.Rad2Deg);
Last = new HeadPose(
new Vector3(headPose.Position.X, headPose.Position.Y, headPose.Position.Z),
rotation,
timeStampUnityUnscaled, headPose.TimeStampMicroSeconds);
}
}
}
#endif
| 33.654545 | 132 | 0.661804 | [
"MIT"
] | OccularFlow/Eye-Tracking-2D | Assets/Tobii/Framework/Internal/HeadPoseDataProvider.cs | 1,853 | C# |
// 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.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static class GeneratedNames
{
private const char IdSeparator = '_';
private const char GenerationSeparator = '#';
internal static bool IsGeneratedMemberName(string memberName)
{
return memberName.Length > 0 && memberName[0] == '<';
}
internal static string MakeBackingFieldName(string propertyName)
{
Debug.Assert((char)GeneratedNameKind.AutoPropertyBackingField == 'k');
return "<" + propertyName + ">k__BackingField";
}
internal static string MakeIteratorFinallyMethodName(int iteratorState)
{
// we can pick any name, but we will try to do
// <>m__Finally1
// <>m__Finally2
// <>m__Finally3
// . . .
// that will roughly match native naming scheme and may also be easier when need to debug.
Debug.Assert((char)GeneratedNameKind.IteratorFinallyMethod == 'm');
return "<>m__Finally" + StringExtensions.GetNumeral(Math.Abs(iteratorState + 2));
}
internal static string MakeStaticLambdaDisplayClassName(int methodOrdinal, int generation)
{
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation);
}
internal static string MakeLambdaDisplayClassName(int methodOrdinal, int generation, int closureOrdinal, int closureGeneration)
{
// -1 for singleton static lambdas
Debug.Assert(closureOrdinal >= -1);
Debug.Assert(methodOrdinal >= 0);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaDisplayClass, methodOrdinal, generation, suffix: "DisplayClass", entityOrdinal: closureOrdinal, entityGeneration: closureGeneration);
}
internal static string MakeAnonymousTypeTemplateName(int index, int submissionSlotIndex, string moduleId)
{
var name = "<" + moduleId + ">f__AnonymousType" + StringExtensions.GetNumeral(index);
if (submissionSlotIndex >= 0)
{
name += "#" + StringExtensions.GetNumeral(submissionSlotIndex);
}
return name;
}
internal static string MakeAnonymousTypeBackingFieldName(string propertyName)
{
return "<" + propertyName + ">i__Field";
}
internal static string MakeAnonymousTypeParameterName(string propertyName)
{
return "<" + propertyName + ">j__TPar";
}
internal static string MakeStateMachineTypeName(string methodName, int methodOrdinal, int generation)
{
Debug.Assert(generation >= 0);
Debug.Assert(methodOrdinal >= -1);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.StateMachineType, methodOrdinal, generation, methodName);
}
internal static string MakeBaseMethodWrapperName(int uniqueId)
{
Debug.Assert((char)GeneratedNameKind.BaseMethodWrapper == 'n');
return "<>n__" + StringExtensions.GetNumeral(uniqueId);
}
internal static string MakeLambdaMethodName(string methodName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(methodGeneration >= 0);
Debug.Assert(lambdaOrdinal >= 0);
Debug.Assert(lambdaGeneration >= 0);
// The EE displays the containing method name and unique id in the stack trace,
// and uses it to find the original binding context.
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaMethod, methodOrdinal, methodGeneration, methodName, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration);
}
internal static string MakeLambdaCacheFieldName(int methodOrdinal, int generation, int lambdaOrdinal, int lambdaGeneration)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(lambdaOrdinal >= 0);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LambdaCacheField, methodOrdinal, generation, entityOrdinal: lambdaOrdinal, entityGeneration: lambdaGeneration);
}
internal static string MakeLocalFunctionName(string methodName, string localFunctionName, int methodOrdinal, int methodGeneration, int lambdaOrdinal, int lambdaGeneration)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(methodGeneration >= 0);
Debug.Assert(lambdaOrdinal >= 0);
Debug.Assert(lambdaGeneration >= 0);
return MakeMethodScopedSynthesizedName(GeneratedNameKind.LocalFunction, methodOrdinal, methodGeneration, methodName, localFunctionName, GeneratedNameConstants.LocalFunctionNameTerminator, lambdaOrdinal, lambdaGeneration);
}
private static string MakeMethodScopedSynthesizedName(
GeneratedNameKind kind,
int methodOrdinal,
int methodGeneration,
string? methodName = null,
string? suffix = null,
char suffixTerminator = default,
int entityOrdinal = -1,
int entityGeneration = -1)
{
Debug.Assert(methodOrdinal >= -1);
Debug.Assert(methodGeneration >= 0 || methodGeneration == -1 && methodOrdinal == -1);
Debug.Assert(entityOrdinal >= -1);
Debug.Assert(entityGeneration >= 0 || entityGeneration == -1 && entityOrdinal == -1);
Debug.Assert(entityGeneration == -1 || entityGeneration >= methodGeneration);
var result = PooledStringBuilder.GetInstance();
var builder = result.Builder;
builder.Append('<');
if (methodName != null)
{
builder.Append(methodName);
// CLR generally allows names with dots, however some APIs like IMetaDataImport
// can only return full type names combined with namespaces.
// see: http://msdn.microsoft.com/en-us/library/ms230143.aspx (IMetaDataImport::GetTypeDefProps)
// When working with such APIs, names with dots become ambiguous since metadata
// consumer cannot figure where namespace ends and actual type name starts.
// Therefore it is a good practice to avoid type names with dots.
// As a replacement use a character not allowed in C# identifier to avoid conflicts.
if (kind.IsTypeName())
{
builder.Replace('.', GeneratedNameConstants.DotReplacementInTypeNames);
}
}
builder.Append('>');
builder.Append((char)kind);
if (suffix != null || methodOrdinal >= 0 || entityOrdinal >= 0)
{
builder.Append(GeneratedNameConstants.SuffixSeparator);
builder.Append(suffix);
if (suffixTerminator != default)
{
builder.Append(suffixTerminator);
}
if (methodOrdinal >= 0)
{
builder.Append(methodOrdinal);
AppendOptionalGeneration(builder, methodGeneration);
}
if (entityOrdinal >= 0)
{
if (methodOrdinal >= 0)
{
builder.Append(IdSeparator);
}
builder.Append(entityOrdinal);
AppendOptionalGeneration(builder, entityGeneration);
}
}
return result.ToStringAndFree();
}
private static void AppendOptionalGeneration(StringBuilder builder, int generation)
{
if (generation > 0)
{
builder.Append(GenerationSeparator);
builder.Append(generation);
}
}
internal static string MakeHoistedLocalFieldName(SynthesizedLocalKind kind, int slotIndex, string? localName = null)
{
Debug.Assert((localName != null) == (kind == SynthesizedLocalKind.UserDefined));
Debug.Assert(slotIndex >= 0);
Debug.Assert(kind.IsLongLived());
// Lambda display class local follows a different naming pattern.
// EE depends on the name format.
// There's logic in the EE to recognize locals that have been captured by a lambda
// and would have been hoisted for the state machine. Basically, we just hoist the local containing
// the instance of the lambda display class and retain its original name (rather than using an
// iterator local name). See FUNCBRECEE::ImportIteratorMethodInheritedLocals.
var result = PooledStringBuilder.GetInstance();
var builder = result.Builder;
builder.Append('<');
if (localName != null)
{
Debug.Assert(localName.IndexOf('.') == -1);
builder.Append(localName);
}
builder.Append('>');
if (kind == SynthesizedLocalKind.LambdaDisplayClass)
{
builder.Append((char)GeneratedNameKind.DisplayClassLocalOrField);
}
else if (kind == SynthesizedLocalKind.UserDefined)
{
builder.Append((char)GeneratedNameKind.HoistedLocalField);
}
else
{
builder.Append((char)GeneratedNameKind.HoistedSynthesizedLocalField);
}
builder.Append("__");
builder.Append(slotIndex + 1);
return result.ToStringAndFree();
}
internal static string AsyncAwaiterFieldName(int slotIndex)
{
Debug.Assert((char)GeneratedNameKind.AwaiterField == 'u');
return "<>u__" + StringExtensions.GetNumeral(slotIndex + 1);
}
internal static string MakeCachedFrameInstanceFieldName()
{
Debug.Assert((char)GeneratedNameKind.LambdaCacheField == '9');
return "<>9";
}
internal static string? MakeSynthesizedLocalName(SynthesizedLocalKind kind, ref int uniqueId)
{
Debug.Assert(kind.IsLongLived());
// Lambda display class local has to be named. EE depends on the name format.
if (kind == SynthesizedLocalKind.LambdaDisplayClass)
{
return MakeLambdaDisplayLocalName(uniqueId++);
}
return null;
}
internal static string MakeSynthesizedInstrumentationPayloadLocalFieldName(int uniqueId)
{
return GeneratedNameConstants.SynthesizedLocalNamePrefix + "InstrumentationPayload" + StringExtensions.GetNumeral(uniqueId);
}
internal static string MakeLambdaDisplayLocalName(int uniqueId)
{
Debug.Assert((char)GeneratedNameKind.DisplayClassLocalOrField == '8');
return GeneratedNameConstants.SynthesizedLocalNamePrefix + "<>8__locals" + StringExtensions.GetNumeral(uniqueId);
}
internal static string MakeFixedFieldImplementationName(string fieldName)
{
// the native compiler adds numeric digits at the end. Roslyn does not.
Debug.Assert((char)GeneratedNameKind.FixedBufferField == 'e');
return "<" + fieldName + ">e__FixedBuffer";
}
internal static string MakeStateMachineStateFieldName()
{
// Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name.
Debug.Assert((char)GeneratedNameKind.StateMachineStateField == '1');
return "<>1__state";
}
internal static string MakeAsyncIteratorPromiseOfValueOrEndFieldName()
{
Debug.Assert((char)GeneratedNameKind.AsyncIteratorPromiseOfValueOrEndBackingField == 'v');
return "<>v__promiseOfValueOrEnd";
}
internal static string MakeAsyncIteratorCombinedTokensFieldName()
{
Debug.Assert((char)GeneratedNameKind.CombinedTokensField == 'x');
return "<>x__combinedTokens";
}
internal static string MakeIteratorCurrentFieldName()
{
Debug.Assert((char)GeneratedNameKind.IteratorCurrentBackingField == '2');
return "<>2__current";
}
internal static string MakeDisposeModeFieldName()
{
Debug.Assert((char)GeneratedNameKind.DisposeModeField == 'w');
return "<>w__disposeMode";
}
internal static string MakeIteratorCurrentThreadIdFieldName()
{
Debug.Assert((char)GeneratedNameKind.IteratorCurrentThreadIdField == 'l');
return "<>l__initialThreadId";
}
internal static string ThisProxyFieldName()
{
Debug.Assert((char)GeneratedNameKind.ThisProxyField == '4');
return "<>4__this";
}
internal static string StateMachineThisParameterProxyName()
{
return StateMachineParameterProxyFieldName(ThisProxyFieldName());
}
internal static string StateMachineParameterProxyFieldName(string parameterName)
{
Debug.Assert((char)GeneratedNameKind.StateMachineParameterProxyField == '3');
return "<>3__" + parameterName;
}
internal static string MakeDynamicCallSiteContainerName(int methodOrdinal, int localFunctionOrdinal, int generation)
{
return MakeMethodScopedSynthesizedName(GeneratedNameKind.DynamicCallSiteContainerType, methodOrdinal, generation,
suffix: localFunctionOrdinal != -1 ? localFunctionOrdinal.ToString() : null,
suffixTerminator: localFunctionOrdinal != -1 ? '_' : default);
}
internal static string MakeDynamicCallSiteFieldName(int uniqueId)
{
Debug.Assert((char)GeneratedNameKind.DynamicCallSiteField == 'p');
return "<>p__" + StringExtensions.GetNumeral(uniqueId);
}
/// <summary>
/// Produces name of the synthesized delegate symbol that encodes the parameter byref-ness and return type of the delegate.
/// The arity is appended via `N suffix in MetadataName calculation since the delegate is generic.
/// </summary>
internal static string MakeDynamicCallSiteDelegateName(RefKindVector byRefs, bool returnsVoid, int generation)
{
var pooledBuilder = PooledStringBuilder.GetInstance();
var builder = pooledBuilder.Builder;
builder.Append(returnsVoid ? "<>A" : "<>F");
if (!byRefs.IsNull)
{
builder.Append("{");
int i = 0;
foreach (int byRefIndex in byRefs.Words())
{
if (i > 0)
{
builder.Append(",");
}
builder.AppendFormat("{0:x8}", byRefIndex);
i++;
}
builder.Append("}");
Debug.Assert(i > 0);
}
AppendOptionalGeneration(builder, generation);
return pooledBuilder.ToStringAndFree();
}
internal static string AsyncBuilderFieldName()
{
// Microsoft.VisualStudio.VIL.VisualStudioHost.AsyncReturnStackFrame depends on this name.
Debug.Assert((char)GeneratedNameKind.AsyncBuilderField == 't');
return "<>t__builder";
}
internal static string ReusableHoistedLocalFieldName(int number)
{
Debug.Assert((char)GeneratedNameKind.ReusableHoistedLocalField == '7');
return "<>7__wrap" + StringExtensions.GetNumeral(number);
}
internal static string LambdaCopyParameterName(int ordinal)
{
return "<p" + StringExtensions.GetNumeral(ordinal) + ">";
}
}
}
| 40.793612 | 233 | 0.610492 | [
"MIT"
] | Blokyk/roslyn | src/Compilers/CSharp/Portable/Symbols/Synthesized/GeneratedNames.cs | 16,605 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Web;
using GoCardlessSdk.Helpers;
using System.Security.Cryptography;
namespace GoCardlessSdk.WebHooks
{
class SignatureValidator
{
public string GetSignature(string key, JObject content)
{
var payload = content["payload"];
var tuples = Flatten(null, payload);
tuples.Sort();
StringBuilder result = new StringBuilder();
var values = new List<string>();
foreach (var tuple in tuples)
{
var encoded = PercentEncode(tuple);
values.Add(string.Format("{0}={1}", encoded.Key, encoded.Value));
}
string digest = String.Join("&", values.ToArray());
Byte[] keyBytes = Encoding.UTF8.GetBytes(key);
Byte[] paramsBytes = Encoding.UTF8.GetBytes(digest);
Byte[] hashedBytes = new HMACSHA256(keyBytes).ComputeHash(paramsBytes);
return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
}
public StringTuple PercentEncode(StringTuple tuple)
{
return new StringTuple(Utils.PercentEncode(tuple.Key), Utils.PercentEncode(tuple.Value));
}
public List<StringTuple> Flatten(string keyFormatString, JToken token)
{
keyFormatString = keyFormatString == null ? "" : keyFormatString;
List<StringTuple> result = new List<StringTuple>();
switch (token.Type)
{
case JTokenType.Property:
JProperty property = token as JProperty;
keyFormatString = string.Format(keyFormatString, property.Name);
break;
case JTokenType.Array:
keyFormatString += "[]";
break;
case JTokenType.Object:
keyFormatString += keyFormatString == string.Empty ? "{0}" : "[{0}]";
break;
default:
JValue value = token as JValue;
// TODO - we should remove the signature before calling this method,
// But LINQ to JSON structures appear immutable.
if (keyFormatString != "signature")
{
string val;
// TODO - it would be nice if we could just turn off JSON.net's type conversion and work with strings.
if (value.Type == JTokenType.Date)
{
val = value.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
else
{
val = value.ToString();
}
result.Add(new StringTuple(keyFormatString, val));
}
break;
}
foreach (var childToken in token)
{
result.AddRange(Flatten(keyFormatString, childToken));
}
return result;
}
}
class StringTuple : IComparable<StringTuple>
{
public string Key { get; private set; }
public string Value { get; private set; }
public StringTuple(string key, string value)
{
this.Key = key;
this.Value = value;
}
public int CompareTo(StringTuple other)
{
var delta = this.Key.CompareTo(other.Key);
return delta == 0 ? this.Value.CompareTo(other.Value) : delta;
}
}
}
| 34.509091 | 127 | 0.503425 | [
"MIT"
] | ChrisG5/gocardless-dotnet | GoCardlessSdk/WebHooks/SignatureValidator.cs | 3,798 | C# |
//extern alias tpx;
namespace Test.Radical
{
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Topics.Radical;
[TestClass()]
public class EnumItemDescriptionAttributeTest
{
private TestContext testContextInstance;
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
protected virtual EnumItemDescriptionAttribute CreateMock( String caption )
{
return new EnumItemDescriptionAttribute( caption );
}
protected virtual EnumItemDescriptionAttribute CreateMock( String caption, Int32 index )
{
return new EnumItemDescriptionAttribute( caption, index );
}
[TestMethod()]
public void EnumItemDescriptionAttribute_ctor_caption()
{
String caption = "fake caption";
EnumItemDescriptionAttribute target = this.CreateMock( caption );
Assert.IsNotNull( target );
}
[TestMethod()]
public void EnumItemDescriptionAttribute_ctor_caption_index()
{
String caption = "fake caption";
Int32 index = 0;
EnumItemDescriptionAttribute target = this.CreateMock( caption, index );
Assert.IsNotNull( target );
}
[TestMethod()]
public void EnumItemDescriptionAttribute_caption()
{
String caption = "fake caption";
EnumItemDescriptionAttribute target = this.CreateMock( caption );
Assert.AreEqual<String>( caption, target.Caption );
}
[TestMethod()]
public void EnumItemDescriptionAttribute_valid_caption()
{
String expectedCaption = "fake caption";
Int32 expectedIndex = 0;
EnumItemDescriptionAttribute target = this.CreateMock( expectedCaption, expectedIndex );
Assert.AreEqual<String>( expectedCaption, target.Caption );
}
[TestMethod()]
public void EnumItemDescriptionAttribute_valid_index()
{
String expectedcaption = "fake caption";
Int32 expectedIndex = 0;
EnumItemDescriptionAttribute target = this.CreateMock( expectedcaption, expectedIndex );
Assert.AreEqual<Int32>( expectedIndex, target.Index );
}
[TestMethod()]
public void EnumItemDescriptionAttribute_Index()
{
EnumItemDescriptionAttribute target = this.CreateMock( "fake caption" );
Int32 actual = target.Index;
Assert.AreEqual<Int32>( -1, actual );
}
[TestMethod()]
[ExpectedException( typeof( ArgumentNullException ) )]
public void EnumItemDescriptionAttribute_ctor_null_caption()
{
EnumItemDescriptionAttribute target = this.CreateMock( null );
}
}
}
| 24.455446 | 91 | 0.739676 | [
"MIT"
] | pdeligia/nekara-artifact | TSVD/Radical/src/net35/Test.Radical/EnumItemDescriptionAttributeTest.cs | 2,472 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
namespace Discord.Commands
{
public class UserTypeReader<T> : TypeReader
where T : class, IUser
{
public override async Task<TypeReaderResult> ReadAsync(ICommandContext context, string input, IServiceProvider services)
{
var results = new Dictionary<ulong, TypeReaderValue>();
IAsyncEnumerable<IUser> channelUsers = context.Channel.GetUsersAsync(CacheMode.CacheOnly).Flatten(); // it's better
IReadOnlyCollection<IGuildUser> guildUsers = ImmutableArray.Create<IGuildUser>();
ulong id;
if (context.Guild != null)
guildUsers = await context.Guild.GetUsersAsync(CacheMode.CacheOnly).ConfigureAwait(false);
//By Mention (1.0)
if (MentionUtils.TryParseUser(input, out id))
{
if (context.Guild != null)
AddResult(results, await context.Guild.GetUserAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T, 1.00f);
else
AddResult(results, await context.Channel.GetUserAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T, 1.00f);
}
//By Id (0.9)
if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
{
if (context.Guild != null)
AddResult(results, await context.Guild.GetUserAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T, 0.90f);
else
AddResult(results, await context.Channel.GetUserAsync(id, CacheMode.CacheOnly).ConfigureAwait(false) as T, 0.90f);
}
//By Username + Discriminator (0.7-0.85)
int index = input.LastIndexOf('#');
if (index >= 0)
{
string username = input.Substring(0, index);
if (ushort.TryParse(input.Substring(index + 1), out ushort discriminator))
{
var channelUser = await channelUsers.FirstOrDefault(x => x.DiscriminatorValue == discriminator &&
string.Equals(username, x.Username, StringComparison.OrdinalIgnoreCase));
AddResult(results, channelUser as T, channelUser?.Username == username ? 0.85f : 0.75f);
var guildUser = guildUsers.FirstOrDefault(x => x.DiscriminatorValue == discriminator &&
string.Equals(username, x.Username, StringComparison.OrdinalIgnoreCase));
AddResult(results, guildUser as T, guildUser?.Username == username ? 0.80f : 0.70f);
}
}
//By Username (0.5-0.6)
{
await channelUsers
.Where(x => string.Equals(input, x.Username, StringComparison.OrdinalIgnoreCase))
.ForEachAsync(channelUser => AddResult(results, channelUser as T, channelUser.Username == input ? 0.65f : 0.55f));
foreach (var guildUser in guildUsers.Where(x => string.Equals(input, x.Username, StringComparison.OrdinalIgnoreCase)))
AddResult(results, guildUser as T, guildUser.Username == input ? 0.60f : 0.50f);
}
//By Nickname (0.5-0.6)
{
await channelUsers
.Where(x => string.Equals(input, (x as IGuildUser)?.Nickname, StringComparison.OrdinalIgnoreCase))
.ForEachAsync(channelUser => AddResult(results, channelUser as T, (channelUser as IGuildUser).Nickname == input ? 0.65f : 0.55f));
foreach (var guildUser in guildUsers.Where(x => string.Equals(input, x.Nickname, StringComparison.OrdinalIgnoreCase)))
AddResult(results, guildUser as T, guildUser.Nickname == input ? 0.60f : 0.50f);
}
if (results.Count > 0)
return TypeReaderResult.FromSuccess(results.Values.ToImmutableArray());
return TypeReaderResult.FromError(CommandError.ObjectNotFound, "User not found.");
}
private void AddResult(Dictionary<ulong, TypeReaderValue> results, T user, float score)
{
if (user != null && !results.ContainsKey(user.Id))
results.Add(user.Id, new TypeReaderValue(user, score));
}
}
}
| 49.733333 | 150 | 0.6021 | [
"MIT"
] | patrykr5/Discord.Net | src/Discord.Net.Commands/Readers/UserTypeReader.cs | 4,476 | C# |
namespace Studio.Persistence.Configurations
{
using Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
{
public void Configure(EntityTypeBuilder<Employee> builder)
{
builder.HasKey(c => c.Id);
builder.Property(c => c.FirstName)
.HasMaxLength(50)
.IsUnicode()
.IsRequired();
builder.Property(c => c.LastName)
.HasMaxLength(50)
.IsUnicode()
.IsRequired();
builder.HasOne(e => e.Location)
.WithMany(l => l.Employees)
.HasForeignKey(e => e.LocationId);
}
}
}
| 28.896552 | 75 | 0.545346 | [
"MIT"
] | VeselinBPavlov/studioto.bg | Src/Infrastructure/Studio.Persistence/Configurations/EmployeeConfiguration.cs | 840 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the dataexchange-2017-07-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using Amazon.Runtime;
namespace Amazon.DataExchange.Model
{
/// <summary>
/// Base class for ListEventActions paginators.
/// </summary>
internal sealed partial class ListEventActionsPaginator : IPaginator<ListEventActionsResponse>, IListEventActionsPaginator
{
private readonly IAmazonDataExchange _client;
private readonly ListEventActionsRequest _request;
private int _isPaginatorInUse = 0;
/// <summary>
/// Enumerable containing all full responses for the operation
/// </summary>
public IPaginatedEnumerable<ListEventActionsResponse> Responses => new PaginatedResponse<ListEventActionsResponse>(this);
/// <summary>
/// Enumerable containing all of the EventActions
/// </summary>
public IPaginatedEnumerable<EventActionEntry> EventActions =>
new PaginatedResultKeyResponse<ListEventActionsResponse, EventActionEntry>(this, (i) => i.EventActions);
internal ListEventActionsPaginator(IAmazonDataExchange client, ListEventActionsRequest request)
{
this._client = client;
this._request = request;
}
#if BCL
IEnumerable<ListEventActionsResponse> IPaginator<ListEventActionsResponse>.Paginate()
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListEventActionsResponse response;
do
{
_request.NextToken = nextToken;
response = _client.ListEventActions(_request);
nextToken = response.NextToken;
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
#if AWS_ASYNC_ENUMERABLES_API
async IAsyncEnumerable<ListEventActionsResponse> IPaginator<ListEventActionsResponse>.PaginateAsync(CancellationToken cancellationToken = default)
{
if (Interlocked.Exchange(ref _isPaginatorInUse, 1) != 0)
{
throw new System.InvalidOperationException("Paginator has already been consumed and cannot be reused. Please create a new instance.");
}
PaginatorUtils.SetUserAgentAdditionOnRequest(_request);
var nextToken = _request.NextToken;
ListEventActionsResponse response;
do
{
_request.NextToken = nextToken;
response = await _client.ListEventActionsAsync(_request, cancellationToken).ConfigureAwait(false);
nextToken = response.NextToken;
cancellationToken.ThrowIfCancellationRequested();
yield return response;
}
while (!string.IsNullOrEmpty(nextToken));
}
#endif
}
} | 40.278351 | 154 | 0.669056 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/DataExchange/Generated/Model/_bcl45+netstandard/ListEventActionsPaginator.cs | 3,907 | C# |
using Ch0nkEngine.Data.Basic;
namespace Ch0nkEngine.Data.Data.BoundingShapes
{
public abstract class BoundingShape
{
public abstract bool Intersects(BoundingShape boundingShape);
public abstract bool Encloses(BoundingShape boundingShape);
}
}
| 22.833333 | 69 | 0.748175 | [
"Unlicense"
] | catdawg/Ch0nkEngine | dev/Ch0nkEngine/Ch0nkEngine.Data/Data/BoundingShapes/BoundingShape.cs | 276 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the qldb-2019-01-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.QLDB.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.QLDB.Model.Internal.MarshallTransformations
{
/// <summary>
/// UntagResource Request Marshaller
/// </summary>
public class UntagResourceRequestMarshaller : IMarshaller<IRequest, UntagResourceRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((UntagResourceRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(UntagResourceRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.QLDB");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-01-02";
request.HttpMethod = "DELETE";
if (!publicRequest.IsSetResourceArn())
throw new AmazonQLDBException("Request object does not have required field ResourceArn set");
request.AddPathResource("{resourceArn}", StringUtils.FromString(publicRequest.ResourceArn));
if (publicRequest.IsSetTagKeys())
request.ParameterCollection.Add("tagKeys", publicRequest.TagKeys);
request.ResourcePath = "/tags/{resourceArn}";
request.MarshallerVersion = 2;
request.UseQueryString = true;
return request;
}
private static UntagResourceRequestMarshaller _instance = new UntagResourceRequestMarshaller();
internal static UntagResourceRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static UntagResourceRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.869565 | 142 | 0.631212 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/QLDB/Generated/Model/Internal/MarshallTransformations/UntagResourceRequestMarshaller.cs | 3,300 | C# |
using System.Threading;
using SmartAdmin.Domain.Models;
using URF.Core.Abstractions.Trackable;
using URF.Core.Services;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using System;
using System.Threading.Tasks;
using System.IO;
using System.Data;
using Microsoft.Extensions.Logging;
using URF.Core.EF;
using System.Linq.Dynamic.Core;
using SmartAdmin.Dto;
using SmartAdmin.Service.Common;
// Sample to extend ProductService, scoped to only ProductService vs. application wide
namespace SmartAdmin.Service
{
public class CompanyService : Service<Company>, ICompanyService
{
private readonly IDataTableImportMappingService mappingservice;
private readonly ILogger<CompanyService> logger;
private readonly IExcelService excelService;
public CompanyService(
IDataTableImportMappingService mappingservice,
ILogger<CompanyService> logger,
IExcelService excelService,
ITrackableRepository<Company> repository) : base(repository)
{
this.mappingservice = mappingservice;
this.logger = logger;
this.excelService = excelService;
}
public async Task<Stream> ExportExcelAsync(string filterRules = "", string sort = "Id", string order = "asc")
{
var filters = PredicateBuilder.FromFilter<Company>(filterRules);
var expcolopts = await this.mappingservice.Queryable()
.Where(x => x.EntitySetName == "Company")
.Select(x => new ExpColumnOpts()
{
EntitySetName = x.EntitySetName,
FieldName = x.FieldName,
IsExportable = x.Exportable,
SourceFieldName = x.SourceFieldName,
LineNo = x.LineNo
}).ToArrayAsync();
var works = (await this.Query(filters).OrderBy(n => n.OrderBy($"{sort} {order}")).SelectAsync()).ToList();
var datarows = works.Select(n => new
{
Id = n.Id,
Name = n.Name,
Code = n.Code,
Address = n.Address,
Contect = n.Contact,
PhoneNumber = n.PhoneNumber,
RegisterDate = n.RegisterDate.ToString("yyyy-MM-dd HH:mm:ss")
}).ToList();
return await this.excelService.Export(datarows,expcolopts);
}
public async Task ImportDataTableAsync(Stream stream)
{
var datatable = await this.excelService.ReadDataTable(stream);
var mapping = await this.mappingservice.Queryable()
.Where(x => x.EntitySetName == "Company" &&
(x.IsEnabled == true || (x.IsEnabled == false && x.DefaultValue != null))
).ToListAsync();
if (mapping.Count == 0)
{
throw new NullReferenceException("没有找到Work对象的Excel导入配置信息,请执行[系统管理/Excel导入配置]");
}
foreach (DataRow row in datatable.Rows)
{
var requiredfield = mapping.Where(x => x.IsRequired == true && x.IsEnabled == true && x.DefaultValue == null).FirstOrDefault()?.SourceFieldName;
if (requiredfield != null || !row.IsNull(requiredfield))
{
var item = new Company();
foreach (var field in mapping)
{
var defval = field.DefaultValue;
var contain = datatable.Columns.Contains(field.SourceFieldName ?? "");
if (contain && !row.IsNull(field.SourceFieldName))
{
var worktype = item.GetType();
var propertyInfo = worktype.GetProperty(field.FieldName);
var safetype = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var safeValue = (row[field.SourceFieldName] == null) ? null : Convert.ChangeType(row[field.SourceFieldName], safetype);
propertyInfo.SetValue(item, safeValue, null);
}
else if (!string.IsNullOrEmpty(defval))
{
var worktype = item.GetType();
var propertyInfo = worktype.GetProperty(field.FieldName);
if (string.Equals(defval, "now", StringComparison.OrdinalIgnoreCase) && (propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(Nullable<DateTime>)))
{
var safetype = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var safeValue = Convert.ChangeType(DateTime.Now, safetype);
propertyInfo.SetValue(item, safeValue, null);
}
else if (string.Equals(defval, "guid", StringComparison.OrdinalIgnoreCase))
{
propertyInfo.SetValue(item, Guid.NewGuid().ToString(), null);
}
else if (string.Equals(defval, "user", StringComparison.OrdinalIgnoreCase))
{
propertyInfo.SetValue(item, "", null);
}
else
{
var safetype = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType;
var safeValue = Convert.ChangeType(defval, safetype);
propertyInfo.SetValue(item, safeValue, null);
}
}
}
this.Insert(item);
}
}
}
// Example, adding synchronous Single method
public Company Single(Expression<Func<Company, bool>> predicate)
{
return this.Repository.Queryable().Single(predicate);
}
}
}
| 39.801471 | 193 | 0.622391 | [
"Apache-2.0"
] | neozhu/smartadmin.core.urf | smartadmin-core-urf/src/SmartAdmin.Service/Implementation/CompanyService.cs | 5,465 | C# |
using Assets.Scripts.Helpers;
using Assets.Scripts.Infra;
using Clarity.App.Worlds.StoryGraph;
using Clarity.App.Worlds.Views;
using Clarity.App.Worlds.Views.Cameras;
using Clarity.Engine.Interaction.Input;
using Clarity.Engine.Interaction.Input.Keyboard;
using Clarity.Engine.Objects.WorldTree;
using Clarity.Engine.Platforms;
using Clarity.Engine.Visualization.Cameras;
using Valve.VR;
namespace Assets.Scripts.Interaction
{
public class FixedSmoothVrNavigationMode : IVrNavigationMode
{
private readonly IGlobalObjectService globalObjectService;
private readonly IInputService inputService;
private ICamera currentPathCamera;
private float floorHeightOffset;
private bool hasFinished;
private static readonly bool[] NoKeys = new bool[100];
public string UserFriendlyName => "Fixed Smooth";
public bool IsEnabled { get; private set; }
public FixedSmoothVrNavigationMode(IGlobalObjectService globalObjectService, IInputService inputService)
{
this.globalObjectService = globalObjectService;
this.inputService = inputService;
}
public void Initialize()
{
}
public void SetEnabled(bool enable)
{
IsEnabled = enable;
if (enable)
{
currentPathCamera = null;
hasFinished = true;
}
}
public void Update(FrameTime frameTime)
{
if (!IsEnabled)
return;
if (currentPathCamera == null)
{
if (SteamVR_Actions.default_NavigateNext.GetStateDown(SteamVR_Input_Sources.RightHand))
{
inputService.OnInputEvent(new KeyEventArgs
{
ComplexEventType = KeyEventType.Down,
KeyModifyers = KeyModifyers.None,
EventKey = Key.Right,
HasFocus = true,
State = new KeyboardState(NoKeys),
Viewport = null
});
}
if (SteamVR_Actions.default_NavigatePrev.GetStateDown(SteamVR_Input_Sources.RightHand))
{
inputService.OnInputEvent(new KeyEventArgs
{
ComplexEventType = KeyEventType.Down,
KeyModifyers = KeyModifyers.None,
EventKey = Key.Left,
HasFocus = true,
State = new KeyboardState(NoKeys),
Viewport = null
});
}
}
else
{
currentPathCamera.Update(frameTime);
var player = globalObjectService.VrPlayerCarrier;
var frame = currentPathCamera.GetGlobalFrame();
var eye = frame.Eye;
eye.Y -= floorHeightOffset;
player.transform.position = eye.ToUnity();
//player.transform.rotation = newProps.Frame.GetRotation().ToUnity();
if (hasFinished)
{
//player.transform.rotation = frame.GetRotation().ToUnity();
currentPathCamera = null;
}
}
}
public void NavigateTo(ISceneNode node, IStoryPath storyPath, CameraProps initialCameraProps, float? initialFloorHeight, float? targetFloorHeight)
{
var cFocusNode = node.GetComponent<IFocusNodeComponent>();
var newCamera = cFocusNode.DefaultViewpointMechanism.CreateControlledViewpoint();
if (initialFloorHeight.HasValue)
initialCameraProps.Frame.Eye.Y = initialFloorHeight.Value + 2;
currentPathCamera = new StoryPathCamera(storyPath, initialCameraProps, newCamera.GetProps(), () => hasFinished = true);
floorHeightOffset = initialFloorHeight.HasValue
? 2//initialCameraProps.Frame.Eye.Y - floorHeight.Value
: 0;
hasFinished = false;
}
public void FixedUpdate()
{
}
public void ShowHints(float seconds)
{
// TODO
}
public void HideHints()
{
// TODO
}
}
}
| 34.606299 | 154 | 0.56041 | [
"MIT"
] | Zulkir/ClarityWorlds | Source/UnityClarity/Assets/Scripts/Interaction/FixedSmoothVrNavigationMode.cs | 4,397 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.Extensions.Options;
namespace Gelf.Extensions.Logging
{
public static class LoggingBuilderExtensions
{
/// <summary>
/// Registers a <see cref="GelfLoggerProvider"/> with the service collection.
/// </summary>
/// <param name="builder"></param>
/// <returns></returns>
public static ILoggingBuilder AddGelf(this ILoggingBuilder builder)
{
builder.AddConfiguration();
builder.Services.AddSingleton<ILoggerProvider, GelfLoggerProvider>();
builder.Services.TryAddSingleton<IConfigureOptions<GelfLoggerOptions>, GelfLoggerOptionsSetup>();
return builder;
}
/// <summary>
/// Registers a <see cref="GelfLoggerProvider"/> with the service collection allowing logger options
/// to be customised.
/// </summary>
/// <param name="builder"></param>
/// <param name="configure"></param>
/// <returns></returns>
public static ILoggingBuilder AddGelf(this ILoggingBuilder builder, Action<GelfLoggerOptions> configure)
{
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
builder.AddGelf();
builder.Services.Configure(configure);
return builder;
}
}
}
| 34.5 | 112 | 0.637051 | [
"MIT"
] | Ned-CV/gelf-extensions-logging | src/Gelf.Extensions.Logging/LoggingBuilderExtensions.cs | 1,589 | C# |
/*
********************************************************************
*
* 曹旭升(sheng.c)
* E-mail: cao.silhouette@msn.com
* QQ: 279060597
* https://github.com/iccb1013
* http://shengxunwei.com
*
* © Copyright 2016
*
********************************************************************/
using Sheng.WeixinConstruction.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sheng.WeixinConstruction.Management.Shell.Models
{
public class LotteryPeriodListViewModel
{
public Campaign_LotteryBundle CampaignBundle
{
get;
set;
}
}
} | 21.451613 | 69 | 0.520301 | [
"MIT"
] | 1002753959/Sheng.WeixinConstruction | SourceCode/Sheng.WeixinConstruction.Management.Shell/Models/Campaign/Lottery/LotteryPeriodListViewModel.cs | 678 | C# |
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using Amns.GreyFox.Web.UI.WebControls;
namespace Amns.Tessen.Web.UI.WebControls
{
/// <summary>
/// <summary>
/// A custom grid for DojoTestListStatus.
/// </summary>
/// </summary>
[DefaultProperty("ConnectionString"),
ToolboxData("<{0}:DojoTestListStatusGrid runat=server></{0}:DojoTestListStatusGrid>")]
public class DojoTestListStatusGrid : TableGrid
{
private string connectionString;
#region Public Properties
[Bindable(false),
Category("Data"),
DefaultValue("")]
public string ConnectionString
{
get
{
return connectionString;
}
set
{
// Parse Connection String
if(value.StartsWith("<jet40virtual>") & Context != null)
connectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" +
Context.Server.MapPath(value.Substring(14, value.Length - 14));
else if(value.StartsWith("<jet40config>") & Context != null)
connectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" +
Context.Server.MapPath(System.Configuration.ConfigurationManager.AppSettings.Get(value.Substring(13, value.Length - 13)));
else
connectionString = value;
}
}
#endregion
protected override void OnInit(EventArgs e)
{
features = TableWindowFeatures.ClipboardCopier |
TableWindowFeatures.Scroller |
TableWindowFeatures.WindowPrinter |
TableWindowFeatures.ClientSideSelector;
}
#region Rendering
/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void RenderContent(HtmlTextWriter output)
{
DojoTestListStatusManager m = new DojoTestListStatusManager();
DojoTestListStatusCollection dojoTestListStatusCollection = m.GetCollection(string.Empty, string.Empty, null);
// Render Header Row
this.headerLockEnabled = true;
RenderRow(this.HeaderRowCssClass, "Status", "Description", "Teacher Editing");
bool rowflag = false;
string rowCssClass;
//
// Render Records
//
foreach(DojoTestListStatus dojoTestListStatus in dojoTestListStatusCollection)
{
if(rowflag) rowCssClass = defaultRowCssClass;
else rowCssClass = alternateRowCssClass;
rowflag = !rowflag;
output.WriteBeginTag("tr");
output.WriteAttribute("i", dojoTestListStatus.ID.ToString());
output.WriteLine(HtmlTextWriter.TagRightChar);
output.Indent++;
output.WriteBeginTag("td");
output.WriteAttribute("class", rowCssClass);
output.Write(HtmlTextWriter.TagRightChar);
output.Write(dojoTestListStatus.Name);
output.WriteEndTag("td");
output.WriteLine();
output.WriteBeginTag("td");
output.WriteAttribute("class", rowCssClass);
output.Write(HtmlTextWriter.TagRightChar);
output.Write(dojoTestListStatus.Description);
output.WriteEndTag("td");
output.WriteLine();
output.WriteBeginTag("td");
output.WriteAttribute("class", rowCssClass);
output.Write(HtmlTextWriter.TagRightChar);
output.Write(dojoTestListStatus.TeacherEditingEnabled.ToString());
output.WriteEndTag("td");
output.WriteLine();
output.Indent--;
output.WriteEndTag("tr");
output.WriteLine();
}
}
#endregion
}
}
| 28.612069 | 128 | 0.714673 | [
"MIT"
] | rahodges/Tessen | Amns.Tessen/Web/UI/WebControls/DojoTestListStatusGrid.cs | 3,319 | C# |
namespace HareDu.Core.Configuration
{
using System;
public interface BrokerConfigurator
{
/// <summary>
/// Specify the RabbitMQ server url to connect to.
/// </summary>
/// <param name="url"></param>
void ConnectTo(string url);
/// <summary>
/// Specify the maximum time before the HTTP request to the RabbitMQ server will fail.
/// </summary>
/// <param name="timeout"></param>
void TimeoutAfter(TimeSpan timeout);
/// <summary>
/// Specify the user credentials to connect to the RabbitMQ server.
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
void UsingCredentials(string username, string password);
}
} | 30.846154 | 94 | 0.573566 | [
"Apache-2.0"
] | ahives/HareDu2 | src/HareDu.Core/Configuration/BrokerConfigurator.cs | 804 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Volo.Abp.Domain.Entities;
namespace Meowv.Blog.Domain.Blog
{
/// <summary>
/// Tag
/// </summary>
public class Tag : Entity<int>
{
/// <summary>
/// 标签名称
/// </summary>
public string TagName { get; set; }
/// <summary>
/// 展示名称
/// </summary>
public string DisplayName { get; set; }
}
}
| 18.791667 | 47 | 0.529933 | [
"MIT"
] | itbetaw/Meowv.Blog | src/Meowv.Blog.Domain/Blog/Tag.cs | 469 | C# |
using System;
using System.Text.RegularExpressions;
namespace Blogifier.Shared.Extensions
{
public static class StringExtensions
{
public static string Capitalize(this string str)
{
if (string.IsNullOrEmpty(str))
return string.Empty;
char[] a = str.ToCharArray();
a[0] = char.ToUpper(a[0]);
return new string(a);
}
public static bool Contains(this string source, string toCheck, StringComparison comp)
{
return source.IndexOf(toCheck, comp) >= 0;
}
public static string SanitizePath(this string str)
{
if (string.IsNullOrWhiteSpace(str))
return string.Empty;
str = str.Replace("%2E", ".").Replace("%2F", "/");
if (str.Contains("..") || str.Contains("//"))
throw new ApplicationException("Invalid directory path");
return str;
}
public static string RemoveScriptTags(this string str)
{
Regex scriptRegex = new Regex(@"<script[^>]*>[\s\S]*?</script>");
return scriptRegex.Replace(str, "");
}
}
}
| 28.309524 | 94 | 0.549201 | [
"MIT"
] | CabinIcarus/Blogifier | src/Blogifier.Shared/Extensions/StringExtensions.cs | 1,189 | C# |
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace System.Data.Fakes.QueryHandling.Impl
{
sealed class ExecuteReaderQueryHandler<TArgs, T> : AbstractQueryHandler
{
private readonly Func<TArgs, T[]> getResult;
public ExecuteReaderQueryHandler(List<Regex> queryRegex, Dictionary<string, Func<object, bool>> argCheckers, Func<TArgs, T[]> getResult) : base(queryRegex, argCheckers)
{
this.getResult = getResult;
}
protected override QueryType Type => QueryType.Reader;
public override IDataReader GetReader(IDbCommand command) => DataReader.Create(getResult(GetArgs<TArgs>(command)));
}
}
| 36.368421 | 176 | 0.7178 | [
"MIT"
] | JTOne123/DotNet.Extensions | Testing.System.Data.Fakes/QueryHandling/Impl/Handlers/ExecuteReaderQueryHandler.cs | 691 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.