content stringlengths 23 1.05M |
|---|
using MatterHackers.Agg.UI;
using System.Collections.Generic;
namespace MatterHackers.Agg
{
public class GridControlPage : TabPage
{
public GridControlPage()
: base("Grid Control")
{
GuiWidget thingToHide;
{
FlowLayoutWidget twoColumns = new FlowLayoutWidget();
twoColumns.Name = "twoColumns";
{
FlowLayoutWidget leftColumn = new FlowLayoutWidget(FlowDirection.TopToBottom);
leftColumn.Name = "leftColumn";
{
FlowLayoutWidget topLeftStuff = new FlowLayoutWidget(FlowDirection.TopToBottom);
topLeftStuff.Name = "topLeftStuff";
topLeftStuff.AddChild(new TextWidget("Top of Top Stuff"));
thingToHide = new Button("thing to hide");
topLeftStuff.AddChild(thingToHide);
topLeftStuff.AddChild(new TextWidget("Bottom of Top Stuff"));
leftColumn.AddChild(topLeftStuff);
//leftColumn.DebugShowBounds = true;
}
twoColumns.AddChild(leftColumn);
}
{
FlowLayoutWidget rightColumn = new FlowLayoutWidget(FlowDirection.TopToBottom);
rightColumn.Name = "rightColumn";
CheckBox hideCheckBox = new CheckBox("Hide Stuff");
rightColumn.AddChild(hideCheckBox);
hideCheckBox.CheckedStateChanged += (sender, e) =>
{
if (hideCheckBox.Checked)
{
thingToHide.Visible = false;
}
else
{
thingToHide.Visible = true;
}
};
twoColumns.AddChild(rightColumn);
}
this.AddChild(twoColumns);
}
}
}
} |
using EasyMoney.Modules.FakeManageUsers.Application.Exceptions;
using EasyMoney.Modules.FakeManageUsers.Domain.Users;
using EasyMoney.Modules.FakeManageUsers.Infrastructure.Context;
using Microsoft.AspNetCore.Identity;
using System.Linq;
using System.Threading.Tasks;
namespace EasyMoney.Modules.FakeManageUsers.Application.Authenticate
{
public class SignInManager : ISignInManager
{
private readonly SignInManager<User> _signInManager;
private readonly ITokenService _tokenService;
private readonly ManageUsersContext _context;
public SignInManager(SignInManager<User> signInManager, ITokenService tokenService, ManageUsersContext context)
{
_signInManager = signInManager;
_tokenService = tokenService;
_context = context;
}
public async Task<string> Authenticate(string userName, string password)
{
var user = _context.Users.SingleOrDefault(x => x.UserName == userName);
if (user == null)
{
throw new LoginOrPasswordAreIncorrectException();
}
var results = await _signInManager.PasswordSignInAsync(userName, password, false, false);
if (!results.Succeeded)
{
throw new LoginOrPasswordAreIncorrectException();
}
var token = _tokenService.GenerateJwtForUser(user.Id);
return token;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace HardwareDrivers.RPi.Wrappers
{
public static class I2CWrapper
{
[DllImport("./NativeLibs/i2cNativeLib.o", EntryPoint = "openBus", SetLastError = true)]
public static extern int OpenBus(string busFileName);
[DllImport("./NativeLibs/i2cNativeLib.o", EntryPoint = "closeBus", SetLastError = true)]
public static extern int CloseBus(int busHandle);
[DllImport("./NativeLibs/i2cNativeLib.o", EntryPoint = "readBytes", SetLastError = true)]
public static extern int ReadBytes(int busHandle, int addr, byte[] buf, int len);
[DllImport("./NativeLibs/i2cNativeLib.o", EntryPoint = "writeBytes", SetLastError = true)]
public static extern int WriteBytes(int busHandle, int addr, byte[] buf, int len);
}
}
|
using System;
using GroboContainer.Impl.Abstractions;
using GroboContainer.Impl.Abstractions.AutoConfiguration;
using GroboContainer.Impl.Implementations;
using NUnit.Framework;
using Rhino.Mocks;
namespace GroboContainer.Tests.AbstractionTests
{
public class AbstractionConfigurationCollectionTest : CoreTestBase
{
#region Setup/Teardown
public override void SetUp()
{
base.SetUp();
factory = GetMock<IAutoAbstractionConfigurationFactory>();
configurationCollection = new AbstractionConfigurationCollection(factory);
}
#endregion
[Test]
public void TestAdd()
{
var configuration = GetMock<IAbstractionConfiguration>();
configuration
.Expect(c => c.GetImplementations())
.Return(new IImplementationConfiguration[] {new InstanceImplementationConfiguration(null, 1)});
configurationCollection.Add(typeof(int), configuration);
Assert.AreSame(configuration, configurationCollection.Get(typeof(int)));
Assert.AreSame(configuration, configurationCollection.Get(typeof(int)));
RunMethodWithException<InvalidOperationException>(
() => configurationCollection.Add(typeof(int), configuration),
"Тип System.Int32 уже сконфигурирован");
}
[Test]
public void TestBig()
{
var configurationIntShort = NewMock<IAbstractionConfiguration>();
var configurationIntInt = NewMock<IAbstractionConfiguration>();
var configurationLong = NewMock<IAbstractionConfiguration>();
configurationCollection.Add(typeof(short), configurationIntShort);
factory.Expect(f => f.CreateByType(typeof(int))).Return(configurationIntInt);
Assert.AreSame(configurationIntInt, configurationCollection.Get(typeof(int)));
Assert.AreSame(configurationIntShort, configurationCollection.Get(typeof(short)));
//factory.ExpectCreateByType(typeof (long), new[] {"a"}, configurationLong);
factory.Expect(f => f.CreateByType(typeof(long))).Return(configurationLong);
Assert.AreSame(configurationLong, configurationCollection.Get(typeof(long)));
}
[Test]
public void TestCreate()
{
var configuration = NewMock<IAbstractionConfiguration>();
factory.Expect(f => f.CreateByType(typeof(int))).Return(configuration);
Assert.AreSame(configuration, configurationCollection.Get(typeof(int)));
Assert.AreSame(configuration, configurationCollection.Get(typeof(int)));
}
[Test]
public void TestGetAll()
{
CollectionAssert.IsEmpty(configurationCollection.GetAll());
var configuration1 = NewMock<IAbstractionConfiguration>();
var configuration2 = NewMock<IAbstractionConfiguration>();
configurationCollection.Add(typeof(string), null); //hack, тест на != null
configurationCollection.Add(typeof(int), configuration1);
configurationCollection.Add(typeof(long), configuration2);
CollectionAssert.AreEquivalent(new[] {null, configuration1, configuration2},
configurationCollection.GetAll());
}
private IAutoAbstractionConfigurationFactory factory;
private AbstractionConfigurationCollection configurationCollection;
}
} |
@using BTCPayServer.Views.Stores
@model BTCPayServer.Services.Altcoins.Stripe.UI.StripeController.StripePaymentMethodViewModel
@{
Layout = "../Shared/_NavLayout.cshtml";
ViewData["NavPartialName"] = "../Stores/_Nav";
ViewData.SetActivePageAndTitle(StoreNavPages.ActivePage, $"{Model.CryptoCode} Settings");
}
<partial name="_StatusMessage" />
<div class="row">
<div class="col-md-6">
<div asp-validation-summary="All" class="text-danger"></div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<form method="post" asp-action="GetStoreStripePaymentMethod"
asp-route-storeId="@this.Context.GetRouteValue("storeId")"
asp-route-cryptoCode="@this.Context.GetRouteValue("cryptoCode")"
class="mt-4" enctype="multipart/form-data">
<input type="hidden" asp-for="CryptoCode"/>
<div class="form-group">
<label asp-for="PublishableKey"></label>
<input asp-for="PublishableKey" type="text" class="form-control"/>
<span asp-validation-for="PublishableKey" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SecretKey"></label>
<input asp-for="SecretKey" type="text" class="form-control"/>
<span asp-validation-for="SecretKey" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Enabled"></label>
<input asp-for="Enabled" type="checkbox" class="form-check"/>
<span asp-validation-for="Enabled" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="UseCheckout"></label>
<input asp-for="UseCheckout" type="checkbox" class="form-check"/>
<span asp-validation-for="UseCheckout" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="SaveButton">Save</button>
<a class="btn btn-secondary" asp-action="GetStoreStripePaymentMethods"
asp-route-storeId="@this.Context.GetRouteValue("storeId")"
asp-route-cryptoCode="@this.Context.GetRouteValue("cryptoCode")"
asp-controller="Stripe">
Back to list
</a>
</div>
</form>
</div>
</div>
@section Scripts {
@await Html.PartialAsync("_ValidationScriptsPartial")
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace LootHeresyLib.Extensions.Specific
{
internal static class InitializerExtensions
{
internal static void Add<T>(this Stack<T> s, T t)
=> s.Push(t);
internal static void Add<T>(this Queue<T> q, T t)
=> q.Enqueue(t);
}
}
|
using PackProject.Tool.Models;
namespace PackProject.Tool.Services.GraphAnalyzer
{
public interface IDependencyGraphAnalyzer
{
DependencyGraphAnalysis Analyze(DependencyGraph graph);
}
} |
namespace MyWebServer.HTTP.Responses.Contracts
{
using MyWebServer.HTTP.Cookies;
using MyWebServer.HTTP.Cookies.Contracts;
using MyWebServer.HTTP.Enums;
using MyWebServer.HTTP.Headers;
using MyWebServer.HTTP.Headers.Contracts;
public interface IHttpResponse
{
HttpResponseStatusCode StatusCode { get; set; }
IHttpHeadersCollection Headers { get; }
IHttpCookieCollection Cookies { get; }
byte[] Content { get; set; }
void AddHeader(HttpHeader header);
void AddCookie(HttpCookie cookie);
byte[] GetBytes();
}
}
|
namespace Nasfaq.JSON
{
//api/getCatalogue
public class GetItemCatalogue
{
public bool success { get; set; }
public ItemCatalogue_Item[] catalogue { get; set; }
}
public class ItemCatalogue_Item
{
public string name { get; set; }
public string description { get; set; }
public string modifier { get; set; }
public double modifierMult { get; set; }
}
} |
using ImageWizard.Core.Processing.Builder;
using ImageWizard.Filters;
using ImageWizard.SvgNet.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;
namespace ImageWizard.SvgNet.Builder
{
class SvgNetBuilder : PipelineBuilder, ISvgNetBuilder
{
public SvgNetBuilder(IServiceCollection service)
: base(service)
{
}
}
}
|
namespace Community.Archives.Core;
public readonly struct ArchiveEntry : IDisposable, IAsyncDisposable
{
public Stream Content { get; init; }
public string Name { get; init; }
public void Dispose()
{
Content?.Dispose();
}
public ValueTask DisposeAsync()
{
return Content?.DisposeAsync() ?? new ValueTask();
}
public override string ToString()
{
return $"{Name} ({Content.Length} bytes)";
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Handlers.Tls
{
using System;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
public sealed class ServerTlsSniSettings
{
public ServerTlsSniSettings(Func<string, Task<ServerTlsSettings>> serverTlsSettingMap, string defaultServerHostName = null)
{
Contract.Requires(serverTlsSettingMap != null);
this.ServerTlsSettingMap = serverTlsSettingMap;
this.DefaultServerHostName = defaultServerHostName;
}
public Func<string, Task<ServerTlsSettings>> ServerTlsSettingMap { get; }
public string DefaultServerHostName { get; }
}
} |
using System;
using Microsoft.Extensions.DiagnosticAdapter;
namespace Plcway.Framework.Tracing
{
internal class DefaultDiagnosticListener
{
[DiagnosticName("Host.MiddlewareStarting")]
public virtual void OnMiddlewareStarting()
{
}
}
}
|
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ORMDemo.MultiTenancy;
namespace ORMDemo.MultiTenancy.Migrations.Tenants
{
[DbContext(typeof(TenantsContext))]
partial class TenantsContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.1.4-rtm-31024")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("ORMDemo.MultiTenancy.Models.Tenant", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Host")
.IsRequired()
.HasMaxLength(100);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100);
b.HasKey("Id");
b.ToTable("Tenants");
b.HasData(
new { Id = new Guid("b992d195-56ce-49bf-bfdd-4145ba9a0c13"), Host = "localhost:5200", Name = "Customer A" },
new { Id = new Guid("f55ae0c8-4573-4a0a-9ef9-32f66a828d0e"), Host = "localhost:5300", Name = "Customer B" }
);
});
#pragma warning restore 612, 618
}
}
}
|
using System.ComponentModel;
namespace Neurotoxin.Roentgen.Data.Entities
{
[DisplayName("NServiceBus Event")]
public class NServiceBusEventEntity : ChannelEntity
{
}
}
|
namespace Nop.Web.Framework.Models
{
/// <summary>
/// Represents a configuration model
/// </summary>
public partial interface IConfigModel
{
}
} |
using NServiceBus.Extensibility;
namespace NServiceBus.FluentOptions
{
public class Dispatch : MessageOption
{
private Dispatch()
{
}
public static Dispatch Immediately { get; } = new Dispatch();
internal override void Apply(ExtendableOptions options)
{
options.RequireImmediateDispatch();
}
internal override bool IsApplied(ExtendableOptions options)
{
return options.RequiredImmediateDispatch();
}
}
} |
#region Copyright
//
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
#region Usings
using System.Xml.XPath;
using DotNetNuke.Common.Lists;
using DotNetNuke.Framework;
#endregion
namespace DotNetNuke.Services.Installer.Dependencies
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The DependencyFactory is a factory class that is used to instantiate the
/// appropriate Dependency
/// </summary>
/// <remarks>
/// </remarks>
/// -----------------------------------------------------------------------------
public class DependencyFactory
{
#region Public Shared Methods
/// -----------------------------------------------------------------------------
/// <summary>
/// The GetDependency method instantiates (and returns) the relevant Dependency
/// </summary>
/// <param name="dependencyNav">The manifest (XPathNavigator) for the dependency</param>
/// -----------------------------------------------------------------------------
public static IDependency GetDependency(XPathNavigator dependencyNav)
{
IDependency dependency = null;
string dependencyType = Util.ReadAttribute(dependencyNav, "type");
switch (dependencyType.ToLowerInvariant())
{
case "coreversion":
dependency = new CoreVersionDependency();
break;
case "package":
dependency = new PackageDependency();
break;
case "managedpackage":
dependency = new ManagedPackageDependency();
break;
case "permission":
dependency = new PermissionsDependency();
break;
case "type":
dependency = new TypeDependency();
break;
default:
//Dependency type is defined in the List
var listController = new ListController();
ListEntryInfo entry = listController.GetListEntryInfo("Dependency", dependencyType);
if (entry != null && !string.IsNullOrEmpty(entry.Text))
{
//The class for the Installer is specified in the Text property
dependency = (DependencyBase)Reflection.CreateObject(entry.Text, "Dependency_" + entry.Value);
}
break;
}
if (dependency == null)
{
//Could not create dependency, show generic error message
dependency = new InvalidDependency(Util.INSTALL_Dependencies);
}
//Read Manifest
dependency.ReadManifest(dependencyNav);
return dependency;
}
#endregion
}
}
|
/*
* 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.
*/
// ReSharper disable SuspiciousTypeConversion.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable StringIndexOfIsCultureSpecific.1
// ReSharper disable StringIndexOfIsCultureSpecific.2
// ReSharper disable StringCompareToIsCultureSpecific
// ReSharper disable StringCompareIsCultureSpecific.1
// ReSharper disable UnusedMemberInSuper.Global
namespace Apache.Ignite.Core.Tests.Cache.Query.Linq
{
using System;
using System.Linq;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Linq;
using NUnit.Framework;
/// <summary>
/// Tests LINQ.
/// </summary>
public partial class CacheLinqTest
{
/// <summary>
/// Tests numerics.
/// </summary>
[Test]
public void TestNumerics()
{
var cache = Ignition.GetIgnite().GetOrCreateCache<int, Numerics>(new CacheConfiguration("numerics",
new QueryEntity(typeof(int), typeof(Numerics)))
{
SqlEscapeAll = GetSqlEscapeAll()
});
for (var i = 0; i < 100; i++)
cache[i] = new Numerics(((double)i - 50) / 3);
var query = cache.AsCacheQueryable().Select(x => x.Value);
var bytes = query.Select(x => x.Byte);
var sbytes = query.Select(x => x.Sbyte);
var shorts = query.Select(x => x.Short);
var ushorts = query.Select(x => x.Ushort);
var ints = query.Select(x => x.Int);
var uints = query.Select(x => x.Uint);
var longs = query.Select(x => x.Long);
var ulongs = query.Select(x => x.Ulong);
var doubles = query.Select(x => x.Double);
var decimals = query.Select(x => x.Decimal);
var floats = query.Select(x => x.Float);
CheckFunc(x => Math.Abs(x), doubles);
CheckFunc(x => Math.Abs((sbyte)x), bytes);
CheckFunc(x => Math.Abs(x), sbytes);
CheckFunc(x => Math.Abs(x), shorts);
CheckFunc(x => Math.Abs((short)x), ushorts);
CheckFunc(x => Math.Abs(x), ints);
CheckFunc(x => Math.Abs((int)x), uints);
CheckFunc(x => Math.Abs(x), longs);
CheckFunc(x => Math.Abs((long)x), ulongs);
CheckFunc(x => Math.Abs(x), decimals);
CheckFunc(x => Math.Abs(x), floats);
CheckFunc(x => Math.Acos(x), doubles);
CheckFunc(x => Math.Asin(x), doubles);
CheckFunc(x => Math.Atan(x), doubles);
CheckFunc(x => Math.Atan2(x, 0.5), doubles);
CheckFunc(x => Math.Ceiling(x), doubles);
CheckFunc(x => Math.Ceiling(x), decimals);
CheckFunc(x => Math.Cos(x), doubles);
CheckFunc(x => Math.Cosh(x), doubles);
CheckFunc(x => Math.Exp(x), doubles);
CheckFunc(x => Math.Floor(x), doubles);
CheckFunc(x => Math.Floor(x), decimals);
CheckFunc(x => Math.Log(x), doubles);
CheckFunc(x => Math.Log10(x), doubles);
CheckFunc(x => Math.Pow(x, 3.7), doubles);
CheckFunc(x => Math.Round(x), doubles);
CheckFunc(x => Math.Round(x, 3), doubles);
CheckFunc(x => Math.Round(x), decimals);
CheckFunc(x => Math.Round(x, 3), decimals);
CheckFunc(x => Math.Sign(x), doubles);
CheckFunc(x => Math.Sign(x), decimals);
CheckFunc(x => Math.Sign(x), floats);
CheckFunc(x => Math.Sign(x), ints);
CheckFunc(x => Math.Sign(x), longs);
CheckFunc(x => Math.Sign(x), shorts);
CheckFunc(x => Math.Sign(x), sbytes);
CheckFunc(x => Math.Sin(x), doubles);
CheckFunc(x => Math.Sinh(x), doubles);
CheckFunc(x => Math.Sqrt(x), doubles);
CheckFunc(x => Math.Tan(x), doubles);
CheckFunc(x => Math.Tanh(x), doubles);
CheckFunc(x => Math.Truncate(x), doubles);
CheckFunc(x => Math.Truncate(x), decimals);
// Operators
CheckFunc(x => x * 7, doubles);
CheckFunc(x => x / 7, doubles);
CheckFunc(x => x % 7, doubles);
CheckFunc(x => x + 7, doubles);
CheckFunc(x => x - 7, doubles);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System;
public class ModesScreenController : MonoBehaviour {
#region Fields
private const int WAVE_AMOUNT = 5;
private const float INPUT_TIME = 0.2f;
private const int COLS = 4;
[SerializeField] private Text[] modes;
private Text selectedMode;
private int selectedModeIndex = 0;
private float lastInput;
[SerializeField] private GameObject asteroids;
private AsteroidSpawner asteroidSpawner;
#endregion
#region Mono Behaviour
void Awake() {
asteroidSpawner = asteroids.GetComponent<AsteroidSpawner>();
lastInput = Time.time;
}
void Start() {
asteroidSpawner.SpawnAsteroids(WAVE_AMOUNT, AsteroidType.Large);
asteroidSpawner.SpawnAsteroids(WAVE_AMOUNT, AsteroidType.Medium);
asteroidSpawner.SpawnAsteroids(WAVE_AMOUNT, AsteroidType.Small);
selectedModeIndex = UnityEngine.Random.Range(0, modes.Length);
SelectMode(selectedModeIndex);
}
void OnEnable() {
EventManager.StartListening<MoveRightInput>(OnMoveRightInput);
EventManager.StartListening<MoveLeftInput>(OnMoveLeftInput);
EventManager.StartListening<MoveUpInput>(OnMoveUpInput);
EventManager.StartListening<MoveDownInput>(OnMoveDownInput);
EventManager.StartListening<SpaceInput>(OnSpaceInput);
EventManager.StartListening<ReturnInput>(OnReturnInput);
}
void OnDisable() {
EventManager.StopListening<MoveRightInput>(OnMoveRightInput);
EventManager.StopListening<MoveLeftInput>(OnMoveLeftInput);
EventManager.StopListening<MoveUpInput>(OnMoveUpInput);
EventManager.StopListening<MoveDownInput>(OnMoveDownInput);
EventManager.StopListening<SpaceInput>(OnSpaceInput);
EventManager.StopListening<ReturnInput>(OnReturnInput);
}
#endregion
#region Event Behaviour
void OnMoveRightInput(MoveRightInput moveRightInput) {
if (Time.time > lastInput + INPUT_TIME && selectedModeIndex < modes.Length - 1)
SelectMode(selectedModeIndex + 1);
}
void OnMoveLeftInput(MoveLeftInput moveLeftInput) {
if (Time.time > lastInput + INPUT_TIME && selectedModeIndex > 0)
SelectMode(selectedModeIndex - 1);
}
void OnMoveUpInput(MoveUpInput moveUpInput) {
if (Time.time > lastInput + INPUT_TIME && selectedModeIndex > COLS - 1)
SelectMode(selectedModeIndex - COLS);
}
void OnMoveDownInput(MoveDownInput moveDownInput) {
if (Time.time > lastInput + INPUT_TIME && selectedModeIndex < modes.Length - COLS) {
SelectMode(selectedModeIndex + COLS);
}
}
void OnSpaceInput(SpaceInput spaceInput) {
SceneManager.LoadScene(selectedModeIndex + 2); // Adds title and mode selection screen
}
void OnReturnInput(ReturnInput returnInput) {
SceneManager.LoadScene(selectedModeIndex + 2); // Adds title and mode selection screen
}
#endregion
#region Private Behaviour
private void SelectMode(int index) {
lastInput = Time.time;
selectedModeIndex = index;
if (selectedMode != null)
selectedMode.GetComponent<Animator>().Play("Idle");
selectedMode = modes[index];
selectedMode.GetComponent<Animator>().Play("BlinkingText");
EventManager.TriggerEvent(new SelectModeEvent());
}
#endregion
}
|
using System;
using System.Net.Http;
using Serilog;
namespace TaskSample
{
class Program
{
static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateLogger();
var client = new HttpClient();
var resultTask = client.GetStringAsync("https://www.packtpub.com");
Console.WriteLine("Performing other operations...");
//Now obtain the resu;t
Log.Information(resultTask.Result);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace DevZH.UI.Drawing
{
[StructLayout(LayoutKind.Sequential)]
public struct FontMetrics
{
public double Ascent;
public double Descent;
public double Leading;
// TODO do these two mean the same across all platforms?
public double UnderlinePos;
public double UnderlineThickness;
}
}
|
using Microsoft.AspNetCore.Authorization;
namespace Abmes.DataCollector.Vault.WebAPI.Authorization
{
public class UserAllowedDataCollectionRequirement : IAuthorizationRequirement
{
public UserAllowedDataCollectionRequirement()
{
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Microsoft.DotNet.Cli
{
// https://github.com/dotnet/runtime/blob/main/src/libraries/Common/src/Interop/Unix/System.Native/Interop.Stat.cs
internal static class StatInterop
{
// Even though csc will by default use a sequential layout, a CS0649 warning as error
// is produced for un-assigned fields when no StructLayout is specified.
//
// Explicitly saying Sequential disables that warning/error for consumers which only
// use Stat in debug builds.
[StructLayout(LayoutKind.Sequential)]
internal struct FileStatus
{
internal FileStatusFlags Flags;
internal int Mode;
internal uint Uid;
internal uint Gid;
internal long Size;
internal long ATime;
internal long ATimeNsec;
internal long MTime;
internal long MTimeNsec;
internal long CTime;
internal long CTimeNsec;
internal long BirthTime;
internal long BirthTimeNsec;
internal long Dev;
internal long Ino;
internal uint UserFlags;
}
[Flags]
internal enum Permissions
{
Mask = S_IRWXU | S_IRWXG | S_IRWXO,
S_IRWXU = S_IRUSR | S_IWUSR | S_IXUSR,
S_IRUSR = 0x100,
S_IWUSR = 0x80,
S_IXUSR = 0x40,
S_IRWXG = S_IRGRP | S_IWGRP | S_IXGRP,
S_IRGRP = 0x20,
S_IWGRP = 0x10,
S_IXGRP = 0x8,
S_IRWXO = S_IROTH | S_IWOTH | S_IXOTH,
S_IROTH = 0x4,
S_IWOTH = 0x2,
S_IXOTH = 0x1,
S_IXUGO = S_IXUSR | S_IXGRP | S_IXOTH,
}
[Flags]
internal enum FileStatusFlags
{
None = 0,
HasBirthTime = 1,
}
[DllImport("libSystem.Native", EntryPoint = "SystemNative_LStat", SetLastError = true)]
internal static extern int LStat(string path, out FileStatus output);
}
}
|
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering
{
public static class TextureXR
{
// Limit memory usage of default textures
const int kMaxSliceCount = 2;
// Must be in sync with shader define in TextureXR.hlsl
public static bool useTexArray
{
get
{
// XRTODO: Vulkan, PSVR, Mac with metal only for OS 10.14+, etc
switch (SystemInfo.graphicsDeviceType)
{
// XRTODO: disabled until all SPI code is merged
case GraphicsDeviceType.Direct3D11:
return false;
}
return false;
}
}
public static VRTextureUsage OverrideRenderTexture(bool xrInstancing, ref TextureDimension dimension, ref int slices)
{
if (xrInstancing && useTexArray)
{
// TEXTURE2D_X macros will now expand to TEXTURE2D_ARRAY
dimension = TextureDimension.Tex2DArray;
// XRTODO: need to also check if stereo is enabled in camera!
if (XRGraphics.stereoRenderingMode == XRGraphics.StereoRenderingMode.SinglePassInstanced)
{
// Add a new dimension
slices = slices * XRGraphics.eyeCount;
// XRTODO: useful? if yes, add validation, asserts
return XRGraphics.eyeTextureDesc.vrUsage;
}
}
return VRTextureUsage.None;
}
public static Texture GetClearTexture()
{
if (useTexArray)
return clearTexture2DArray;
return clearTexture;
}
public static Texture GetBlackTexture()
{
if (useTexArray)
return blackTexture2DArray;
return Texture2D.blackTexture;
}
public static Texture GetWhiteTexture()
{
if (useTexArray)
return whiteTexture2DArray;
return Texture2D.whiteTexture;
}
private static Texture2DArray CreateTexture2DArrayFromTexture2D(Texture2D source, string name)
{
Texture2DArray texArray = new Texture2DArray(source.width, source.height, kMaxSliceCount, source.format, false) { name = name };
for (int i = 0; i < kMaxSliceCount; ++i)
Graphics.CopyTexture(source, 0, 0, texArray, i, 0);
return texArray;
}
private static Texture2D m_ClearTexture;
private static Texture2D clearTexture
{
get
{
if (m_ClearTexture == null)
{
m_ClearTexture = new Texture2D(1, 1, TextureFormat.ARGB32, false) { name = "Clear Texture" };
m_ClearTexture.SetPixel(0, 0, Color.clear);
m_ClearTexture.Apply();
}
return m_ClearTexture;
}
}
static Texture2DArray m_ClearTexture2DArray;
public static Texture2DArray clearTexture2DArray
{
get
{
if (m_ClearTexture2DArray == null)
m_ClearTexture2DArray = CreateTexture2DArrayFromTexture2D(clearTexture, "Clear Texture2DArray");
Debug.Assert(XRGraphics.eyeCount <= m_ClearTexture2DArray.depth);
return m_ClearTexture2DArray;
}
}
static Texture2DArray m_BlackTexture2DArray;
public static Texture2DArray blackTexture2DArray
{
get
{
if (m_BlackTexture2DArray == null)
m_BlackTexture2DArray = CreateTexture2DArrayFromTexture2D(Texture2D.blackTexture, "Black Texture2DArray");
Debug.Assert(XRGraphics.eyeCount <= m_BlackTexture2DArray.depth);
return m_BlackTexture2DArray;
}
}
static Texture2DArray m_WhiteTexture2DArray;
public static Texture2DArray whiteTexture2DArray
{
get
{
if (m_WhiteTexture2DArray == null)
m_WhiteTexture2DArray = CreateTexture2DArrayFromTexture2D(Texture2D.whiteTexture, "White Texture2DArray");
Debug.Assert(XRGraphics.eyeCount <= m_WhiteTexture2DArray.depth);
return m_WhiteTexture2DArray;
}
}
}
}
|
using System.Collections.Generic;
using DeltaEngine.Datatypes;
using DeltaEngine.Rendering2D.Fonts;
namespace DeltaEngine.Rendering2D.Graphs
{
/// <summary>
/// Labels at fixed vertical intervals to the right of the graph - eg. if there were five
/// percentiles there's be six lines at 0%, 20%, 40%, 60%, 80% and 100% of the maximum value.
/// </summary>
internal class RenderPercentileLabels
{
public void Refresh(Graph graph)
{
ClearOldPercentileLabels();
if (graph.IsVisible && IsVisible)
CreateNewPercentileLabels(graph);
}
public bool IsVisible { get; set; }
private void ClearOldPercentileLabels()
{
foreach (FontText percentileLabel in PercentileLabels)
percentileLabel.IsActive = false;
PercentileLabels.Clear();
}
public readonly List<FontText> PercentileLabels = new List<FontText>();
private void CreateNewPercentileLabels(Graph graph)
{
for (int i = 0; i <= NumberOfPercentiles; i++)
CreatePercentileLabel(graph, i);
}
public int NumberOfPercentiles { get; set; }
private void CreatePercentileLabel(Graph graph, int index)
{
PercentileLabels.Add(new FontText(Font.Default, GetPercentileLabelText(graph, index),
GetPercentileLabelDrawArea(graph, index))
{
RenderLayer = graph.RenderLayer + RenderLayerOffset,
Color = PercentileLabelColor,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Center,
});
}
private string GetPercentileLabelText(Graph graph, int index)
{
float value = graph.Viewport.Top + index * graph.Viewport.Height / NumberOfPercentiles;
if (ArePercentileLabelsInteger)
value = (int)value;
return PercentilePrefix + value + PercentileSuffix;
}
private Rectangle GetPercentileLabelDrawArea(Entity2D graph, int index)
{
float borderWidth = graph.DrawArea.Width * Graph.Border;
float x = graph.DrawArea.Right + 2 * borderWidth;
float borderHeight = graph.DrawArea.Height * Graph.Border;
float interval = (graph.DrawArea.Height - 2 * borderHeight) / NumberOfPercentiles;
float bottom = graph.DrawArea.Bottom - borderHeight;
float y = bottom - index * interval;
return new Rectangle(x, y - interval / 2, 1.0f, interval);
}
public bool ArePercentileLabelsInteger;
public string PercentilePrefix = "";
public string PercentileSuffix = "";
public Color PercentileLabelColor = Color.White;
private const int RenderLayerOffset = 2;
}
} |
using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using SiteWatcher.WebAPI.Extensions;
using Microsoft.AspNetCore.Mvc;
using SiteWatcher.WebAPI.Filters;
using Microsoft.AspNetCore.HttpOverrides;
using SiteWatcher.Application;
using SiteWatcher.Application.Interfaces;
using SiteWatcher.Application.Users.Commands.RegisterUser;
using SiteWatcher.Infra;
using SiteWatcher.Infra.Authorization;
using SiteWatcher.Infra.Authorization.Middleware;
namespace SiteWatcher.WebAPI;
public class Startup : IStartup
{
private readonly IConfiguration _configuration;
public IAppSettings AppSettings { get; set; }
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
// Add services to the container.
public void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
{
AppSettings = services.AddSettings(_configuration, env);
services.AddControllers(opts => opts.Filters.Add(typeof(CommandValidationFilter)))
.AddJsonOptions(opts => opts.JsonSerializerOptions.PropertyNamingPolicy = null)
.AddFluentValidation(opts =>
{
opts.AutomaticValidationEnabled = false;
opts.RegisterValidatorsFromAssemblyContaining<RegisterUserCommand>();
});
services.Configure<ApiBehaviorOptions>(opt => opt.SuppressModelStateInvalidFilter = true);
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.AddDataContext<SiteWatcherContext>();
services.AddRepositories();
services.AddDapperRepositories();
services.AddApplication();
services.AddRedisCache(AppSettings);
services.AddSessao()
.AddEmailService()
.AddFireAndForgetService();
services.ConfigureAuth(AppSettings);
services.AddHttpClient();
services.AddCors(options => {
options.AddPolicy(name: AppSettings.CorsPolicy,
builder =>
{
builder.WithOrigins(AppSettings.FrontEndUrl);
builder.AllowAnyHeader();
builder.WithMethods("OPTIONS", "GET", "POST", "PUT", "DELETE");
});
});
}
// Configure the HTTP request pipeline.
public void Configure(WebApplication app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
app.ConfigureGlobalExceptionHandlerMiddleware(env, loggerFactory);
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(opt =>
{
opt.SwaggerEndpoint("/swagger/v1/swagger.json", "SiteWatcher.WebAPI");
opt.RoutePrefix = "swagger";
});
}
app.UseCors(AppSettings.CorsPolicy);
app.UseHttpsRedirection();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
app.UseAuthentication();
// Session is instantiated first on authz handlers (AuthService) before the authz occurs
// This middleware ensures that the session has the correct auth info on authz handlers
// And through the request
app.UseMiddleware<MultipleJwtsMiddleware>();
app.UseAuthorization();
app.MapControllers();
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Alexa.NET;
using Alexa.NET.RequestHandlers;
using Alexa.NET.RequestHandlers.Handlers;
using Alexa.NET.Response;
namespace AlexaSamplePetMatch
{
public class ErrorHandler:AlwaysTrueErrorHandler
{
public override async Task<SkillResponse> Handle(RequestInformation information, Exception exception)
{
Console.WriteLine(exception.ToString());
return ResponseBuilder.Tell("So sorry, but something appears to have gone wrong");
}
}
}
|
@model PFCharacterSheetEditor.Models.CharacterSheet
@{
ViewBag.Title = "Home Page";
}
<div>
<h1 class="text-center">Pathfinder Character Sheet Editor</h1>
<p class="lead text-center">Easily generate PDFs of your pathfinder characters.</p>
</div>
<h5> Start by going to the Create page, or clicking the button below.</h5>
<hr />
<a href="/Home/Create" class="btn btn-lg btn-info" role="button">Create a new sheet</a>
<style>
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 100%;
}
</style> |
namespace SpaceStation.Core
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Contracts;
using Models.Astronauts;
using SpaceStation.Models.Astronauts.Contracts;
using Models.Mission;
using Models.Planets;
using Repositories;
using SpaceStation.Repositories.Contracts;
using Utilities.Messages;
public class Controller : IController
{
private readonly IRepository<IPlanet> planetRepository;
private readonly IRepository<IAstronaut> astronautRepository;
private readonly IMission mission;
private int exploredPlanetsCount;
public Controller()
{
this.planetRepository=new PlanetRepository();
this.astronautRepository=new AstronautRepository();
this.mission=new Mission();
this.exploredPlanetsCount = 0;
}
public string AddAstronaut(string type, string astronautName)
{
IAstronaut astronaut = null;
if (type == nameof(Biologist))
{
astronaut = new Biologist(astronautName);
}
else if (type == nameof(Geodesist))
{
astronaut = new Geodesist(astronautName);
}
else if (type == nameof(Meteorologist))
{
astronaut = new Meteorologist(astronautName);
}
else
{
throw new InvalidOperationException(ExceptionMessages.InvalidAstronautType);
}
this.astronautRepository.Add(astronaut);
return string.Format(OutputMessages.AstronautAdded, type, astronautName);
}
public string AddPlanet(string planetName, params string[] items)
{
IPlanet planet = new Planet(planetName);
foreach (var item in items)
{
planet.Items.Add(item);
}
this.planetRepository.Add(planet);
return string.Format(OutputMessages.PlanetAdded, planetName);
}
public string RetireAstronaut(string astronautName)
{
IAstronaut astronaut = this.astronautRepository.FindByName(astronautName);
if (astronaut==null)
{
throw new InvalidOperationException(ExceptionMessages.InvalidRetiredAstronaut);
}
this.astronautRepository.Remove(astronaut);
return string.Format(OutputMessages.AstronautRetired, astronautName);
}
public string ExplorePlanet(string planetName)
{
List<IAstronaut> suitableAstronauts = this.astronautRepository.Models.Where(a => a.Oxygen > 60).ToList();
if (suitableAstronauts.Count==0)
{
throw new InvalidOperationException(ExceptionMessages.InvalidAstronautCount);
}
IPlanet planet = this.planetRepository.FindByName(planetName);
mission.Explore(planet, suitableAstronauts);
this.exploredPlanetsCount++;
int deadAstronauts = suitableAstronauts.Count(a => !a.CanBreath);
return string.Format(OutputMessages.PlanetExplored, planetName, deadAstronauts);
}
public string Report()
{
var sb = new StringBuilder();
sb.AppendLine($"{this.exploredPlanetsCount} planets were explored!");
sb.AppendLine("Astronauts info:");
foreach (var astronaut in this.astronautRepository.Models)
{
sb.AppendLine($"Name: {astronaut.Name}");
sb.AppendLine($"Oxygen: {astronaut.Oxygen}");
sb.Append("Bag items: ");
if (astronaut.Bag.Items.Count==0)
{
sb.AppendLine("none");
}
else
{
sb.AppendLine(string.Join(", ",astronaut.Bag.Items));
}
}
return sb.ToString().TrimEnd();
}
}
}
|
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;
namespace Exentials.MdcBlazor
{
public partial class MdcIconButtonToggle : MdcButtonComponentBase
{
private bool _selected;
[CascadingParameter(Name = "MdcParentContainerType")] Type ParentContainerType { get; set; }
[Parameter] public string ToggleIcon { get; set; }
[Parameter]
public bool Selected
{
get { return _selected; }
set
{
if (_selected != value)
{
_selected = value;
if (SelectedChanged.HasDelegate)
{
SelectedChanged.InvokeAsync(_selected);
}
InvokeAsync(async () => await JsSetSelected(_selected));
}
}
}
[Parameter] public EventCallback<bool> SelectedChanged { get; set; }
protected override void OnInitialized()
{
base.OnInitialized();
if (ParentContainerType == typeof(MdcCardActions))
{
CssAttributes.Add("mdc-card__action");
CssAttributes.Add("mdc-card__action--icon");
}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
await JsSetSelected(Selected);
}
}
[JSInvokable("MDCIconButtonToggle:change")]
public ValueTask MDCIconButtonToggleChange(bool value)
{
Selected = value;
StateHasChanged();
return ValueTask.CompletedTask;
}
private ValueTask JsSetSelected(bool value)
{
return JsInvokeVoidAsync("setSelect", value);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetAmbSwitch : MonoBehaviour
{
[SerializeField] AK.Wwise.Switch ambSwitch;
private void OnTriggerEnter(Collider other)
{
ambSwitch.SetValue(GameObject.Find("WwiseHandler"));
}
}
|
using System;
using WebBackgrounder;
using Dal;
using System.Threading.Tasks;
namespace Solitude.Server
{
public class EventEndedJob : Job
{
public DatabaseAbstrationLayer Dal;
public EventEndedJob(string name, TimeSpan time, DatabaseAbstrationLayer dal) : base(name,time)
{
Dal = dal;
}
public override Task Execute()
{
return new Task(() =>
{
Dal.DeleteHeldEvents(DateTimeOffset.UtcNow);
});
}
}
}
|
using Newtonsoft.Json;
namespace CHC.Consent.Common.Infrastructure.Definitions
{
public interface IDefinition
{
string SystemName { get; }
IDefinitionType Type { get; }
[JsonIgnore]
string AsString { get; }
}
} |
using System.Collections.Generic;
using System.Linq;
using Manhasset.Core.src.Containers;
using Manhasset.Core.src.Generators;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Manhasset.Generator.src.CustomContainers
{
public class DefaultMethodContainer : BaseMethodContainer
{
public bool HasRequest { get; set; }
public override MethodDeclarationSyntax GetSyntax()
{
var syntax = base.GetSyntax();
var tryCatch = MethodGenerators.GetTryCatchBlock();
var methodBody = base.GetMethodBodyParams();
var returnStatement = new ApiCallReturnStatementContainer
{
Path = Path,
PathParams = PathParams,
QueryParams = QueryParams,
FileParams = FileParams,
FormParams = FormParams,
BodyParams = BodyParams,
HttpMethod = HttpMethod,
Returns = Returns,
EntityName = EntityName,
HasRequest = HasRequest,
IsVoidTask = IsVoidTask,
};
methodBody.Add(returnStatement.GetSyntax());
var block = SyntaxFactory.Block(methodBody.ToArray());
tryCatch = tryCatch.WithBlock(block);
syntax = syntax.WithBody(SyntaxFactory.Block(tryCatch));
return syntax;
}
}
} |
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using SharpFlame.Core.Extensions;
using SharpFlame.Core.Parsers.Lev2;
using SharpFlame.Core.Parsers.Lev2;
using Sprache;
namespace SharpFlame.Tests.Parser
{
[TestFixture]
public class Lev2ParserTests
{
[Test]
public void test()
{
var lineEnd = Parse.Return( "" ).End()
.XOr( Parse.String( "\r" ).Text() )
.Or( Parse.String( "\n" ).Text() )
.Or( Parse.String( "\r\n" ) );
var parser = Parse.String("//").Then(
_ => Parse.AnyChar.Until(lineEnd)).Text();
var result = parser.Parse("// foobar");
result.Should().Be(" foobar");
}
[Test]
public void can_parse_single_line_comment()
{
var data = @"// Made with SharpFlame 0.20 Windows";
var result = Lev2Grammar.SingleLineComment.Parse(data);
result.Should().Be(" Made with SharpFlame 0.20 Windows");
}
[Test]
public void can_parse_multi_line_comment()
{
var data = @"/** .foo. **/";
var result = Lev2Grammar.MultiLineComment.Parse( data );
result.Should().Be( "* .foo. *" );
}
[Test]
public void can_parse_campaign_directive()
{
var data = @"campaign MULTI_CAM_1
";
var result = Lev2Grammar.CampaingDirective.Parse(data);
result.Should().Be("MULTI_CAM_1");
}
[Test]
public void can_parse_data_driective()
{
var data = @"data ""wrf/basic.wrf""
";
var result = Lev2Grammar.DataDirective.Parse(data);
result.Should().Be("wrf/basic.wrf");
}
[Test]
public void can_parse_campaign_section()
{
var data = @"campaign MULTI_CAM_3
data ""wrf/vidmem3.wrf""
data ""wrf/basic.wrf""
data ""wrf/cam3.wrf""
data ""wrf/audio.wrf""
data ""wrf/piestats.wrf""
data ""wrf/stats.wrf""
data ""wrf/multires.wrf""
";
var result = Lev2Grammar.Campaign.Parse(data);
result.Data.Length.Should().Be(7);
result.Data[3].Should().Be("wrf/audio.wrf");
result.Name.Should().Be("MULTI_CAM_3");
}
[Test]
public void can_parse_level_directive()
{
var data = @"level Sk-Rush-T3
";
var result = Lev2Grammar.LevelDirective.Parse(data);
result.Should().Be("Sk-Rush-T3");
}
[Test]
public void can_parse_player_directive()
{
var data = @"players 4
";
var result = Lev2Grammar.PlayersDirective.Parse(data);
result.Should().Be(4);
}
[Test]
public void can_parse_type_directive()
{
var data = @"type 18
";
var result = Lev2Grammar.TypeDirective.Parse( data );
result.Should().Be( 18 );
}
[Test]
public void can_parse_dataset_directive()
{
var data = @"dataset MULTI_T2_C1
";
var result = Lev2Grammar.DatasetDirective.Parse(data);
result.Should().Be("MULTI_T2_C1");
}
[Test]
public void can_parse_game_directive()
{
var data = @"game ""multiplay/maps/4c-rush.gam""
";
var result = Lev2Grammar.GameDirective.Parse( data );
result.Should().Be( "multiplay/maps/4c-rush.gam" );
}
[Test]
public void can_parse_level_section()
{
var data = @"level Sk-Rush2-T2
players 4
type 18
dataset MULTI_T2_C1
game ""multiplay/maps/4c-rush2.gam""
";
var result = Lev2Grammar.Level.Parse(data);
result.Name.Should().Be("Sk-Rush2-T2");
result.Players.Should().Be(4);
result.Type.Should().Be(18);
result.Dataset.Should().Be("MULTI_T2_C1");
result.Game.Should().Be("multiplay/maps/4c-rush2.gam");
}
[Test]
public void can_parse_level_with_mutiple_game_directives()
{
var data = @"level Tinny-War-T3
players 2
type 19
dataset MULTI_T3_C1
game ""multiplay/maps/2c-Tinny-War.gam""
data ""wrf/multi/t3-skirmish2.wrf""
data ""wrf/multi/fog1.wrf""
";
var result = Lev2Grammar.Level.Parse( data );
result.Name.Should().Be( "Tinny-War-T3" );
result.Players.Should().Be( 2 );
result.Type.Should().Be( 19 );
result.Dataset.Should().Be( "MULTI_T3_C1" );
result.Game.Should().Be( "multiplay/maps/2c-Tinny-War.gam" );
result.Data[0].Should().Be( "wrf/multi/t3-skirmish2.wrf" );
result.Data[1].Should().Be( "wrf/multi/fog1.wrf" );
}
[Test]
public void can_parse_tinny_war_lev_file()
{
var data = @"// Made with SharpFlame 0.20 Windows
// Date: 2014/02/13 12:23:17
// Author: Unknown
// License: CC0
level Tinny-War-T1
players 2
type 14
dataset MULTI_CAM_1
game ""multiplay/maps/2c-Tinny-War.gam""
data ""wrf/multi/skirmish2.wrf""
data ""wrf/multi/fog1.wrf""
level Tinny-War-T2
players 2
type 18
dataset MULTI_T2_C1
game ""multiplay/maps/2c-Tinny-War.gam""
data ""wrf/multi/t2-skirmish2.wrf""
data ""wrf/multi/fog1.wrf""
level Tinny-War-T3
players 2
type 19
dataset MULTI_T3_C1
game ""multiplay/maps/2c-Tinny-War.gam""
data ""wrf/multi/t3-skirmish2.wrf""
data ""wrf/multi/fog1.wrf""
";
var result = Lev2Grammar.Lev.Parse(data);
result.Levels.Length.Should().Be(3);
result.Levels[1].Players.Should().Be(2);
result.Levels[0].Type.Should().Be( 14 );
result.Levels[1].Type.Should().Be( 18 );
result.Levels[2].Type.Should().Be( 19 );
result.Levels[0].Dataset.Should().Be( "MULTI_CAM_1" );
result.Levels[1].Dataset.Should().Be( "MULTI_T2_C1" );
result.Levels[2].Dataset.Should().Be( "MULTI_T3_C1" );
result.Levels[0].Name.Should().Be( "Tinny-War-T1" );
result.Levels[1].Name.Should().Be( "Tinny-War-T2" );
result.Levels[2].Name.Should().Be( "Tinny-War-T3" );
result.Levels[1].Data.Count().Should().Be( 2 );
result.Levels[1].Data[0].Should().Be( "wrf/multi/t2-skirmish2.wrf" );
}
[Test]
public void can_parse_addon_lev()
{
var file = "Data"
.CombinePathWith("Levels")
.CombinePathWith("addon.lev");
var txt = File.ReadAllText(file);
var levfile = Lev2Grammar.Lev.Parse(txt);
Console.WriteLine( "# of campaigns: {0}", levfile.Campaigns.Length );
Console.WriteLine( "# of levels: {0}", levfile.Levels.Length );
levfile.Campaigns.Length.Should().Be(9);
levfile.Levels.Length.Should().Be(114);
}
[Test]
[Explicit]
public void benchmark()
{
var file = "Data"
.CombinePathWith( "Levels" )
.CombinePathWith( "addon.lev" );
var txt = File.ReadAllText( file );
Console.WriteLine( "Parsing: {0}", file );
var s = new Stopwatch();
s.Start();
for( int i = 0; i < 1000; i++ )
{
Lev2Grammar.Lev.Parse( txt );
}
s.Stop();
Console.WriteLine( "Total Time: " + s.Elapsed );
//CPU: INTEL 3960X EE, 64GB RAM
//Total Time: 00:00:13.5444390
}
}
} |
using System;
using GamesToGo.Editor.Project.Arguments;
using JetBrains.Annotations;
namespace GamesToGo.Editor.Project.Events
{
[UsedImplicitly]
public class DrawCardOffTileEvent : ProjectEvent
{
public override int TypeID => 5;
public override EventSourceActivator Source => EventSourceActivator.SingleTile;
public override EventSourceActivator Activator => EventSourceActivator.SinglePlayer;
public override string[] Text => new[] { @"Al tomar una carta" };
public override ArgumentType[] ExpectedArguments => Array.Empty<ArgumentType>();
}
}
|
namespace MessageQueueManager.Interfaces
{
public interface IMessageQueueManager
{
bool SendMessage(string message);
string ReadMessage();
}
}
|
namespace SimplCommerce.Module.Catalog.Services.Dtos
{
public class ProductSettingDto
{
public decimal ConversionRate { get; set; }
public decimal FeeOfPicker { get; set; }
public decimal FeePerWeightUnit { get; set; }
}
} |
using System.Collections.Generic;
using WABA360Dialog.ApiClient.Payloads.Enums;
using WABA360Dialog.Common.Converters.Base;
namespace WABA360Dialog.ApiClient.Payloads.Converters
{
internal class ComponentTypeConverter : EnumConverter<ComponentType>
{
protected override ComponentType GetEnumValue(string value) =>
EnumStringConverter.GetComponentType(value);
protected override string GetStringValue(ComponentType value) =>
value.GetString();
}
public static partial class EnumStringConverter
{
private static readonly IReadOnlyDictionary<string, ComponentType> ComponentTypeStringToEnum =
new Dictionary<string, ComponentType>
{
{ "header", ComponentType.header },
{ "body", ComponentType.body },
{ "button", ComponentType.button },
};
private static readonly IReadOnlyDictionary<ComponentType, string> ComponentTypeEnumToString =
new Dictionary<ComponentType, string>
{
{ ComponentType.header, "header" },
{ ComponentType.body, "body" },
{ ComponentType.button, "button" },
};
public static string GetString(this ComponentType status) =>
ComponentTypeEnumToString.TryGetValue(status, out var stringValue)
? stringValue
: "unknown";
public static ComponentType GetComponentType(string status) =>
ComponentTypeStringToEnum.TryGetValue(status, out var enumValue)
? enumValue
: 0;
}
} |
using Business.Abstract;
using Business.Constants;
using Core.Utilities.Results;
using DataAccess.Abstract;
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace Business.Concrete
{
public class BidClientManager : IBidClientService
{
IBidClientDal _bidClientDal;
public BidClientManager(IBidClientDal bidClientDal)
{
_bidClientDal = bidClientDal;
}
public IResult Add(BidClient bidClient)
{
_bidClientDal.Add(bidClient);
return new SuccessResult(Messages.Added);
}
public IResult Delete(BidClient bidClient)
{
_bidClientDal.Delete(bidClient);
return new SuccessResult(Messages.Deleted);
}
public IDataResult<BidClient> GetById(int bidId)
{
return new SuccessDataResult<BidClient>(_bidClientDal.Get(b => b.BidClientId == bidId));
}
public IResult Update(BidClient bidClient)
{
_bidClientDal.Update(bidClient);
return new SuccessResult(Messages.Updated);
}
DataResult<List<BidClient>> IBidClientService.GetAll()
{
throw new NotImplementedException();
}
DataResult<BidClient> IBidClientService.GetById(int bidClientId)
{
throw new NotImplementedException();
}
}
}
|
using System;
using OpenTK.Graphics.OpenGL4;
using OpenTK.Platform;
using OpenTK.Platform.Windows;
using OpenTkWPFHost.Abstraction;
using OpenTkWPFHost.Configuration;
using OpenTkWPFHost.Core;
namespace OpenTkWPFHost.DirectX
{
///Renderer that uses DX_Interop for a fast-path.
public class DXProcedure : IRenderProcedure, IRenderBuffer
{
private DxGlContext _context;
private DxGLFramebuffer _frameBuffer => _frameBuffers.GetBackBuffer();
public bool EnableFlush { get; set; } = true;
/// The OpenGL framebuffer handle.
public int FrameBufferHandle => _frameBuffer?.GLFramebufferHandle ?? 0;
public bool IsInitialized { get; private set; }
private readonly GenericMultiBuffer<DxGLFramebuffer> _frameBuffers;
public void Swap()
{
_frameBuffers.Swap();
}
public IRenderCanvas CreateCanvas()
{
return new MultiDxCanvas();
}
public IRenderBuffer CreateRenderBuffer()
{
return this;
}
public DXProcedure()
{
_frameBuffers = new GenericMultiBuffer<DxGLFramebuffer>(3);
}
/// Sets up the framebuffer, directx stuff for rendering.
public void PreRender()
{
Wgl.DXLockObjectsNV(_context.GlDeviceHandle, 1, new[] {_frameBuffer.DxInteropRegisteredHandle});
GL.BindFramebuffer(FramebufferTarget.Framebuffer, _frameBuffer.GLFramebufferHandle);
}
/// Sets up the framebuffer and prepares stuff for usage in directx.
public RenderArgs PostRender()
{
GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
Wgl.DXUnlockObjectsNV(_context.GlDeviceHandle, 1, new[] {_frameBuffer.DxInteropRegisteredHandle});
if (EnableFlush)
{
GL.Flush();
}
return new DXRenderArgs(_renderTargetInfo, _frameBuffer.DxRenderTargetHandle);
}
public GLContextBinding Initialize(IWindowInfo window, GLSettings settings)
{
if (IsInitialized)
{
throw new NotSupportedException("Initialized already!");
}
_context = new DxGlContext(settings, window);
IsInitialized = true;
return new GLContextBinding(_context.GraphicsContext, window);
}
private RenderTargetInfo _renderTargetInfo;
public void Apply(RenderTargetInfo renderTarget)
{
this._renderTargetInfo = renderTarget;
var renderTargetPixelSize = renderTarget.PixelSize;
_frameBuffers.Instantiate((i, d) =>
{
d?.Release();
return new DxGLFramebuffer(_context, renderTargetPixelSize);
});
_frameBuffers.Swap();
}
public void Dispose()
{
_frameBuffers.ForEach(((i, frameBuffer) => frameBuffer.Release()));
_context?.Dispose();
}
public FrameArgs ReadFrames(RenderArgs args)
{
return new DXFrameArgs(((DXRenderArgs) args).RenderTargetIntPtr, args.TargetInfo);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class EndMessage : MonoBehaviour
{
public Score score;
public Text endMessage;
public Text scoreMessage;
public Button menuButton;
public Button exitButton;
public AudioSource buttonSound;
private TextFade messageFade;
private TextFade scoreFade;
private enum ButtonPress
{
menu, exit, none
}
private ButtonPress buttonPressed;
public bool displayed
{
get { return messageFade.Faded();}
}
void Start ()
{
messageFade = endMessage.GetComponent<TextFade>();
scoreFade = scoreMessage.GetComponent<TextFade>();
menuButton.onClick.AddListener(MenuButtonClicked);
exitButton.onClick.AddListener(ExitButtonClicked);
menuButton.gameObject.SetActive(false);
exitButton.gameObject.SetActive(false);
buttonPressed = ButtonPress.none;
}
// Update is called once per frame
void Update ()
{
if(messageFade.Faded())
{
messageFade.StopFade();
scoreFade.StopFade();
menuButton.gameObject.SetActive(true);
exitButton.gameObject.SetActive(true);
}
if (buttonPressed != ButtonPress.none && !buttonSound.isPlaying)
{
switch (buttonPressed)
{
case ButtonPress.menu:
SceneManager.LoadScene("Menu");
break;
case ButtonPress.exit:
Application.Quit();
break;
}
}
}
public void display(bool won)
{
scoreMessage.text = "score: "+ score.scoreVal;
if (won)
endMessage.text = "You Made It Home";
else
endMessage.text = "You Crashed";
messageFade.Fade();
scoreFade.Fade();
}
void MenuButtonClicked()
{
buttonPressed = ButtonPress.menu;
buttonSound.Play();
}
void ExitButtonClicked()
{
buttonPressed = ButtonPress.exit;
buttonSound.Play();
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using LoggerService;
using Contracts;
namespace NetCoreApi_BoilerPlate
{
public static class ServiceExtensions{
public static string CorsAnyPolicy = "CorsAnyPolicy";
public static string CorsWithPolicy = "CorsWithPolicy";
/// <summary>
/// This method is to configure CORS with any domain any method and any header
/// </summary>
/// <param name="services"></param>
public static void ConfigureAnyCors(this IServiceCollection services ) =>
services.AddCors(options => {
options.AddPolicy(CorsAnyPolicy, builder =>
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
/// <summary>
/// This method is to finest CORS configuration
/// </summary>
/// <param name="services"></param>
public static void ConfigureWithCors(this IServiceCollection services ) =>
services.AddCors(options => {
options.AddPolicy(CorsWithPolicy, builder =>
builder.WithOrigins("http://wwww.google.com")
.WithMethods("POST")
.WithExposedHeaders("x-custom-header")
.WithHeaders("x-custom-header"));
});
public static void ConfigureIISIntegration(this IServiceCollection services) =>
services.Configure<IISOptions>(options =>{
});
public static void ConfigureLoggerService(this IServiceCollection services) =>
services.AddScoped<ILoggerManager,LoggerManager>();
}
} |
using Cysharp.Threading.Tasks;
using UnityEngine;
[CreateAssetMenu(fileName = "player prefs storage service", menuName = "App/Services/PlayerPrefsStorage")]
public class PlayerPrefsStorageService : StorageService {
/// <summary>
/// Save string data.
/// </summary>
/// <param name="key">data key.</param>
/// <param name="data">data</param>
/// <returns>Did overwrite value</returns>
public override async UniTask<bool> SaveAsync(string key, string data) {
bool hasKey = PlayerPrefs.HasKey(key);
PlayerPrefs.SetString(key, data);
return await UniTask.FromResult(hasKey);
}
/// <summary>
/// Load string data.
/// </summary>
/// <param name="key">storage key</param>
/// <returns>Value from key. Empty string if value does not exist.</returns>
public override async UniTask<string> LoadAsync(string key) {
string data = PlayerPrefs.GetString(key);
return await UniTask.FromResult(data);
}
/// <summary>
/// Delete data.
/// </summary>
/// <param name="key">data key.</param>
public override UniTask DeleteAsync(string key) {
PlayerPrefs.DeleteKey(key);
return UniTask.CompletedTask;
}
} |
namespace Quadspace.TBP.Messages {
public class TbpBotMessage {
public BotMessageType type;
}
} |
// ReSharper disable UnusedTypeParameter
namespace CopperCowEngine.ECS
{
public abstract class Required { }
public abstract class Required<T> : Required
where T : struct, IComponentData { }
public abstract class Required<T1, T2> : Required
where T1 : struct, IComponentData
where T2 : struct, IComponentData { }
public abstract class Required<T1, T2, T3> : Required
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData { }
public abstract class Required<T1, T2, T3, T4> : Required
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData
where T4 : struct, IComponentData
{ }
public abstract class Required<T1, T2, T3, T4, T5> : Required
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData
where T4 : struct, IComponentData
where T5 : struct, IComponentData
{ }
public abstract class Optional { }
public abstract class Optional<T> : Optional
where T : struct, IComponentData
{ }
public abstract class Optional<T1, T2> : Optional
where T1 : struct, IComponentData
where T2 : struct, IComponentData
{ }
public abstract class Optional<T1, T2, T3> : Optional
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData
{ }
public abstract class Optional<T1, T2, T3, T4> : Optional
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData
where T4 : struct, IComponentData
{ }
public abstract class Optional<T1, T2, T3, T4, T5> : Optional
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData
where T4 : struct, IComponentData
where T5 : struct, IComponentData
{ }
public abstract class Excepted { }
public abstract class Excepted<T> : Excepted
where T : struct, IComponentData
{ }
public abstract class Excepted<T1, T2> : Excepted
where T1 : struct, IComponentData
where T2 : struct, IComponentData
{ }
public abstract class Excepted<T1, T2, T3> : Excepted
where T1 : struct, IComponentData
where T2 : struct, IComponentData
where T3 : struct, IComponentData
{ }
}
|
using System.Collections.Generic;
namespace Diesel.Parsing
{
public class ApplicationServiceDeclaration : TypeDeclaration
{
public IEnumerable<CommandDeclaration> Commands { get; private set; }
public ApplicationServiceDeclaration(string name, IEnumerable<CommandDeclaration> commands)
: base(name)
{
Commands = commands;
}
public override IEnumerable<ITreeNode> Children
{
get { return Commands; }
}
public override void Accept(ITypeDeclarationVisitor visitor)
{
visitor.Visit(this);
}
}
public abstract class TypeDeclaration : ITypeDeclaration
{
public string Name { get; private set; }
protected TypeDeclaration(string name)
{
Name = name;
}
public abstract IEnumerable<ITreeNode> Children { get; }
public void Accept(IDieselExpressionVisitor visitor)
{
Accept((ITypeDeclarationVisitor) visitor);
}
public abstract void Accept(ITypeDeclarationVisitor visitor);
}
} |
using System;
namespace DevAge.Patterns
{
/// <summary>
/// Exception fired when canceling an activity with the Cancel method.
/// </summary>
[Serializable]
public class ActivityCanceledException : DevAgeApplicationException
{
/// <summary>
/// Constructor
/// </summary>
public ActivityCanceledException():
base("Activity canceled.")
{
}
}
/// <summary>
/// Exception fired when canceling an activity with the Cancel method.
/// </summary>
[Serializable]
public class ActivityStatusNotValidException : DevAgeApplicationException
{
/// <summary>
/// Constructor
/// </summary>
public ActivityStatusNotValidException():
base("Activity status not valid.")
{
}
}
/// <summary>
/// Exception fired when a time out is encountered.
/// </summary>
[Serializable]
public class TimeOutActivityException : DevAgeApplicationException
{
/// <summary>
/// Constructor
/// </summary>
public TimeOutActivityException():
base("Activity timeout.")
{
}
}
/// <summary>
/// Exception fired when a time out is encountered.
/// </summary>
[Serializable]
public class SubActivityException : DevAgeApplicationException
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="activityName"></param>
/// <param name="innerException"></param>
public SubActivityException(string activityName, Exception innerException):
base("The activity " + activityName + " throwed an exception, " + innerException.Message, innerException)
{
}
}
}
|
@{
ViewData["Title"] = "Roles";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using System.Security.Claims
<script type="text/javascript">
$(document).ready(function () {
$('.create-role-view').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '@Url.Action("CreateRoleView", "Roles")',
success: function (result) {
$('#createRoleView').html(result);
}
});
});
$('.assign-role-view').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '@Url.Action("AssignRoleView", "Roles")',
success: function (result) {
$('#assignRoleView').html(result);
}
});
});
});
</script>
<h3>Roles</h3>
<br />
@foreach (var role in Model)
{
<p>@role.Name</p>
}
<div class="list-card">
<button class="create-role-view">Create role</button>
<button class="assign-role-view">Assign role</button>
<div id="createRoleView"></div>
<div id="assignRoleView"></div>
</div>
<hr />
<p>@Html.ActionLink("Go to Account", "Index", "Account")</p>
<p>@Html.ActionLink("Go to Items", "Index", "Items")</p>
<p>@Html.ActionLink("Go to Cart", "Index", "Sales")</p>
p>@Html.ActionLink("Go to Commission", "Index", "Commission")</p> |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Windows.UI.Xaml;
namespace Microsoft.UI.Xaml.Controls
{
public partial class ItemsRepeaterElementIndexChangedEventArgs
{
internal ItemsRepeaterElementIndexChangedEventArgs(
UIElement element,
int oldIndex,
int newIndex)
{
Update(element, oldIndex, newIndex);
}
#region IElementPreparedEventArgs
public UIElement Element { get; private set; }
public int OldIndex { get; private set; }
public int NewIndex { get; private set; }
#endregion
public void Update(UIElement element, in int oldIndex, in int newIndex)
{
Element = element;
OldIndex = oldIndex;
NewIndex = newIndex;
}
}
}
|
using System;
using System.Reflection;
using Glass.Mapper.Pipelines.DataMapperResolver;
using NUnit.Framework;
using Glass.Mapper.Configuration;
using Glass.Mapper.Diagnostics;
using Glass.Mapper.IoC;
using Glass.Mapper.Pipelines.ObjectConstruction;
using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateInterface;
using NSubstitute;
namespace Glass.Mapper.Tests
{
[TestFixture]
public class ContextFixture
{
[TearDown]
public void TearDown()
{
Context.Clear();
}
[SetUp]
public void Setup()
{
}
#region Create
[Test]
public void Create_CreateContext_CanGetContextFromContextDictionary()
{
//Assign
string contextName = "testContext";
bool isDefault = false;
Context.Clear();
//Act
Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault);
//Assert
Assert.IsTrue(Context.Contexts.ContainsKey(contextName));
Assert.IsNotNull(Context.Contexts[contextName]);
Assert.IsNull(Context.Default);
}
[Test]
public void Create_LoadContextAsDefault_CanGetContextFromContextDictionary()
{
//Assign
string contextName = "testContext";
bool isDefault = true;
//Act
Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault);
//Assert
Assert.IsTrue(Context.Contexts.ContainsKey(contextName));
Assert.IsNotNull(Context.Contexts[contextName]);
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[contextName], Context.Default);
}
[Test]
public void Create_LoadContextAsDefault_CanGetContextFromContextDictionaryUsingDefault()
{
//Assign
//Act
Context.Create(Substitute.For<IDependencyResolver>());
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
}
#endregion
#region Load
[Test]
public void Load_LoadContextWithTypeConfigs_CanGetTypeConfigsFromContext()
{
//Assign
var loader1 = Substitute.For<IConfigurationLoader>();
var config1 = Substitute.For<AbstractTypeConfiguration>();
config1.Type = typeof (StubClass1);
loader1.Load().Returns(new[]{config1});
var loader2 = Substitute.For<IConfigurationLoader>();
var config2 = Substitute.For<AbstractTypeConfiguration>();
config2.Type = typeof(StubClass2);
loader2.Load().Returns(new[] { config2 });
//Act
var context = Context.Create(Substitute.For<IDependencyResolver>());
context.Config = new Config();
context.Load(loader1, loader2);
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
Assert.AreEqual(config1, Context.Default.TypeConfigurations[config1.Type]);
Assert.AreEqual(config2, Context.Default.TypeConfigurations[config2.Type]);
}
/// <summary>
/// From issue https://github.com/mikeedwards83/Glass.Mapper/issues/85
/// </summary>
[Test]
public void Load_LoadContextWithGenericType_CanGetTypeConfigsFromContext()
{
//Assign
var loader1 = Substitute.For<IConfigurationLoader>();
var config1 = Substitute.For<AbstractTypeConfiguration>();
config1.Type = typeof(Sample);
loader1.Load().Returns(new[] { config1 });
//Act
var context = Context.Create(Substitute.For<IDependencyResolver>());
context.Config = new Config();
context.Load(loader1);
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
Assert.AreEqual(config1, Context.Default.TypeConfigurations[config1.Type]);
}
/// <summary>
/// From issue https://github.com/mikeedwards83/Glass.Mapper/issues/85
/// </summary>
[Test]
public void Load_LoadContextGenericType_GenericTypeNotCreated()
{
//Assign
var loader1 = Substitute.For<IConfigurationLoader>();
var config1 = new StubAbstractTypeConfiguration();
config1.Type = typeof(Generic<>);
config1.AutoMap = true;
loader1.Load().Returns(new[] { config1 });
//Act
var context = Context.Create(Substitute.For<IDependencyResolver>());
context.Config = new Config();
context.Load(loader1);
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
Assert.IsFalse(Context.Default.TypeConfigurations.ContainsKey(config1.Type));
}
/// <summary>
/// From issue https://github.com/mikeedwards83/Glass.Mapper/issues/85
/// </summary>
[Test]
public void Load_LoadContextDerivedFromGenericType_CanGetTypeConfigsFromContext()
{
//Assign
var loader1 = Substitute.For<IConfigurationLoader>();
var config1 = new StubAbstractTypeConfiguration();
config1.Type = typeof(Sample);
config1.AutoMap = true;
loader1.Load().Returns(new[] { config1 });
var resolver = Substitute.For<IDependencyResolver>();
//Act
var context = Context.Create(resolver);
context.Config = new Config();
context.Load(loader1);
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
Assert.IsTrue(Context.Default.TypeConfigurations.ContainsKey(config1.Type));
}
#endregion
#region Indexers
[Test]
public void Indexer_UseTypeIndexerWithValidConfig_ReturnsTypeConfiguration()
{
//Assign
var loader1 = Substitute.For<IConfigurationLoader>();
var config1 = Substitute.For<AbstractTypeConfiguration>();
config1.Type = typeof(StubClass1);
loader1.Load().Returns(new[] { config1 });
//Act
var context = Context.Create(Substitute.For<IDependencyResolver>());
context.Config = new Config();
context.Load(loader1);
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
Assert.AreEqual(config1, Context.Default[config1.Type]);
}
[Test] public void Indexer_UseTypeIndexerWithInvalidConfig_ReturnsNull()
{
//Assign
var loader1 = Substitute.For<IConfigurationLoader>();
//Act
var context = Context.Create(Substitute.For<IDependencyResolver>());
context.Config = new Config();
context.Load(loader1);
//Assert
Assert.IsNotNull(Context.Default);
Assert.AreEqual(Context.Contexts[Context.DefaultContextName], Context.Default);
Assert.IsNull( Context.Default[typeof(StubClass1)]);
}
#endregion
#region GetTypeConfiguration
[Test]
public void GetTypeConfiguration_BaseTypeNullForInterface_AutoLoadsConfig()
{
//Arrange
string contextName = "testContext";
bool isDefault = true;
var type = typeof (IStubInterface1);
Context.Create(Substitute.For<IDependencyResolver>(), contextName, isDefault);
var context = Context.Contexts[contextName];
context.Config = new Config();
//Act
var config = context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(type);
//Assert
Assert.IsNotNull(config);
}
[Test]
public void GetTypeConfiguration_TwoInterfacesWithTheSameNameUsingCastleProxy_ReturnsEachCorrectly()
{
//Arrange
string contextName = "testContext";
bool isDefault = true;
var type = typeof (NS1.ProxyTest1);
var service = Substitute.For<IAbstractService>();
var task = new CreateInterfaceTask(new LazyLoadingHelper());
#region CreateTypes
Context context = Context.Create(Substitute.For<IDependencyResolver>());
context.Config = new Config();
AbstractTypeCreationContext abstractTypeCreationContext1 = new TestTypeCreationContext();
abstractTypeCreationContext1.Options = new TestGetOptions()
{
Type = typeof(NS1.ProxyTest1)
};
var configuration1 = Substitute.For<AbstractTypeConfiguration>();
configuration1.Type = typeof(NS1.ProxyTest1);
ObjectConstructionArgs args1 = new ObjectConstructionArgs(context, abstractTypeCreationContext1, configuration1, service);
AbstractTypeCreationContext abstractTypeCreationContext2 = new TestTypeCreationContext();
abstractTypeCreationContext2.Options = new TestGetOptions()
{
Type = typeof(NS2.ProxyTest1)
};
var configuration2 = Substitute.For<AbstractTypeConfiguration>();
configuration2.Type = typeof(NS2.ProxyTest1);
ObjectConstructionArgs args2 = new ObjectConstructionArgs(context, abstractTypeCreationContext2, configuration2, service);
//Act
task.Execute(args1);
task.Execute(args2);
#endregion
context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(typeof(NS1.ProxyTest1));
context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(typeof(NS2.ProxyTest1));
//Act
var config1 = context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(args1.Result.GetType());
var config2 = context.GetTypeConfigurationFromType<StubAbstractTypeConfiguration>(args2.Result.GetType());
//Assert
Assert.AreEqual(typeof(NS1.ProxyTest1), config1.Type);
Assert.AreEqual(typeof(NS2.ProxyTest1), config2.Type);
}
#endregion
#region Stubs
public class StubAbstractDataMappingContext : AbstractDataMappingContext
{
public StubAbstractDataMappingContext(object obj, GetOptions options)
: base(obj, options)
{
}
}
public class TestTypeCreationContext : AbstractTypeCreationContext
{
public override bool CacheEnabled { get; }
public override AbstractDataMappingContext CreateDataMappingContext(object obj)
{
return new StubAbstractDataMappingContext(obj, Options);
}
}
public interface IStubInterface1
{
}
public class StubClass1
{
}
public class StubClass2
{
}
#region ISSUE 85
public class ItemBase
{
public virtual Guid ItemId { get; set; }
}
public abstract class Generic<T> : ItemBase
{
public T Value { get; set; }
public string Text { get; set; }
}
public class Sample : Generic<string>
{
public string Title { get; set; }
}
#endregion
public class StubAbstractDataMapper : AbstractDataMapper
{
public Func<AbstractPropertyConfiguration, bool> CanHandleFunction { get; set; }
public override bool CanHandle(AbstractPropertyConfiguration configuration, Context context)
{
return CanHandleFunction(configuration);
}
public override void MapToCms(AbstractDataMappingContext mappingContext)
{
throw new NotImplementedException();
}
public override object MapToProperty(AbstractDataMappingContext mappingContext)
{
throw new NotImplementedException();
}
public override void Setup(DataMapperResolverArgs args)
{
throw new NotImplementedException();
}
}
public class StubAbstractTypeConfiguration : AbstractTypeConfiguration
{
protected override AbstractPropertyConfiguration AutoMapProperty(PropertyInfo property)
{
var config = new StubAbstractPropertyConfiguration();
config.PropertyInfo = property;
config.Mapper = new StubAbstractDataMapper();
return config;
}
}
public class StubAbstractPropertyConfiguration : AbstractPropertyConfiguration {
protected override AbstractPropertyConfiguration CreateCopy()
{
throw new NotImplementedException();
}
}
#endregion
}
namespace NS1
{
public interface ProxyTest1 { }
}
namespace NS2
{
public interface ProxyTest1 { }
}
}
|
// <auto-generated>
// Auto-generated by StoneAPI, do not modify.
// </auto-generated>
namespace Dropbox.Api.Sharing
{
using sys = System;
using col = System.Collections.Generic;
using re = System.Text.RegularExpressions;
using enc = Dropbox.Api.Stone;
/// <summary>
/// <para>Whether the user is allowed to take the action on the associated member.</para>
/// </summary>
public class MemberPermission
{
#pragma warning disable 108
/// <summary>
/// <para>The encoder instance.</para>
/// </summary>
internal static enc.StructEncoder<MemberPermission> Encoder = new MemberPermissionEncoder();
/// <summary>
/// <para>The decoder instance.</para>
/// </summary>
internal static enc.StructDecoder<MemberPermission> Decoder = new MemberPermissionDecoder();
/// <summary>
/// <para>Initializes a new instance of the <see cref="MemberPermission" />
/// class.</para>
/// </summary>
/// <param name="action">The action that the user may wish to take on the
/// member.</param>
/// <param name="allow">True if the user is allowed to take the action.</param>
/// <param name="reason">The reason why the user is denied the permission. Not present
/// if the action is allowed</param>
public MemberPermission(MemberAction action,
bool allow,
PermissionDeniedReason reason = null)
{
if (action == null)
{
throw new sys.ArgumentNullException("action");
}
this.Action = action;
this.Allow = allow;
this.Reason = reason;
}
/// <summary>
/// <para>Initializes a new instance of the <see cref="MemberPermission" />
/// class.</para>
/// </summary>
/// <remarks>This is to construct an instance of the object when
/// deserializing.</remarks>
public MemberPermission()
{
}
/// <summary>
/// <para>The action that the user may wish to take on the member.</para>
/// </summary>
public MemberAction Action { get; protected set; }
/// <summary>
/// <para>True if the user is allowed to take the action.</para>
/// </summary>
public bool Allow { get; protected set; }
/// <summary>
/// <para>The reason why the user is denied the permission. Not present if the action
/// is allowed</para>
/// </summary>
public PermissionDeniedReason Reason { get; protected set; }
#region Encoder class
/// <summary>
/// <para>Encoder for <see cref="MemberPermission" />.</para>
/// </summary>
private class MemberPermissionEncoder : enc.StructEncoder<MemberPermission>
{
/// <summary>
/// <para>Encode fields of given value.</para>
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public override void EncodeFields(MemberPermission value, enc.IJsonWriter writer)
{
WriteProperty("action", value.Action, writer, Dropbox.Api.Sharing.MemberAction.Encoder);
WriteProperty("allow", value.Allow, writer, enc.BooleanEncoder.Instance);
if (value.Reason != null)
{
WriteProperty("reason", value.Reason, writer, Dropbox.Api.Sharing.PermissionDeniedReason.Encoder);
}
}
}
#endregion
#region Decoder class
/// <summary>
/// <para>Decoder for <see cref="MemberPermission" />.</para>
/// </summary>
private class MemberPermissionDecoder : enc.StructDecoder<MemberPermission>
{
/// <summary>
/// <para>Create a new instance of type <see cref="MemberPermission" />.</para>
/// </summary>
/// <returns>The struct instance.</returns>
protected override MemberPermission Create()
{
return new MemberPermission();
}
/// <summary>
/// <para>Set given field.</para>
/// </summary>
/// <param name="value">The field value.</param>
/// <param name="fieldName">The field name.</param>
/// <param name="reader">The json reader.</param>
protected override void SetField(MemberPermission value, string fieldName, enc.IJsonReader reader)
{
switch (fieldName)
{
case "action":
value.Action = Dropbox.Api.Sharing.MemberAction.Decoder.Decode(reader);
break;
case "allow":
value.Allow = enc.BooleanDecoder.Instance.Decode(reader);
break;
case "reason":
value.Reason = Dropbox.Api.Sharing.PermissionDeniedReason.Decoder.Decode(reader);
break;
default:
reader.Skip();
break;
}
}
}
#endregion
}
}
|
using aspnet_demo_server.Controllers.HealthChecks;
using aspnet_demo_server.Filters;
using aspnet_demo_server.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Serilog;
using Serilog.Events;
namespace aspnet_demo_server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddControllers(options =>
options.Filters.Add(new ExceptionFilter()))
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
})
;
services.AddHttpClient();
services.AddHealthChecks()
.AddCheck<SimpleHealthCheck>("simple")
;
services
.AddSingleton<IPlantManager, PlantManager>()
;
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {Title = "aspnet-demo-server", Version = "v1"});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime appLifetime)
{
appLifetime.ApplicationStopping.Register(ApplicationStopping);
appLifetime.ApplicationStopped.Register(ApplicationStopped);
app.UseSerilogRequestLogging(options =>
{
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
};
options.GetLevel = (ctx, d, ex) =>
{
return ctx.Response.StatusCode switch
{
_ when ex != null => LogEventLevel.Error,
_ when ctx.GetEndpoint()?.DisplayName == "Health checks" => LogEventLevel.Verbose,
> 499 => LogEventLevel.Error,
_ => LogEventLevel.Information,
};
};
});
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseHsts();
app.UseRouting();
app.UseAuthorization();
app.UseCors(builder => builder.WithOrigins("*").AllowAnyHeader());
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "aspnet-demo-server v1"));
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHealthChecks("/health");
});
}
private void ApplicationStopping()
{
Log.Information("Graceful shutdown in progress");
}
private void ApplicationStopped()
{
Log.Information("Graceful shutdown completed");
}
}
}
|
namespace Firefly.CloudFormationParser.GraphObjects
{
using Firefly.CloudFormationParser.TemplateObjects;
using QuikGraph.Graphviz.Dot;
/// <summary>
/// Graph vertex that represents a template parameter
/// </summary>
/// <seealso cref="Firefly.CloudFormationParser.GraphObjects.AbstractVertex" />
public class ParameterVertex : AbstractVertex, IParameterVertex
{
/// <summary>
/// Initializes a new instance of the <see cref="ParameterVertex"/> class.
/// </summary>
/// <param name="templateObject">The template object.</param>
public ParameterVertex(ITemplateObject templateObject)
: base(templateObject)
{
}
/// <inheritdoc />
public override GraphvizVertexShape Shape => GraphvizVertexShape.Diamond;
}
} |
using UnityEngine;
namespace BUCK.AudioManagement.SFX
{
/// <inheritdoc />
[AddComponentMenu("Audio/SFX Controller")]
public class SFXController : BaseSFXController<SFXClip>
{
}
}
|
using System.Management.Automation;
using System.Threading;
using System.Threading.Tasks;
namespace PSAsync.Command
{
public abstract class AsyncCmdlet :
Cmdlet,
IAsyncCmdlet
{
protected override void BeginProcessing()
{
}
protected override void ProcessRecord()
{
if (!this.IsOverridden(nameof(this.ProcessRecordAsync)))
{
return;
}
this.ExecuteAsyncMethod((c, t) => c.ProcessRecordAsync(t));
}
protected override void EndProcessing()
{
}
private bool IsOverridden(
string methodName)
{
var method = this.GetType().GetMethod(
nameof(this.ProcessRecordAsync),
new[] { typeof(CancellationToken) });
return method.DeclaringType != typeof(AsyncCmdlet);
}
public virtual Task ProcessRecordAsync(
CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
|
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace Cympatic.Extensions.Http.Interfaces
{
public interface IApiServiceResult
{
HttpStatusCode StatusCode { get; }
string ReasonPhrase { get; }
HttpResponseHeaders ResponseHeaders { get; }
HttpContentHeaders ContentHeaders { get; }
string Content { get; }
bool IsSuccessStatusCode { get; }
Task InitializeAsync(HttpResponseMessage response, CancellationToken cancellationToken = default);
}
}
|
using UnityEngine;
using XNodeEditor;
using PaperStag.FSM;
namespace PaperStag.Editor
{
[CustomNodeGraphEditor(typeof(FSMGraph))]
public class FSMGraphEditor : NodeGraphEditor
{
public override void OnOpen()
{
base.OnOpen();
window.titleContent = new GUIContent("FSM");
}
public override string GetNodeMenuName(System.Type type)
{
if (type.Namespace == "PaperStag.FSM")
{
return type.Name;
}
else
{
return null;
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.Common.Core.Imaging;
using Microsoft.Common.Core.Services;
using Microsoft.UnitTests.Core.XUnit;
using Xunit;
namespace Microsoft.VisualStudio.R.Package.Test.Images {
[ExcludeFromCodeCoverage]
[Category.Project.Services]
[Collection(CollectionNames.NonParallel)]
public class ImageServiceTest {
private readonly IServiceContainer _services;
public ImageServiceTest(IServiceContainer services) {
_services = services;
}
[Test]
public void Test01() {
var service = _services.GetService<IImageService>();
service.Should().NotBeNull();
service.GetFileIcon("foo.R").Should().NotBeNull();
service.GetFileIcon("foo.rproj").Should().NotBeNull();
service.GetFileIcon("foo.rdata").Should().NotBeNull();
service.GetFileIcon("foo.rd").Should().NotBeNull();
service.GetFileIcon("foo.rmd").Should().NotBeNull();
service.GetFileIcon("foo.sql").Should().NotBeNull();
service.GetImage("RProjectNode").Should().NotBeNull();
service.GetImage("RFileNode").Should().NotBeNull();
service.GetImage("RDataFileNode").Should().NotBeNull();
service.GetImage("RdFileNode").Should().NotBeNull();
service.GetImage("RMdFileNode").Should().NotBeNull();
service.GetImage("SQLFileNode").Should().NotBeNull();
service.GetImage("ProcedureFileNode").Should().NotBeNull();
}
}
}
|
namespace Rook.Framework.Api {
public interface IApiService
{
void Start();
}
} |
using System.Threading;
using Stackage.Aws.Lambda.Abstractions;
namespace Stackage.Aws.Lambda.Middleware
{
public class DeadlineCancellation : IDeadlineCancellation, IDeadlineCancellationInitializer
{
public CancellationToken Token { get; private set; }
public void Initialize(CancellationToken token)
{
Token = token;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Torque3D.Engine.Util.Enums
{
[Flags]
public enum ObjectTypes
{
/// Default value for type masks.
DefaultObjectType = 0,
/// @}
/// @name Basic Engine Types
/// @{
/// Any kind of SceneObject that is not supposed to change transforms
/// except during editing (or not at all).
StaticObjectType = 1,
/// Environment objects such as clouds, skies, forests, etc.
EnvironmentObjectType = 1 << 1,
/// A terrain object.
/// @see TerrainBlock
TerrainObjectType = 1 << 2,
/// An object defining a water volume.
/// @see WaterObject
WaterObjectType = 1 << 3,
/// An object defining an invisible trigger volume.
/// @see Trigger
TriggerObjectType = 1 << 4,
/// An object defining an invisible marker.
/// @see MissionMarker
MarkerObjectType = 1 << 5,
/// A light emitter.
/// @see LightBase
LightObjectType = 1 << 6,
/// An object that manages zones. This is automatically set by
/// SceneZoneSpaceManager when a SceneZoneSpace registers zones. Should
/// not be manually set.
///
/// @see SceneZoneSpace
/// @see SceneZoneSpaceManager
ZoneObjectType = 1 << 7,
/// Any object that defines one or more solid, renderable static geometries that
/// should be included in collision and raycasts.
///
/// Use this mask to find objects that are part of the static level geometry.
///
/// @note If you set this, you will also want to set StaticObjectType.
StaticShapeObjectType = 1 << 8,
/// Any object that defines one or more solid, renderable dynamic geometries that
/// should be included in collision and raycasts.
///
/// Use this mask to find objects that are part of the dynamic game geometry.
DynamicShapeObjectType = 1 << 9,
/// @}
/// @name Game Types
/// @{
/// Any GameBase-derived object.
/// @see GameBase
GameBaseObjectType = 1 << 10,
/// An object that uses hifi networking.
GameBaseHiFiObjectType = 1 << 11,
/// Any ShapeBase-derived object.
/// @see ShapeBase
ShapeBaseObjectType = 1 << 12,
/// A camera object.
/// @see Camera
CameraObjectType = 1 << 13,
/// A human or AI player object.
/// @see Player
PlayerObjectType = 1 << 14,
/// An item pickup.
/// @see Item
ItemObjectType = 1 << 15,
/// A vehicle.
/// @see Vehicle
VehicleObjectType = 1 << 16,
/// An object that blocks vehicles.
/// @see VehicleBlocker
VehicleBlockerObjectType = 1 << 17,
/// A weapon projectile.
/// @see Projectile
ProjectileObjectType = 1 << 18,
/// An explosion object.
/// @see Explosion
ExplosionObjectType = 1 << 19,
/// A dead player. This is dynamically set and unset.
/// @see Player
CorpseObjectType = 1 << 20,
/// A debris object.
/// @see Debris
DebrisObjectType = 1 << 21,
/// A volume that asserts forces on player objects.
/// @see PhysicalZone
PhysicalZoneObjectType = 1 << 22,
EntityObjectType = 1 << 23,
/// @}
}
}
|
using NUnit.Framework;
using Assert = ProSuite.Commons.Essentials.Assertions.Assert;
using AssertionException = ProSuite.Commons.Essentials.Assertions.AssertionException;
namespace ProSuite.Commons.Test.Assertions
{
[TestFixture]
public class AssertTest
{
[Test]
public void CanAssertNotNull()
{
Assert.NotNull("not null");
}
[Test]
public void CanThrowNotNull()
{
const object dummy = null;
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.NotNull(dummy));
}
[Test]
public void CanThrowNotNullForNullable()
{
int? dummy = null;
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.NotNull(dummy));
}
[Test]
public void CanAssertNotNullMsg()
{
Assert.NotNull("not null", "{0} {1}", "arg1", "arg");
}
[Test]
public void CanThrowNotNullMsg()
{
const object dummy = null;
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.NotNull(dummy, "{0} {1}", "arg1", "arg"));
}
[Test]
public void CanAssertAreEqual()
{
Assert.AreEqual(111, 111, "equal");
}
[Test]
public void CanThrowAreEqual()
{
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.AreEqual(111, 112, "equal"));
}
[Test]
public void CanAssertAssignable()
{
Assert.IsAssignable(new SubClass(), typeof(SuperClass));
}
[Test]
public void CantAssertNotAssignable1()
{
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.IsAssignable(new OtherClass(), typeof(SuperClass)));
}
[Test]
public void CantAssertNotAssignable2()
{
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.IsAssignable(new SuperClass(), typeof(SubClass)));
}
[Test]
public void CanAssertAssignableFrom()
{
Assert.IsAssignableFrom(typeof(SuperClass), typeof(SubClass));
}
[Test]
public void CantAssertNotAssignableFrom1()
{
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.IsAssignableFrom(typeof(SuperClass), typeof(OtherClass)));
}
[Test]
public void CantAssertNotAssignableFrom2()
{
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.IsAssignableFrom(typeof(SubClass), typeof(SuperClass)));
}
[Test]
public void CanAssertIs()
{
Assert.IsExactType(new SuperClass(), typeof(SuperClass));
}
[Test]
public void CantAssertNotEqualType()
{
NUnit.Framework.Assert.Throws<AssertionException>(
() => Assert.IsExactType(new SuperClass(), typeof(SubClass)));
}
}
internal class SuperClass { }
internal class SubClass : SuperClass { }
internal class OtherClass { }
} |
using System.Collections.Generic;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.ConditionalAppearance;
using DevExpress.ExpressApp.Model;
using DevExpress.ExpressApp.Model.Core;
using DevExpress.ExpressApp.Model.NodeGenerators;
using DevExpress.Xpo.Metadata;
using Xpand.Persistent.Base.General;
using System.Linq;
namespace Xpand.ExpressApp.Scheduler.Reminders {
public class ReminderInfoAppearenceRuleUpdater:ModelNodesGeneratorUpdater<ModelBOModelClassNodesGenerator> {
public override void UpdateNode(ModelNode node) {
var modelApplicationBases = GetModulesDifferences(node);
var modelClasses = modelApplicationBases.Cast<IModelApplication>().SelectMany(modelApplication
=> modelApplication.BOModel.Where(HasReminderMember));
foreach (var modelClass in modelClasses) {
AddRule(node.Application, modelClass);
}
}
IEnumerable<ModelApplicationBase> GetModulesDifferences(ModelNode node) {
var modelApplicationBases = new List<ModelApplicationBase>();
foreach (var moduleBase in ((IModelSources)node.Application).Modules) {
var modelApplicationBase = node.CreatorInstance.CreateModelApplication();
modelApplicationBase.Id = moduleBase.Name;
var resourcesModelStore = new ResourcesModelStore(moduleBase.GetType().Assembly);
resourcesModelStore.Load(modelApplicationBase);
var modelBoModel = ((IModelApplication) modelApplicationBase).BOModel;
if (modelBoModel != null&&modelBoModel.Any(HasReminderMember))
modelApplicationBases.Add(modelApplicationBase);
}
return modelApplicationBases;
}
bool HasReminderMember(IModelClass @class) {
return @class.OwnMembers != null && @class.OwnMembers.OfType<IModelMemberReminderInfo>().Any();
}
public static void AddRule(IModelApplication modelApplication, IModelClass modelClass) {
if (modelClass.OwnMembers != null) {
var modelMemberReminderInfo = modelClass.OwnMembers.OfType<IModelMemberReminderInfo>().FirstOrDefault();
if (modelMemberReminderInfo != null) {
var conditionalAppearance = (IModelConditionalAppearance)modelApplication.BOModel.GetClass(modelClass.TypeInfo.Type);
var modelAppearanceRule = conditionalAppearance.AppearanceRules.AddNode<IModelAppearanceRule>("ReminderInfo.TimeBeforeStart");
modelAppearanceRule.AppearanceItemType = AppearanceItemType.ViewItem.ToString();
modelAppearanceRule.Criteria = "!" + modelMemberReminderInfo.Name + ".HasReminder";
modelAppearanceRule.Enabled = false;
modelAppearanceRule.TargetItems = modelMemberReminderInfo.Name+".TimeBeforeStart";
}
}
}
}
public class ReminderInfoModelMemberUpdater : ModelNodesGeneratorUpdater<ModelBOModelMemberNodesGenerator> {
public override void UpdateNode(ModelNode node) {
var modelBoModelClassMembers = ((IModelBOModelClassMembers) node);
var modelClass = ((IModelClass) modelBoModelClassMembers.Parent);
var supportsReminderAttribute = modelClass.TypeInfo.FindAttribute<SupportsReminderAttribute>();
if (supportsReminderAttribute!=null) {
var modelMemberReminderInfo = modelBoModelClassMembers.AddNode<IModelMemberReminderInfo>(supportsReminderAttribute.MemberName);
modelMemberReminderInfo.Name = supportsReminderAttribute.MemberName;
modelMemberReminderInfo.ReminderCriteria=supportsReminderAttribute.Criteria;
if (modelMemberReminderInfo.MemberInfo != null){
var classInfo = modelMemberReminderInfo.MemberInfo.Owner.QueryXPClassInfo();
XPMemberInfo xpMemberInfo = classInfo.FindMember(modelMemberReminderInfo.Name);
ModelMemberReminderInfoDomainLogic.ModifyModel(modelMemberReminderInfo, xpMemberInfo);
}
ReminderInfoAppearenceRuleUpdater.AddRule(modelClass.Application,modelClass);
}
}
}
}
|
/*
* Gitea API.
*
* This documentation describes the Gitea API.
*
* OpenAPI spec version: 1.1.1
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using SwaggerDateConverter = Altinn.Studio.Designer.RepositoryClient.Client.SwaggerDateConverter;
namespace Altinn.Studio.Designer.RepositoryClient.Model
{
/// <summary>
/// PublicKey publickey is a user key to push code to repository
/// </summary>
[DataContract]
public partial class PublicKey : IEquatable<PublicKey>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PublicKey" /> class.
/// </summary>
/// <param name="CreatedAt">CreatedAt.</param>
/// <param name="Fingerprint">Fingerprint.</param>
/// <param name="Id">Id.</param>
/// <param name="Key">Key.</param>
/// <param name="Title">Title.</param>
/// <param name="Url">Url.</param>
public PublicKey(DateTime? CreatedAt = default(DateTime?), string Fingerprint = default(string), long? Id = default(long?), string Key = default(string), string Title = default(string), string Url = default(string))
{
this.CreatedAt = CreatedAt;
this.Fingerprint = Fingerprint;
this.Id = Id;
this.Key = Key;
this.Title = Title;
this.Url = Url;
}
/// <summary>
/// Gets or Sets CreatedAt
/// </summary>
[DataMember(Name="created_at", EmitDefaultValue=false)]
public DateTime? CreatedAt { get; set; }
/// <summary>
/// Gets or Sets Fingerprint
/// </summary>
[DataMember(Name="fingerprint", EmitDefaultValue=false)]
public string Fingerprint { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public long? Id { get; set; }
/// <summary>
/// Gets or Sets Key
/// </summary>
[DataMember(Name="key", EmitDefaultValue=false)]
public string Key { get; set; }
/// <summary>
/// Gets or Sets Title
/// </summary>
[DataMember(Name="title", EmitDefaultValue=false)]
public string Title { get; set; }
/// <summary>
/// Gets or Sets Url
/// </summary>
[DataMember(Name="url", EmitDefaultValue=false)]
public string Url { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PublicKey {\n");
sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n");
sb.Append(" Fingerprint: ").Append(Fingerprint).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Key: ").Append(Key).Append("\n");
sb.Append(" Title: ").Append(Title).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PublicKey);
}
/// <summary>
/// Returns true if PublicKey instances are equal
/// </summary>
/// <param name="input">Instance of PublicKey to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PublicKey input)
{
if (input == null)
{
return false;
}
return
(
this.CreatedAt == input.CreatedAt ||
(this.CreatedAt != null &&
this.CreatedAt.Equals(input.CreatedAt))) &&
(
this.Fingerprint == input.Fingerprint ||
(this.Fingerprint != null &&
this.Fingerprint.Equals(input.Fingerprint))) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))) &&
(
this.Key == input.Key ||
(this.Key != null &&
this.Key.Equals(input.Key))) &&
(
this.Title == input.Title ||
(this.Title != null &&
this.Title.Equals(input.Title))) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url)));
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// Overflow is fine, just wrap
unchecked
{
int hashCode = 41;
if (this.CreatedAt != null)
{
hashCode = (hashCode * 59) + this.CreatedAt.GetHashCode();
}
if (this.Fingerprint != null)
{
hashCode = (hashCode * 59) + this.Fingerprint.GetHashCode();
}
if (this.Id != null)
{
hashCode = (hashCode * 59) + this.Id.GetHashCode();
}
if (this.Key != null)
{
hashCode = (hashCode * 59) + this.Key.GetHashCode();
}
if (this.Title != null)
{
hashCode = (hashCode * 59) + this.Title.GetHashCode();
}
if (this.Url != null)
{
hashCode = (hashCode * 59) + this.Url.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
|
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using TCGPrimus.Contracts;
using TCGPrimus.Entities.Extensions;
using TCGPrimus.Entities.Models;
namespace TCGPrimus.Api.Controllers
{
[Route("api/account")]
[ApiController]
public class AccountController : ControllerBase
{
private ILoggerManager _logger;
private IRepositoryWrapper _repository;
public AccountController(ILoggerManager logger, IRepositoryWrapper repository)
{
_logger = logger;
_repository = repository;
}
[HttpGet]
public IActionResult GetAllAccounts()
{
try
{
var accounts = _repository.Account.GetAllAccounts();
_logger.LogInfo($"Returned all accounts from database.");
return Ok(accounts);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside GetAllAccounts action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
[HttpGet("{id}", Name = "AccountById")]
public IActionResult GetAccountById(Guid id)
{
try
{
var account = _repository.Account.GetAccountById(id);
if (account.IsEmptyObject())
{
_logger.LogError($"Account with id: {id}, hasn't been found in db.");
return NotFound();
}
else
{
_logger.LogInfo($"Returned account with id: {id}");
return Ok(account);
}
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside GetAccountById action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
[HttpPost]
public IActionResult CreateAccount([FromBody] Account account)
{
try
{
if (account.IsObjectNull())
{
_logger.LogError("Account object sent from client is null.");
return BadRequest("Account object is null");
}
if (!ModelState.IsValid)
{
_logger.LogError("Invalid account object sent from client.");
return BadRequest("Invalid model object");
}
_repository.Account.CreateAccount(account);
return CreatedAtRoute("AccountById", new { id = account.Id }, account);
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside CreateAccount action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
[HttpPut("{id}")]
public IActionResult UpdateAccount(Guid id, [FromBody] Account account)
{
try
{
if (account.IsObjectNull())
{
_logger.LogError("Account object sent from client is null.");
return BadRequest("Account object is null");
}
if (!ModelState.IsValid)
{
_logger.LogError("Invalid account object sent from client.");
return BadRequest("Invalid model object");
}
var dbAccount = _repository.Account.GetAccountById(id);
if (dbAccount.IsEmptyObject())
{
_logger.LogError($"Account with id: {id}, hasn't been found in db.");
return NotFound();
}
_repository.Account.UpdateAccount(dbAccount, account);
return NoContent();
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside UpdateAccount action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
[HttpDelete("{id}")]
public IActionResult DeleteAccount(Guid id)
{
try
{
var account = _repository.Account.GetAccountById(id);
if (account.IsEmptyObject())
{
_logger.LogError($"Account with id: {id}, hasn't been found in db.");
return NotFound();
}
_repository.Account.DeleteAccount(account);
return NoContent();
}
catch (Exception ex)
{
_logger.LogError($"Something went wrong inside DeleteAccount action: {ex.Message}");
return StatusCode(500, "Internal server error");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ToBallState : State
{
GameObject ball;
Arrive arrive;
public override void Enter() {
arrive = owner.GetComponent<Arrive>();
ball = Player.instance.mostInterestingBallThrown;
}
public override void Exit() {
owner.GetComponent<Dog>().Pickup(ball);
}
public override void Think() {
arrive.targetPosition = new Vector3(ball.transform.position.x, 0f, ball.transform.position.z);
if (Vector3.Distance(owner.transform.position, arrive.targetPosition) <= 2f)
{
owner.ChangeState(new ToPlayerState());
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Tabi.Helpers;
namespace Tabi.Logging
{
public class FileLogWriter : LogWriter
{
public static EventHandler<EventArgs> LogWriteEvent;
LogFileAccess logAccess;
public FileLogWriter() : base()
{
logAccess = new LogFileAccess();
}
private async Task WriteToFile(string text)
{
await logAccess.AppendAsync(text);
LogWriteEvent?.Invoke(this, EventArgs.Empty);
}
protected override async Task ErrorConsumerAsync(ISourceBlock<Exception> Source)
{
while (await Source.OutputAvailableAsync())
{
await WriteToFile($"{DateTime.Now} {Source.Receive()}\n");
LogWriteEvent?.Invoke(this, EventArgs.Empty);
}
}
protected override async Task LogConsumerAsync(ISourceBlock<string> Source)
{
while (await Source.OutputAvailableAsync())
{
await WriteToFile($"{DateTime.Now} {Source.Receive()}\n");
LogWriteEvent?.Invoke(this, EventArgs.Empty);
}
}
}
}
|
namespace TrackMe.Core.Services.Interfaces
{
public interface ISettings
{
bool AddOrUpdate<T>(string key, T value);
T GetValue<T>(string key, T defualt = default(T));
void Clear();
}
}
|
using Commons.Libs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FashionGo.Controllers
{
public class MailController : BaseController
{
// GET: Mail
public ActionResult Index()
{
return View();
}
public ActionResult Send(string name, string email, string message)
{
try
{
var from = name + "<" + email + ">";
XMail.Send(from, "thien154@gmail.com", "test", message);
}
catch
{
}
return View();
}
}
} |
using Alza.Core.Module.Abstraction;
using Alza.Module.Catalog.Dal.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Alza.Module.Catalog.Dal.Repository.Abstraction
{
public interface ICategoryRepository : IRepository<Category>
{
Category GetByName(string name);
Category GetBySEOName(string seoName);
int GetStats1ByCategoryName(string categoryName = null, string MediaType = null);
Dictionary<string, int> GetStats1(string MediaType);
}
}
|
// -- FILE ------------------------------------------------------------------
// name : CalendarVisitorFilter.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.02.18
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace Itenso.TimePeriod
{
// ------------------------------------------------------------------------
public class CalendarVisitorFilter : ICalendarVisitorFilter
{
// ----------------------------------------------------------------------
public virtual void Clear()
{
years.Clear();
months.Clear();
days.Clear();
weekDays.Clear();
hours.Clear();
} // Clear
// ----------------------------------------------------------------------
public ITimePeriodCollection ExcludePeriods
{
get { return excludePeriods; }
} // ExcludePeriods
// ----------------------------------------------------------------------
public IList<int> Years
{
get { return years; }
} // Years
// ----------------------------------------------------------------------
public IList<YearMonth> Months
{
get { return months; }
} // Months
// ----------------------------------------------------------------------
public IList<int> Days
{
get { return days; }
} // Days
// ----------------------------------------------------------------------
public IList<DayOfWeek> WeekDays
{
get { return weekDays; }
} // WeekDays
// ----------------------------------------------------------------------
public IList<int> Hours
{
get { return hours; }
} // Hours
// ----------------------------------------------------------------------
public void AddWorkingWeekDays()
{
weekDays.Add( DayOfWeek.Monday );
weekDays.Add( DayOfWeek.Tuesday );
weekDays.Add( DayOfWeek.Wednesday );
weekDays.Add( DayOfWeek.Thursday );
weekDays.Add( DayOfWeek.Friday );
} // AddWorkingWeekDays
// ----------------------------------------------------------------------
public void AddWeekendWeekDays()
{
weekDays.Add( DayOfWeek.Saturday );
weekDays.Add( DayOfWeek.Sunday );
} // AddWeekendWeekDays
// ----------------------------------------------------------------------
// members
private readonly TimePeriodCollection excludePeriods = new TimePeriodCollection();
private readonly List<int> years = new List<int>();
private readonly List<YearMonth> months = new List<YearMonth>();
private readonly List<int> days = new List<int>();
private readonly List<DayOfWeek> weekDays = new List<DayOfWeek>();
private readonly List<int> hours = new List<int>();
} // class CalendarVisitorFilter
} // namespace Itenso.TimePeriod
// -- EOF -------------------------------------------------------------------
|
//--------------------------------------------------
// Motion Framework
// Copyright©2018-2021 何冠峰
// Licensed under the MIT license
//--------------------------------------------------
using System.IO;
using MotionFramework.IO;
namespace MotionFramework.Resource
{
internal static class AssetPathHelper
{
/// <summary>
/// 获取规范化的路径
/// </summary>
public static string GetRegularPath(string path)
{
return path.Replace('\\', '/').Replace("\\", "/"); //替换为Linux路径格式
}
/// <summary>
/// 获取文件所在的目录路径(Linux格式)
/// </summary>
public static string GetDirectory(string filePath)
{
string directory = Path.GetDirectoryName(filePath);
return GetRegularPath(directory);
}
/// <summary>
/// 获取基于流文件夹的加载路径
/// </summary>
public static string MakeStreamingLoadPath(string path)
{
return StringFormat.Format("{0}/{1}", UnityEngine.Application.streamingAssetsPath, path);
}
/// <summary>
/// 获取基于沙盒文件夹的加载路径
/// </summary>
public static string MakePersistentLoadPath(string path)
{
#if UNITY_EDITOR
// 注意:为了方便调试查看,编辑器下把存储目录放到项目里
string projectPath = GetDirectory(UnityEngine.Application.dataPath);
return StringFormat.Format("{0}/Sandbox/{1}", projectPath, path);
#else
return StringFormat.Format("{0}/Sandbox/{1}", UnityEngine.Application.persistentDataPath, path);
#endif
}
/// <summary>
/// 获取网络资源加载路径
/// </summary>
public static string ConvertToWWWPath(string path)
{
// 注意:WWW加载方式,必须要在路径前面加file://
#if UNITY_EDITOR
return StringFormat.Format("file:///{0}", path);
#elif UNITY_IPHONE
return StringFormat.Format("file://{0}", path);
#elif UNITY_ANDROID
return path;
#elif UNITY_STANDALONE
return StringFormat.Format("file:///{0}", path);
#endif
}
/// <summary>
/// 合并资源路径
/// </summary>
internal static string CombineAssetPath(string root, string location)
{
if (string.IsNullOrEmpty(root))
return location;
else
return $"{root}/{location}";
}
/// <summary>
/// 获取AssetDatabase的加载路径
/// </summary>
internal static string FindDatabaseAssetPath(string location)
{
#if UNITY_EDITOR
string filePath = CombineAssetPath(AssetSystem.LocationRoot, location);
if (File.Exists(filePath))
return filePath;
// AssetDatabase加载资源需要提供文件后缀格式,然而资源定位地址并没有文件格式信息。
// 所以我们通过查找该文件所在文件夹内同名的首个文件来确定AssetDatabase的加载路径。
// 注意:AssetDatabase.FindAssets() 返回文件内包括递归文件夹内所有资源的GUID
string fileName = Path.GetFileName(filePath);
string directory = GetDirectory(filePath);
string[] guids = UnityEditor.AssetDatabase.FindAssets(string.Empty, new[] { directory });
for (int i = 0; i < guids.Length; i++)
{
string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
if (UnityEditor.AssetDatabase.IsValidFolder(assetPath))
continue;
string assetDirectory = GetDirectory(assetPath);
if (assetDirectory != directory)
continue;
string assetName = Path.GetFileNameWithoutExtension(assetPath);
if (assetName == fileName)
return assetPath;
}
// 没有找到同名的资源文件
MotionLog.Warning($"Not found asset : {filePath}");
return filePath;
#else
return string.Empty;
#endif
}
}
} |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.CMS.Account.Models;
using System.IO;
using Kooboo.Runtime.Serialization;
using Kooboo.CMS.Common;
using Kooboo.CMS.Common.Runtime.Dependency;
using Kooboo.CMS.Common.Persistence.Non_Relational;
namespace Kooboo.CMS.Account.Persistence.FileSystem
{
[Dependency(typeof(IRoleProvider))]
[Dependency(typeof(IProvider<Role>))]
public class RoleProvider : ObjectFileRepository<Role>, IRoleProvider
{
private static System.Threading.ReaderWriterLockSlim locker = new System.Threading.ReaderWriterLockSlim();
private IAccountBaseDir accountBaseDir;
public RoleProvider(IAccountBaseDir baseDir)
{
accountBaseDir = baseDir;
}
protected override System.Threading.ReaderWriterLockSlim GetLocker()
{
return locker;
}
protected override string GetFilePath(Role o)
{
return Path.Combine(GetBasePath(), o.Name + ".config");
}
protected override string GetBasePath()
{
return Path.Combine(accountBaseDir.PhysicalPath, "Roles");
}
protected override Role CreateObject(string filePath)
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
return new Role() { Name = fileName };
}
}
}
|
using System;
using Robust.Shared.Interfaces.GameObjects;
namespace Content.Client.Interfaces.GameObjects.Components.Interaction
{
/// <summary>
/// This interface allows a local client to initiate dragging of the component's entity by mouse, for drag and
/// drop interactions. The actual logic of what happens on drop
/// is handled by IDragDrop
/// </summary>
public interface IClientDraggable
{
/// <summary>
/// Invoked on entities visible to the user to check if this component's entity
/// can be dropped on the indicated target entity. No need to check range / reachability in here.
/// </summary>
/// <returns>true iff target is a valid target to be dropped on by this
/// component's entity. Returning true will cause the target entity to be highlighted as a potential
/// target and allow dropping when in range.</returns>
bool ClientCanDropOn(CanDropEventArgs eventArgs);
/// <summary>
/// Invoked clientside when user is attempting to initiate a drag with this component's entity
/// in range. Return true if the drag should be initiated. It's fine to
/// return true even if there wouldn't be any valid targets - just return true
/// if this entity is in a "draggable" state.
/// </summary>
/// <param name="eventArgs"></param>
/// <returns>true iff drag should be initiated</returns>
bool ClientCanDrag(CanDragEventArgs eventArgs);
}
public class CanDropEventArgs : EventArgs
{
/// <summary>
/// Creates a new instance of <see cref="CanDropEventArgs"/>.
/// </summary>
/// <param name="user">The entity doing the drag and drop.</param>
/// <param name="dragged">The entity that is being dragged and dropped.</param>
/// <param name="target">The entity that <see cref="dragged"/> is being dropped onto.</param>
public CanDropEventArgs(IEntity user, IEntity dragged, IEntity target)
{
User = user;
Dragged = dragged;
Target = target;
}
/// <summary>
/// The entity doing the drag and drop.
/// </summary>
public IEntity User { get; }
/// <summary>
/// The entity that is being dragged and dropped.
/// </summary>
public IEntity Dragged { get; }
/// <summary>
/// The entity that <see cref="Dragged"/> is being dropped onto.
/// </summary>
public IEntity Target { get; }
}
public class CanDragEventArgs : EventArgs
{
/// <summary>
/// Creates a new instance of <see cref="CanDragEventArgs"/>.
/// </summary>
/// <param name="user">The entity doing the drag and drop.</param>
/// <param name="dragged">The entity that is being dragged and dropped.</param>
public CanDragEventArgs(IEntity user, IEntity dragged)
{
User = user;
Dragged = dragged;
}
/// <summary>
/// The entity doing the drag and drop.
/// </summary>
public IEntity User { get; }
/// <summary>
/// The entity that is being dragged and dropped.
/// </summary>
public IEntity Dragged { get; }
}
}
|
using MicroserviceTemplate.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Threading.Tasks;
namespace MicroserviceTemplate.Command.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ItemController : ControllerBase
{
public ItemController()
{
}
[HttpPost]
[ProducesResponseType(typeof(Item), (int)HttpStatusCode.Accepted)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public async Task<IActionResult> CreateItem(Item request)
{
// Execute your command here
return Accepted();
}
[HttpPut]
[Route("{id}")]
[ProducesResponseType((int)HttpStatusCode.Accepted)]
[ProducesResponseType(typeof(Item), (int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public async Task<IActionResult> UpdateItem([Required] Guid id, Item request)
{
// Execute your command here
return Accepted();
}
[HttpDelete]
[Route("{id}")]
[ProducesResponseType((int)HttpStatusCode.Accepted)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.InternalServerError)]
public async Task<IActionResult> DeleteItem([Required] Guid id, [Required] string tenant)
{
// Execute your command here
return Accepted();
}
}
}
|
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Linq;
using Newtonsoft.Json;
namespace Squidex.Domain.Apps.Core.Contents.Json
{
public class JsonWorkflowTransition
{
[JsonProperty]
public string? Expression { get; set; }
[JsonProperty]
public string? Role { get; set; }
[JsonProperty]
public string[]? Roles { get; set; }
public JsonWorkflowTransition()
{
}
public JsonWorkflowTransition(WorkflowTransition transition)
{
Roles = transition.Roles?.ToArray();
Expression = transition.Expression;
}
public WorkflowTransition ToTransition()
{
var roles = Roles;
if (!string.IsNullOrEmpty(Role))
{
roles = new[] { Role };
}
return WorkflowTransition.When(Expression, roles);
}
}
} |
/*
* Win32 controls scrolling management
*/
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using PluginCore;
namespace Win32
{
public class Scrolling
{
public const int SB_HORZ = 0;
public const int SB_VERT = 1;
const int SB_LEFT = 6;
const int SB_RIGHT = 7;
const int WM_HSCROLL = 0x0114;
const int WM_VSCROLL = 0x0115;
public static void scrollToBottom(Control ctrl)
{
int min, max;
OSHelper.API.GetScrollRange(ctrl.Handle, SB_VERT, out min, out max);
OSHelper.API.SendMessage(ctrl.Handle, WM_VSCROLL, SB_RIGHT, max);
}
public static void scrollToTop(Control ctrl)
{
OSHelper.API.SendMessage(ctrl.Handle, WM_VSCROLL, SB_LEFT, 0);
}
public static void scrollToRight(Control ctrl)
{
int min, max;
OSHelper.API.GetScrollRange(ctrl.Handle, SB_HORZ, out min, out max);
OSHelper.API.SendMessage(ctrl.Handle, WM_HSCROLL, SB_RIGHT, max);
}
public static void scrollToLeft(Control ctrl)
{
OSHelper.API.SendMessage(ctrl.Handle, WM_HSCROLL, SB_LEFT, 0);
}
}
}
|
using System;
using System.Formats.Asn1;
namespace Codemations.Asn1
{
public interface IAsnConverter
{
object Read(AsnReader reader, Asn1Tag? tag, Type type);
void Write(AsnWriter writer, Asn1Tag? tag, object value);
}
} |
//
// Drawer.cs
// ProductName Ling
//
// Created by toshiki sakamoto on 2020.07.05
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
namespace Utility.Editor
{
/// <summary>
/// <see cref="UnityEditor.PropertyDrawer"/>関連の便利関数定義
/// </summary>
public static class Drawer
{
#region 定数, class, enum
#endregion
#region public, protected 変数
#endregion
#region private 変数
#endregion
#region public, protected 関数
/// <summary>
/// 指定した区画の幅を<paramref name="num"/>で分割する
/// </summary>
/// <param name="rect">分割対象</param>
/// <param name="num">分割する数</param>
/// <param name="space">スペースを作る場合指定</param>
/// <returns></returns>
public static List<Rect> SplitHorizontalRects(in Rect rect, int num, float space = 0f)
{
if (num <= 0) return new List<Rect> { rect };
var result = new List<Rect>();
var x = rect.x;
var w = (rect.width - (space * num - 1)) / num;
for (int i = 0; i < num; ++i)
{
var r = rect;
r.x = x;
r.width = w;
result.Add(r);
x += w + space;
}
return result;
}
#endregion
#region private 関数
#endregion
}
}
|
/*
Copyright (c) 2016 Denis Zykov, GameDevWare.com
This a part of "Json & MessagePack Serialization" Unity Asset - https://www.assetstore.unity3d.com/#!/content/59918
THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE
AND THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
This source code is distributed via Unity Asset Store,
to use it in your project you should accept Terms of Service and EULA
https://unity3d.com/ru/legal/as_terms
*/
// ReSharper disable once CheckNamespace
namespace GameDevWare.Serialization.MessagePack
{
public enum MsgPackExtType : byte
{
None = 0,
DateTimeOld = 1,
DecimalOld = 2,
DateTime = 40,
DateTimeOffset = 41,
Decimal = 42
}
}
|
using System;
using System.Collections.Generic;
using SchinkZeShips.Core.SchinkZeShipsReference;
namespace SchinkZeShips.Core.GameLogic.Board
{
public partial class ShipStatusDisplay
{
public ShipStatusDisplay()
{
InitializeComponent();
Battleships.BindingContext = DummyShip(5);
Cruisers.BindingContext = DummyShip(4);
Destroyer.BindingContext = DummyShip(3);
Submarines.BindingContext = DummyShip(2);
}
private static Ship DummyShip(int length)
{
var parts = new List<CellViewModel>();
for (var i = 0; i < length; i++)
{
parts.Add(new CellViewModel(new Coordinate(0, i), false));
}
var ship = new Ship(parts, true, Guid.NewGuid().ToString());
foreach (var part in parts)
{
part.Model = new CellState();
part.Ship = ship;
}
return ship;
}
}
} |
// <auto-generated />
using Chatter.Infra.Data.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
namespace Chatter.Infra.Data.Migrations
{
[DbContext(typeof(ChatterContext))]
[Migration("20180401133856_InitialData")]
partial class InitialData
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.0.2-rtm-10011")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Chatter.Domain.Categories.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<DateTime>("Created")
.ValueGeneratedOnAdd()
.HasDefaultValueSql("GETDATE()");
b.Property<string>("Description")
.HasColumnType("varchar(500)");
b.Property<string>("Image")
.HasColumnType("varchar(500)");
b.Property<bool>("IsFeatured");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(100)");
b.Property<bool>("Removed")
.ValueGeneratedOnAdd()
.HasDefaultValue(false);
b.HasKey("Id");
b.ToTable("Categories");
});
modelBuilder.Entity("Chatter.Domain.Topics.Post", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("Created")
.ValueGeneratedOnAdd()
.HasDefaultValueSql("GETDATE()");
b.Property<bool>("Removed")
.ValueGeneratedOnAdd()
.HasDefaultValue(false);
b.Property<string>("Text")
.IsRequired()
.HasColumnType("varchar(1000)");
b.Property<int>("TopicId");
b.Property<int>("UserId");
b.HasKey("Id");
b.HasIndex("TopicId");
b.HasIndex("UserId");
b.ToTable("Posts");
});
modelBuilder.Entity("Chatter.Domain.Topics.Topic", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<int>("CategoryId");
b.Property<DateTime>("Created")
.ValueGeneratedOnAdd()
.HasDefaultValueSql("GETDATE()");
b.Property<string>("Description")
.HasColumnType("varchar(1000)");
b.Property<bool>("Removed")
.ValueGeneratedOnAdd()
.HasDefaultValue(false);
b.Property<string>("Title")
.IsRequired()
.HasColumnType("varchar(200)");
b.Property<int>("UserId");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.HasIndex("UserId");
b.ToTable("Topics");
});
modelBuilder.Entity("Chatter.Domain.Users.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<DateTime>("Created")
.ValueGeneratedOnAdd()
.HasDefaultValueSql("GETDATE()");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("varchar(150)");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("varchar(200)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("varchar(20)");
b.Property<bool>("Removed")
.ValueGeneratedOnAdd()
.HasDefaultValue(false);
b.HasKey("Id");
b.ToTable("Users");
});
modelBuilder.Entity("Chatter.Domain.Topics.Post", b =>
{
b.HasOne("Chatter.Domain.Topics.Topic", "Topic")
.WithMany("Posts")
.HasForeignKey("TopicId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Chatter.Domain.Users.User", "User")
.WithMany("Posts")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity("Chatter.Domain.Topics.Topic", b =>
{
b.HasOne("Chatter.Domain.Categories.Category", "Category")
.WithMany("Topics")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Chatter.Domain.Users.User", "User")
.WithMany("Topics")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
|
using System;
public class main {
public static void Main() {
// ACM-ICPC 인터넷 예선, Regional, 그리고 World Finals까지 이미 2회씩 진출해버린 kriii는
// 미련을 버리지 못하고 왠지 모르게 올해에도 파주 World Finals 준비 캠프에 참여했다.
// 대회를 뜰 줄 모르는 지박령 kriii를 위해서 격려의 문구를 출력해주자.
// 두 줄에 걸쳐 "강한친구 대한육군"을 한 줄에 한 번씩 출력한다.
Console.WriteLine("강한친구 대한육군");
Console.WriteLine("강한친구 대한육군");
}
} |
using System;
using UnityEngine;
namespace FriendlyMonster.Stencil
{
public class Papers : MonoBehaviour
{
[SerializeField] private Paper Paper;
[SerializeField] private Texture[] Textures;
private RenderTexture[] m_RenderTextures;
private void Awake()
{
m_RenderTextures = new RenderTexture[Textures.Length];
for (int i = 0; i < m_RenderTextures.Length; i++)
{
m_RenderTextures[i] = new RenderTexture(256, 256, 16, RenderTextureFormat.ARGB32);
}
}
public void RegisterOnMove(Action commitPaint)
{
Paper.RegisterOnMove(commitPaint);
}
public void OnTouch(Touch touch, RaycastHit hit)
{
Paper.OnTouch(touch, hit);
}
public void RenderPreview()
{
Paper.RenderPreview();
}
public void Commit()
{
Paper.Commit();
}
public void SelectTexture(int textureIndex)
{
Paper.SelectTexture(Textures[textureIndex], m_RenderTextures[textureIndex]);
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace JacksonVeroneze.NET.Commons.Database.Relational
{
public static class DatabaseConfiguration
{
public static IServiceCollection AddSqlServerDatabaseConfiguration<T>(this IServiceCollection services,
Action<DatabaseOptions> action) where T : DbContext
{
DatabaseOptions optionsConfig = FactoryOptions(action);
return services.AddDbContext<T>((_, options) =>
options.UseSqlServer(optionsConfig.ConnectionString, optionsBuilder =>
optionsBuilder
.CommandTimeout((int) TimeSpan.FromMinutes(3).TotalSeconds)
.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null)
)
.ConfigureOptions(optionsConfig)
.ConfigureLogger(optionsConfig)
);
}
public static IServiceCollection AddPostgreSqlDatabaseConfiguration<T>(this IServiceCollection services,
Action<DatabaseOptions> action) where T : DbContext
{
DatabaseOptions optionsConfig = FactoryOptions(action);
return services.AddDbContext<T>((_, options) =>
options.UseNpgsql(optionsConfig.ConnectionString, optionsBuilder =>
optionsBuilder
.CommandTimeout((int) TimeSpan.FromMinutes(3).TotalSeconds)
.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null)
)
.ConfigureOptions(optionsConfig)
.ConfigureLogger(optionsConfig)
);
}
public static IServiceCollection AddSqliteDatabaseConfiguration<T>(this IServiceCollection services,
Action<DatabaseOptions> action) where T : DbContext
{
DatabaseOptions optionsConfig = FactoryOptions(action);
return services.AddDbContext<T>((_, options) =>
options.UseSqlite(optionsConfig.ConnectionString, optionsBuilder =>
optionsBuilder
.CommandTimeout((int) TimeSpan.FromMinutes(3).TotalSeconds)
)
.ConfigureOptions(optionsConfig)
.ConfigureLogger(optionsConfig)
);
}
private static DatabaseOptions FactoryOptions(Action<DatabaseOptions> action)
{
DatabaseOptions optionsConfig = new DatabaseOptions();
action?.Invoke(optionsConfig);
return optionsConfig;
}
private static DbContextOptionsBuilder ConfigureOptions(this DbContextOptionsBuilder options,
DatabaseOptions optionsConfig)
{
options.UseSnakeCaseNamingConvention();
if (optionsConfig.UseLazyLoadingProxies)
options.UseLazyLoadingProxies();
if (optionsConfig.EnableDetailedErrors)
options.EnableDetailedErrors();
if (optionsConfig.EnableSensitiveDataLogging)
options.EnableSensitiveDataLogging();
return options;
}
private static DbContextOptionsBuilder ConfigureLogger(this DbContextOptionsBuilder options,
DatabaseOptions optionsConfig)
=> options;
}
} |
namespace SourceQuery
{
public partial class SourceServer
{
public class Info
{
public byte version;
public string hostname;
public string map;
public string game_directory;
public string game_description;
public short app_id;
public byte num_players;
public byte max_players;
public byte num_of_bots;
public char type;
public char os;
public bool password;
public bool secure;
public string game_version;
public ushort port;
public ulong steamid;
public ushort tvport;
public string tvname;
public string tags;
public ulong gameid;
};
}
}
|
// ***********************************************************************
// Assembly : ModMaker
// Author : TJ
// Created : 08-27-2015
//
// Last Modified By : TJ
// Last Modified On : 08-27-2015
// ***********************************************************************
// <copyright file="InternalEditor.cs" company="">
// Copyright © 2015
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Windows.Forms;
namespace ModManagerUlt {
/// <summary>
/// Class InternalEditor.
/// </summary>
public partial class InternalEditor : Form {
/// <summary>
/// Initializes a new instance of the <see cref="InternalEditor" /> class.
/// </summary>
public InternalEditor() {
InitializeComponent();
}
/// <summary>
/// save
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private void button1_Click(object sender, EventArgs e) {
//save
}
/// <summary>
/// dispose
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private void button3_Click(object sender, EventArgs e) {
Dispose();
}
/// <summary>
/// load
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
private void InternalEditor_Load(object sender, EventArgs e) {
}
}
} |
using System;
using System.Globalization;
using System.Windows.Data;
using Resx = Neurotoxin.Godspeed.Shell.Properties.Resources;
namespace Neurotoxin.Godspeed.Shell.Converters
{
public class ResxConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var format = parameter as string;
var v = format != null ? String.Format(format, value) : value.ToString();
return Resx.ResourceManager.GetString(v) ?? "Key: " + v;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace TezosNotifyBot.Domain
{
public class Message
{
public int Id { get; set; }
public User User { get; set; }
public long UserId { get; set; }
public MessageKind Kind { get; set; } = MessageKind.Simple;
public MessageStatus Status { get; set; } = MessageStatus.Sent;
public DateTime CreateDate { get; set; }
public string Text { get; set; }
public string CallbackQueryData { get; set; }
public bool FromUser { get; set; }
public int? TelegramMessageId { get; set; }
public static Message Push(long userId, string text)
{
return new Message
{
Kind = MessageKind.Push,
UserId = userId,
FromUser = false,
CreateDate = DateTime.Now,
Text = text,
Status = MessageStatus.Sending,
};
}
public void Sent(in int telegramMessageId)
{
TelegramMessageId = telegramMessageId;
Status = MessageStatus.Sent;
}
public void SentFailed()
{
Status = MessageStatus.SentFailed;
}
}
public enum MessageKind
{
Simple,
Push
}
public enum MessageStatus
{
Sent,
SentFailed,
Sending
}
} |
namespace MdTranslator.Lib
{
public class TranslateLine
{
public int Line { get; set; }
public string OrigTerm { get; set; }
public string TranslatedTerm { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SIL.Extensions;
using SIL.Machine.Corpora;
using SIL.Machine.NgramModeling;
using SIL.Machine.Optimization;
using SIL.Machine.Statistics;
using SIL.Machine.Utils;
using SIL.ObjectModel;
namespace SIL.Machine.Translation.Thot
{
public class ThotSmtModelTrainer : DisposableBase, ITrainer
{
private readonly ITokenProcessor _sourcePreprocessor;
private readonly ITokenProcessor _targetPreprocessor;
private readonly ParallelTextCorpus _parallelCorpus;
private readonly HashSet<int> _tuneCorpusIndices;
private readonly IParameterTuner _modelWeightTuner;
private readonly string _tempDir;
private readonly string _lmFilePrefix;
private readonly string _tmFilePrefix;
private readonly string _trainLMDir;
private readonly string _trainTMDir;
private readonly int _maxCorpusCount;
private readonly ThotWordAlignmentModelType _wordAlignmentModelType;
public ThotSmtModelTrainer(ThotWordAlignmentModelType wordAlignmentModelType, ParallelTextCorpus corpus,
string cfgFileName, ITokenProcessor sourcePreprocessor = null, ITokenProcessor targetPreprocessor = null,
int maxCorpusCount = int.MaxValue)
: this(wordAlignmentModelType, corpus, ThotSmtParameters.Load(cfgFileName), sourcePreprocessor,
targetPreprocessor, maxCorpusCount)
{
ConfigFileName = cfgFileName;
}
public ThotSmtModelTrainer(ThotWordAlignmentModelType wordAlignmentModelType, ParallelTextCorpus corpus,
ThotSmtParameters parameters = null, ITokenProcessor sourcePreprocessor = null,
ITokenProcessor targetPreprocessor = null, int maxCorpusCount = int.MaxValue)
{
Parameters = parameters ?? new ThotSmtParameters();
Parameters.Freeze();
_sourcePreprocessor = sourcePreprocessor ?? TokenProcessors.NoOp;
_targetPreprocessor = targetPreprocessor ?? TokenProcessors.NoOp;
_maxCorpusCount = maxCorpusCount;
_parallelCorpus = corpus;
_wordAlignmentModelType = wordAlignmentModelType;
// _modelWeightTuner = new MiraModelWeightTuner(swAlignClassName);
_modelWeightTuner = new SimplexModelWeightTuner(wordAlignmentModelType);
_tuneCorpusIndices = CreateTuneCorpus();
do
{
_tempDir = Path.Combine(Path.GetTempPath(), "thot-smt-train-" + Guid.NewGuid());
} while (Directory.Exists(_tempDir));
Directory.CreateDirectory(_tempDir);
_lmFilePrefix = Path.GetFileName(Parameters.LanguageModelFileNamePrefix);
_tmFilePrefix = Path.GetFileName(Parameters.TranslationModelFileNamePrefix);
_trainLMDir = Path.Combine(_tempDir, "lm");
_trainTMDir = Path.Combine(_tempDir, "tm_train");
}
public string ConfigFileName { get; }
public ThotSmtParameters Parameters { get; private set; }
public TrainStats Stats { get; } = new TrainStats();
public Func<ParallelTextSegment, int, bool> SegmentFilter { get; set; } = (s, i) => true;
private HashSet<int> CreateTuneCorpus()
{
int corpusCount = 0;
var invalidIndices = new HashSet<int>();
int index = 0;
foreach (ParallelTextSegment segment in _parallelCorpus.Segments)
{
if (IsSegmentValid(segment) && SegmentFilter(segment, index))
corpusCount++;
else
invalidIndices.Add(index);
index++;
if (corpusCount == _maxCorpusCount)
break;
}
Stats.TrainedSegmentCount = corpusCount;
int tuneCorpusCount = Math.Min((int)(corpusCount * 0.1), 1000);
var r = new Random(31415);
return new HashSet<int>(Enumerable.Range(0, corpusCount + invalidIndices.Count)
.Where(i => !invalidIndices.Contains(i))
.OrderBy(i => r.Next()).Take(tuneCorpusCount));
}
public virtual void Train(IProgress<ProgressStatus> progress = null, Action checkCanceled = null)
{
var reporter = new ThotTrainProgressReporter(progress, checkCanceled);
Directory.CreateDirectory(_trainLMDir);
string trainLMPrefix = Path.Combine(_trainLMDir, _lmFilePrefix);
Directory.CreateDirectory(_trainTMDir);
string trainTMPrefix = Path.Combine(_trainTMDir, _tmFilePrefix);
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
TrainLanguageModel(trainLMPrefix, 3);
TrainTranslationModel(trainTMPrefix, reporter);
reporter.CheckCanceled();
string tuneTMDir = Path.Combine(_tempDir, "tm_tune");
Directory.CreateDirectory(tuneTMDir);
string tuneTMPrefix = Path.Combine(tuneTMDir, _tmFilePrefix);
CopyFiles(_trainTMDir, tuneTMDir, _tmFilePrefix);
var tuneSourceCorpus = new List<IReadOnlyList<string>>(_tuneCorpusIndices.Count);
var tuneTargetCorpus = new List<IReadOnlyList<string>>(_tuneCorpusIndices.Count);
foreach (ParallelTextSegment segment in GetTuningSegments(_parallelCorpus))
{
tuneSourceCorpus.Add(_sourcePreprocessor.Process(segment.SourceSegment));
tuneTargetCorpus.Add(_targetPreprocessor.Process(segment.TargetSegment));
}
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
TuneLanguageModel(trainLMPrefix, tuneTargetCorpus, 3);
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
TuneTranslationModel(tuneTMPrefix, trainLMPrefix, tuneSourceCorpus, tuneTargetCorpus, phaseProgress);
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
TrainTuneCorpus(trainTMPrefix, trainLMPrefix, tuneSourceCorpus, tuneTargetCorpus, phaseProgress);
}
public virtual void Save()
{
SaveParameters();
string lmDir = Path.GetDirectoryName(Parameters.LanguageModelFileNamePrefix);
Debug.Assert(lmDir != null);
string tmDir = Path.GetDirectoryName(Parameters.TranslationModelFileNamePrefix);
Debug.Assert(tmDir != null);
if (!Directory.Exists(lmDir))
Directory.CreateDirectory(lmDir);
CopyFiles(_trainLMDir, lmDir, _lmFilePrefix);
if (!Directory.Exists(tmDir))
Directory.CreateDirectory(tmDir);
CopyFiles(_trainTMDir, tmDir, _tmFilePrefix);
}
public Task SaveAsync()
{
Save();
return Task.CompletedTask;
}
private void SaveParameters()
{
if (string.IsNullOrEmpty(ConfigFileName) || Parameters.ModelWeights == null)
return;
string[] lines = File.ReadAllLines(ConfigFileName);
using (var writer = new StreamWriter(ConfigFileName))
{
bool weightsWritten = false;
foreach (string line in lines)
{
if (ThotSmtParameters.GetConfigParameter(line, out string name, out string value) && name == "tmw")
{
WriteModelWeights(writer);
weightsWritten = true;
}
else
{
writer.Write($"{line}\n");
}
}
if (!weightsWritten)
WriteModelWeights(writer);
}
}
private void WriteModelWeights(StreamWriter writer)
{
writer.Write($"-tmw {string.Join(" ", Parameters.ModelWeights.Select(w => w.ToString("0.######")))}\n");
}
private static void CopyFiles(string srcDir, string destDir, string filePrefix)
{
foreach (string srcFile in Directory.EnumerateFiles(srcDir, filePrefix + "*"))
{
string fileName = Path.GetFileName(srcFile);
Debug.Assert(fileName != null);
File.Copy(srcFile, Path.Combine(destDir, fileName), true);
}
}
private void TrainLanguageModel(string lmPrefix, int ngramSize)
{
WriteNgramCountsFile(lmPrefix, ngramSize);
WriteLanguageModelWeightsFile(lmPrefix, ngramSize, Enumerable.Repeat(0.5, ngramSize * 3));
WriteWordPredictionFile(lmPrefix);
}
private void WriteNgramCountsFile(string lmPrefix, int ngramSize)
{
int wordCount = 0;
var ngrams = new Dictionary<Ngram<string>, int>();
var vocab = new HashSet<string>();
foreach (ParallelTextSegment segment in _parallelCorpus.Segments
.Where((s, i) => !_tuneCorpusIndices.Contains(i) && SegmentFilter(s, i) && s.TargetSegment.Count > 0))
{
var words = new List<string> { "<s>" };
foreach (string word in _targetPreprocessor.Process(segment.TargetSegment).Select(Thot.EscapeToken))
{
if (vocab.Contains(word))
{
words.Add(word);
}
else
{
vocab.Add(word);
words.Add("<unk>");
}
}
words.Add("</s>");
if (words.Count == 2)
continue;
wordCount += words.Count;
for (int n = 1; n <= ngramSize; n++)
{
for (int i = 0; i <= words.Count - n; i++)
{
var ngram = new Ngram<string>(Enumerable.Range(i, n).Select(j => words[j]));
ngrams.UpdateValue(ngram, () => 0, c => c + 1);
}
}
}
using (var writer = new StreamWriter(lmPrefix))
{
foreach (KeyValuePair<Ngram<string>, int> kvp in ngrams.OrderBy(kvp => kvp.Key.Length)
.ThenBy(kvp => string.Join(" ", kvp.Key)))
{
writer.Write("{0} {1} {2}\n", string.Join(" ", kvp.Key),
kvp.Key.Length == 1 ? wordCount : ngrams[kvp.Key.TakeAllExceptLast()], kvp.Value);
}
}
}
private static void WriteLanguageModelWeightsFile(string lmPrefix, int ngramSize, IEnumerable<double> weights)
{
File.WriteAllText(lmPrefix + ".weights",
$"{ngramSize} 3 10 {string.Join(" ", weights.Select(w => w.ToString("0.######")))}\n");
}
private void WriteWordPredictionFile(string lmPrefix)
{
var rand = new Random(31415);
using (var writer = new StreamWriter(lmPrefix + ".wp"))
{
foreach (ParallelTextSegment segment in _parallelCorpus.Segments
.Where((s, i) => !_tuneCorpusIndices.Contains(i) && SegmentFilter(s, i)
&& s.TargetSegment.Count > 0)
.Take(100000).OrderBy(i => rand.Next()))
{
string segmentStr = string.Join(" ", _targetPreprocessor.Process(segment.TargetSegment)
.Select(Thot.EscapeToken));
writer.Write("{0}\n", segmentStr);
}
}
}
private void TrainTranslationModel(string tmPrefix, ThotTrainProgressReporter reporter)
{
string invswmPrefix = tmPrefix + "_invswm";
GenerateWordAlignmentModel(invswmPrefix, _sourcePreprocessor, _targetPreprocessor, _parallelCorpus,
reporter);
string swmPrefix = tmPrefix + "_swm";
GenerateWordAlignmentModel(swmPrefix, _targetPreprocessor, _sourcePreprocessor, _parallelCorpus.Invert(),
reporter);
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
Thot.giza_symmetr1(swmPrefix + ".bestal", invswmPrefix + ".bestal", tmPrefix + ".A3.final", true);
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
Thot.phraseModel_generate(tmPrefix + ".A3.final", 10, tmPrefix + ".ttable", 20);
File.WriteAllText(tmPrefix + ".lambda", "0.7 0.7");
File.WriteAllText(tmPrefix + ".srcsegmlentable", "Uniform");
File.WriteAllText(tmPrefix + ".trgcutstable", "0.999");
File.WriteAllText(tmPrefix + ".trgsegmlentable", "Geometric");
}
private void GenerateWordAlignmentModel(string swmPrefix, ITokenProcessor sourcePreprocessor,
ITokenProcessor targetPreprocessor, ParallelTextCorpus corpus, ThotTrainProgressReporter reporter)
{
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
{
TrainWordAlignmentModel(swmPrefix, sourcePreprocessor, targetPreprocessor, corpus, phaseProgress);
}
reporter.CheckCanceled();
string ext = null;
switch (_wordAlignmentModelType)
{
case ThotWordAlignmentModelType.Hmm:
ext = ".hmm_lexnd";
break;
case ThotWordAlignmentModelType.Ibm1:
case ThotWordAlignmentModelType.Ibm2:
ext = ".ibm_lexnd";
break;
case ThotWordAlignmentModelType.FastAlign:
ext = ".fa_lexnd";
break;
}
Debug.Assert(ext != null);
PruneLexTable(swmPrefix + ext, 0.00001);
using (PhaseProgress phaseProgress = reporter.StartNextPhase())
{
GenerateBestAlignments(swmPrefix, swmPrefix + ".bestal", sourcePreprocessor, targetPreprocessor, corpus,
phaseProgress);
}
}
private static void PruneLexTable(string fileName, double threshold)
{
var entries = new List<Tuple<uint, uint, float>>();
#if THOT_TEXT_FORMAT
using (var reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split(' ');
entries.Add(Tuple.Create(uint.Parse(fields[0], CultureInfo.InvariantCulture),
uint.Parse(fields[1], CultureInfo.InvariantCulture),
float.Parse(fields[2], CultureInfo.InvariantCulture)));
}
}
#else
using (var reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
{
int pos = 0;
var length = (int)reader.BaseStream.Length;
while (pos < length)
{
uint srcIndex = reader.ReadUInt32();
pos += sizeof(uint);
uint trgIndex = reader.ReadUInt32();
pos += sizeof(uint);
float numer = reader.ReadSingle();
pos += sizeof(float);
reader.ReadSingle();
pos += sizeof(float);
entries.Add(Tuple.Create(srcIndex, trgIndex, numer));
}
}
#endif
#if THOT_TEXT_FORMAT
using (var writer = new StreamWriter(fileName))
#else
using (var writer = new BinaryWriter(File.Open(fileName, FileMode.Create)))
#endif
{
foreach (IGrouping<uint, Tuple<uint, uint, float>> g in entries.GroupBy(e => e.Item1).OrderBy(g => g.Key))
{
Tuple<uint, uint, float>[] groupEntries = g.OrderByDescending(e => e.Item3).ToArray();
double lcSrc = groupEntries.Select(e => e.Item3).Skip(1)
.Aggregate((double)groupEntries[0].Item3, (a, n) => LogSpace.Add(a, n));
double newLcSrc = -99999;
int count = 0;
foreach (Tuple<uint, uint, float> entry in groupEntries)
{
double prob = Math.Exp(entry.Item3 - lcSrc);
if (prob < threshold)
break;
newLcSrc = LogSpace.Add(newLcSrc, entry.Item3);
count++;
}
for (int i = 0; i < count; i++)
{
#if THOT_TEXT_FORMAT
writer.Write("{0} {1} {2:0.######} {3:0.######}\n", groupEntries[i].Item1,
groupEntries[i].Item2, groupEntries[i].Item3, newLcSrc);
#else
writer.Write(groupEntries[i].Item1);
writer.Write(groupEntries[i].Item2);
writer.Write(groupEntries[i].Item3);
writer.Write((float)newLcSrc);
#endif
}
}
}
}
private void TrainWordAlignmentModel(string swmPrefix, ITokenProcessor sourcePreprocessor,
ITokenProcessor targetPreprocessor, ParallelTextCorpus corpus, IProgress<ProgressStatus> progress)
{
var parameters = new ThotWordAlignmentParameters();
if (_wordAlignmentModelType == ThotWordAlignmentModelType.FastAlign)
{
parameters.FastAlignIterationCount = (int)Parameters.LearningEMIters;
}
else
{
parameters.Ibm1IterationCount = (int)Parameters.LearningEMIters;
parameters.Ibm2IterationCount = _wordAlignmentModelType == ThotWordAlignmentModelType.Ibm2
? (int)Parameters.LearningEMIters : 0;
parameters.HmmIterationCount = (int)Parameters.LearningEMIters;
parameters.Ibm3IterationCount = (int)Parameters.LearningEMIters;
parameters.Ibm4IterationCount = (int)Parameters.LearningEMIters;
}
using (var trainer = new ThotWordAlignmentModelTrainer(_wordAlignmentModelType, corpus, swmPrefix,
parameters, sourcePreprocessor, targetPreprocessor, _maxCorpusCount))
{
trainer.SegmentFilter = (s, i) => !_tuneCorpusIndices.Contains(i) && SegmentFilter(s, i);
trainer.Train(progress);
trainer.Save();
}
}
private void GenerateBestAlignments(string swmPrefix, string fileName, ITokenProcessor sourcePreprocessor,
ITokenProcessor targetPreprocessor, ParallelTextCorpus corpus, IProgress<ProgressStatus> progress)
{
var escapeTokenProcessor = new EscapeTokenProcessor();
sourcePreprocessor = TokenProcessors.Pipeline(sourcePreprocessor, escapeTokenProcessor);
targetPreprocessor = TokenProcessors.Pipeline(targetPreprocessor, escapeTokenProcessor);
using (var model = ThotWordAlignmentModel.Create(_wordAlignmentModelType))
using (var writer = new StreamWriter(fileName))
{
model.Load(swmPrefix);
int i = 0;
foreach (ParallelTextSegment segment in GetTrainingSegments(corpus))
{
progress.Report(new ProgressStatus(i, Stats.TrainedSegmentCount));
writer.Write($"# {segment.TextId} {segment.SegmentRef}\n");
writer.Write(model.GetGizaFormatString(segment, sourcePreprocessor, targetPreprocessor));
i++;
}
progress.Report(new ProgressStatus(1.0));
}
}
private void TuneLanguageModel(string lmPrefix, IList<IReadOnlyList<string>> tuneTargetCorpus, int ngramSize)
{
if (tuneTargetCorpus.Count == 0)
return;
var simplex = new NelderMeadSimplex(0.1, 200, 1.0);
MinimizationResult result = simplex.FindMinimum(w =>
CalculatePerplexity(tuneTargetCorpus, lmPrefix, ngramSize, w), Enumerable.Repeat(0.5, ngramSize * 3));
WriteLanguageModelWeightsFile(lmPrefix, ngramSize, result.MinimizingPoint);
Stats.Metrics["perplexity"] = result.ErrorValue;
}
private static double CalculatePerplexity(IList<IReadOnlyList<string>> tuneTargetCorpus, string lmPrefix,
int ngramSize, Vector weights)
{
if (weights.Any(w => w < 0 || w >= 1.0))
return 999999;
WriteLanguageModelWeightsFile(lmPrefix, ngramSize, weights);
double lp = 0;
int wordCount = 0;
using (var lm = new ThotLanguageModel(lmPrefix))
{
foreach (IReadOnlyList<string> segment in tuneTargetCorpus)
{
lp += lm.GetSegmentLog10Probability(segment);
wordCount += segment.Count;
}
}
return Math.Exp(-(lp / (wordCount + tuneTargetCorpus.Count)) * Math.Log(10));
}
private void TuneTranslationModel(string tuneTMPrefix, string tuneLMPrefix,
IReadOnlyList<IReadOnlyList<string>> tuneSourceCorpus,
IReadOnlyList<IReadOnlyList<string>> tuneTargetCorpus, IProgress<ProgressStatus> progress)
{
if (tuneSourceCorpus.Count == 0)
return;
string phraseTableFileName = tuneTMPrefix + ".ttable";
FilterPhraseTableUsingCorpus(phraseTableFileName, tuneSourceCorpus);
ThotSmtParameters oldParameters = Parameters;
ThotSmtParameters initialParameters = oldParameters.Clone();
initialParameters.TranslationModelFileNamePrefix = tuneTMPrefix;
initialParameters.LanguageModelFileNamePrefix = tuneLMPrefix;
initialParameters.ModelWeights = new[] { 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0f };
initialParameters.Freeze();
ThotSmtParameters tunedParameters = _modelWeightTuner.Tune(initialParameters, tuneSourceCorpus,
tuneTargetCorpus, Stats, progress);
Parameters = tunedParameters.Clone();
Parameters.TranslationModelFileNamePrefix = oldParameters.TranslationModelFileNamePrefix;
Parameters.LanguageModelFileNamePrefix = oldParameters.LanguageModelFileNamePrefix;
Parameters.Freeze();
}
private static void FilterPhraseTableUsingCorpus(string fileName, IEnumerable<IEnumerable<string>> sourceCorpus)
{
var phrases = new HashSet<string>();
foreach (IEnumerable<string> segment in sourceCorpus)
{
string[] segmentArray = segment.ToArray();
for (int i = 0; i < segmentArray.Length; i++)
{
for (int j = 0; j < segmentArray.Length && j + i < segmentArray.Length; j++)
{
var phrase = new StringBuilder();
for (int k = i; k <= i + j; k++)
{
if (k != i)
phrase.Append(" ");
phrase.Append(segmentArray[k]);
}
phrases.Add(phrase.ToString());
}
}
}
string tempFileName = fileName + ".temp";
using (var reader = new StreamReader(fileName))
using (var writer = new StreamWriter(tempFileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split(new[] { "|||" }, StringSplitOptions.RemoveEmptyEntries);
string phrase = fields[1].Trim();
if (phrases.Contains(phrase))
writer.Write("{0}\n", line);
}
}
File.Copy(tempFileName, fileName, true);
File.Delete(tempFileName);
}
private void TrainTuneCorpus(string trainTMPrefix, string trainLMPrefix,
IReadOnlyList<IReadOnlyList<string>> tuneSourceCorpus,
IReadOnlyList<IReadOnlyList<string>> tuneTargetCorpus, IProgress<ProgressStatus> progress)
{
if (tuneSourceCorpus.Count == 0)
return;
ThotSmtParameters parameters = Parameters.Clone();
parameters.TranslationModelFileNamePrefix = trainTMPrefix;
parameters.LanguageModelFileNamePrefix = trainLMPrefix;
using (var smtModel = new ThotSmtModel(_wordAlignmentModelType, parameters))
using (IInteractiveTranslationEngine engine = smtModel.CreateInteractiveEngine())
{
for (int i = 0; i < tuneSourceCorpus.Count; i++)
{
progress.Report(new ProgressStatus(i, tuneSourceCorpus.Count));
engine.TrainSegment(tuneSourceCorpus[i], tuneTargetCorpus[i]);
}
progress.Report(new ProgressStatus(1.0));
}
}
private IEnumerable<ParallelTextSegment> GetTrainingSegments(ParallelTextCorpus corpus)
{
return GetSegments(corpus, i => !_tuneCorpusIndices.Contains(i));
}
private IEnumerable<ParallelTextSegment> GetTuningSegments(ParallelTextCorpus corpus)
{
return GetSegments(corpus, i => _tuneCorpusIndices.Contains(i));
}
private IEnumerable<ParallelTextSegment> GetSegments(ParallelTextCorpus corpus, Func<int, bool> filter)
{
int corpusCount = 0;
int index = 0;
foreach (ParallelTextSegment segment in corpus.Segments)
{
if (IsSegmentValid(segment) && SegmentFilter(segment, index))
{
if (filter(index))
yield return segment;
corpusCount++;
}
index++;
if (corpusCount == _maxCorpusCount)
break;
}
}
private static bool IsSegmentValid(ParallelTextSegment segment)
{
return !segment.IsEmpty && segment.SourceSegment.Count <= TranslationConstants.MaxSegmentLength
&& segment.TargetSegment.Count <= TranslationConstants.MaxSegmentLength;
}
protected override void DisposeManagedResources()
{
Directory.Delete(_tempDir, true);
}
private class EscapeTokenProcessor : ITokenProcessor
{
public IReadOnlyList<string> Process(IReadOnlyList<string> tokens)
{
return tokens.Select(Thot.EscapeToken).ToArray();
}
}
}
}
|
using ExtendedXmlSerializer.Core.Sources;
using System;
namespace ExtendedXmlSerializer.ExtensionModel.Types.Sources
{
/// <summary>
/// Iterates through all public types found in the namespace of the provided reference type.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class PublicTypesInSameNamespace<T> : Items<Type>
{
/// <summary>
/// Creates a new instance.
/// </summary>
public PublicTypesInSameNamespace() : base(new PublicTypesInSameNamespace(typeof(T))) {}
}
/// <summary>
/// Iterates through all public types found in the namespace of the provided reference type.
/// </summary>
public sealed class PublicTypesInSameNamespace : Items<Type>
{
/// <summary>
/// Creates a new instance.
/// </summary>
/// <param name="referenceType">The reference type to query.</param>
public PublicTypesInSameNamespace(Type referenceType)
: base(new TypesInSameNamespace(referenceType, new AllAssemblyTypes(referenceType))) {}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace KerbalKonstructs.Core
{
class GrassColorUtils
{
internal static Color ManualCalcNewColor(Color oldColor, string oldTextrueName, string newTextureName)
{
if (String.IsNullOrEmpty(oldTextrueName) || oldTextrueName == "BUILTIN:/terrain_grass00_new")
{
oldTextrueName = "KerbalKonstructs/Assets/Colors/legacyGrassColors";
}
if (String.IsNullOrEmpty(newTextureName))
{
newTextureName = "BUILTIN:/terrain_grass00_new_detail";
}
Texture2D oldTexture = KKGraphics.GetTexture(oldTextrueName).BlitTexture(64);
Texture2D newTexture = KKGraphics.GetTexture(newTextureName).BlitTexture(64);
Color oldAvgTexColor = AverageColor(oldTexture.GetPixels());
Color newAvgTexColor = AverageColor(newTexture.GetPixels());
//Log.Normal("oldAvgTexColor: " + oldAvgTexColor.ToString());
//Log.Normal("newAvgTexColor: " + newAvgTexColor.ToString());
Color legacyColor = Color.Lerp(oldColor, oldAvgTexColor, oldColor.a);
legacyColor.a = 1;
//Color firstNewColor = newAvgTexColor * legacyColor;
//Log.Normal("firstNewColor : " + firstNewColor.ToString());
Color finalColor = legacyColor.DivideWith(newAvgTexColor).LimitTo(6f);
finalColor.a = 1;
//Log.Normal("final Color: " + finalColor.ToString());
return finalColor;
}
internal static Color GetAverageColor(string textureName)
{
Texture2D texture = KKGraphics.GetTexture(textureName).BlitTexture(64);
if (texture == null)
{
return Color.grey;
}
return AverageColor(texture.GetPixels());
}
internal static Color AverageColor(Color[] array)
{
Color sum = Color.clear;
for (var i = 0; i < array.Length; i++)
{
sum += array[i];
}
return (sum / array.Length);
}
internal static Color GetUnderGroundColor(StaticInstance staticInstance)
{
Color underGroundColor;
if (KerbalKonstructs.useCam)
{
underGroundColor = GrasColorCam.instance.GetCameraColor(staticInstance);
}
else
{
underGroundColor = GetSurfaceColorPQS(staticInstance.CelestialBody, staticInstance.RefLatitude, staticInstance.RefLongitude);
// Texture2D groundTex = GrasColorCam.instance.GetCameraTexture(staticInstance);
// if (groundTex != null)
// {
// Color textureColor = AverageColor(groundTex.GetPixels());
// Log.Normal("TextureColor: " + textureColor.ToString());
// underGroundColor += textureColor;
// }
// else
// {
// Log.Normal("No Texture received");
// }
}
Color avColor = GetAverageColor(staticInstance.GrasTexture);
underGroundColor = underGroundColor.DivideWith(avColor);
underGroundColor.a = 1;
return underGroundColor;
}
internal static Color GetUnderGroundColor(GrassColor2 selectedMod)
{
Color underGroundColor;
StaticInstance staticInstance = selectedMod.staticInstance;
if (KerbalKonstructs.useCam)
{
underGroundColor = GrasColorCam.instance.GetCameraColor(staticInstance);
}
else
{
underGroundColor = GetSurfaceColorPQS(staticInstance.CelestialBody, staticInstance.RefLatitude, staticInstance.RefLongitude);
//Texture2D groundTex = GrasColorCam.instance.GetCameraTexture(staticInstance);
//if (groundTex != null)
//{
// Color textureColor = AverageColor(groundTex.GetPixels());
// Log.Normal("TextureColor: " + textureColor.ToString());
// underGroundColor += textureColor;
//}
//else
//{
// Log.Normal("No Texture received");
//}
}
Color avColor = GetAverageColor(selectedMod.farGrassTextureName);
underGroundColor = underGroundColor.DivideWith(avColor);
underGroundColor.a = 1;
return underGroundColor;
}
/// <summary>
/// Uses the PQS System to query the color of the undergound
/// </summary>
/// <param name="body"></param>
/// <param name="lat"></param>
/// <param name="lon"></param>
/// <returns></returns>
public static Color GetSurfaceColorPQS(CelestialBody body, Double lat, Double lon)
{
// Tell the PQS that our actions are not supposed to end up in the terrain
body.pqsController.isBuildingMaps = true;
body.pqsController.isFakeBuild = true;
// Create the vertex information
PQS.VertexBuildData data = new PQS.VertexBuildData
{
directionFromCenter = body.GetRelSurfaceNVector(lat, lon).normalized,
//vertHeight = body.pqsController.radius
vertHeight = body.pqsController.GetSurfaceHeight(body.GetRelSurfaceNVector(lat, lon).normalized * body.Radius)
};
// Fetch all enabled Mods
//PQSMod[] mods = body.GetComponentsInChildren<PQSMod>(true).Where(m => m.modEnabled && m.sphere == body.pqsController).ToArray();
List<PQSMod> modsList = body.GetComponentsInChildren<PQSMod>(true).Where(m => m.modEnabled && m.sphere == body.pqsController).ToList();
modsList.Sort(delegate (PQSMod first, PQSMod second)
{
return first.order.CompareTo(second.order);
});
PQSMod[] mods = modsList.ToArray();
// Iterate over them and build the height at this point
// This is neccessary for mods that use the terrain height to
// color the terrain (like HeightColorMap)
foreach (PQSMod mod in mods)
{
mod.OnVertexBuildHeight(data);
}
// Iterate over the mods again, this time build the color component
foreach (PQSMod mod in mods)
{
mod.OnVertexBuild(data);
}
// Reset the PQS
body.pqsController.isBuildingMaps = false;
body.pqsController.isFakeBuild = false;
Color vertColor = data.vertColor;
vertColor += new Color(0.01f, 0.01f, 0.02f);
vertColor.a = 1;
// The terrain color is now stored in data.vertColor.
// For getting the height at this point you can use data.vertHeight
return vertColor;
}
}
}
|
/*
Write a C# Sharp program to print the result of dividing two numbers.
*/
using System;
namespace Exercice_03
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"The division of 15 by 3 = {(15/3)}");
}
}
}
|
namespace WindowsFormGridView
{
partial class QuerysInnerJoinDataSet1
{
partial class UsuariosDataTable
{
}
}
}
|
using DOTSSpriteRenderer.Components;
using DOTSSpriteRenderer.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;
using Random = Unity.Mathematics.Random;
namespace DOTSSpriteRenderer.Examples
{
[UpdateInGroup(typeof(LateSimulationSystemGroup))]
public class MakeSpritesSystem : ComponentSystem
{
EntityQuery spawnerQuery_;
void DoSpawn(SpriteSpawnerTest.SpawnData spawner, Material mat)
{
ComponentType[] type = new ComponentType[]
{
typeof(Position2D),
typeof(Rotation2D),
typeof(Scale),
typeof(SpriteSheetAnimation),
typeof(SpriteSheetMaterial),
typeof(SpriteSheetColor),
typeof(UVCell)
};
var em = EntityManager;
var archetype = em.CreateArchetype(type);
NativeArray<Entity> entities = new NativeArray<Entity>(spawner.spriteCount, Allocator.Temp);
em.CreateEntity(archetype, entities);
int cellCount = CachedUVData.GetCellCount(mat);
Random rand = new Random((uint)UnityEngine.Random.Range(0, int.MaxValue));
Rect area = spawner.GetSpawnArea();
SpriteSheetMaterial material = new SpriteSheetMaterial { material = mat };
var maxFrames = CachedUVData.GetCellCount(mat);
//Debug.Log("Spawning entities and setting components");
for (int i = 0; i < entities.Length; i++)
{
Entity e = entities[i];
Scale scale = new Scale { Value = rand.NextFloat(spawner.minScale, spawner.maxScale) };
float2 p = rand.NextFloat2(area.min, area.max);
Position2D pos = spawner.origin.xy + p;
Rotation2D rot = new Rotation2D { angle = spawner.rotation };
int numFrames = rand.NextInt(3, maxFrames / 2);
int minFrame = rand.NextInt(0, maxFrames - numFrames);
SpriteSheetAnimation anim = new SpriteSheetAnimation
{
play = true,
repetition = SpriteSheetAnimation.RepetitionType.Loop,
fps = rand.NextFloat(spawner.minFPS_, spawner.maxFPS_),
frameMin = minFrame,
frameMax = minFrame + numFrames
};
SpriteSheetColor color = UnityEngine.Random.ColorHSV(.35f, .75f);
UVCell cell = new UVCell { value = rand.NextInt(0, maxFrames) };
em.SetComponentData(e, scale);
em.SetComponentData(e, pos);
em.SetComponentData(e, anim);
em.SetComponentData(e, color);
em.SetComponentData(e, cell);
em.SetComponentData(e, rot);
em.SetSharedComponentData(e, material);
}
}
protected override void OnCreate()
{
base.OnCreate();
spawnerQuery_ = GetEntityQuery(typeof(SpriteSpawnerTest.SpawnData));
}
protected override void OnUpdate()
{
var spawners = spawnerQuery_.ToEntityArray(Allocator.TempJob);
var e = spawners[0];
var mat = EntityManager.GetSharedComponentData<SpriteSheetMaterial>(e).material;
var spawnData = EntityManager.GetComponentData<SpriteSpawnerTest.SpawnData>(e);
var entities = EntityManager.GetAllEntities(Allocator.TempJob);
EntityManager.DestroyEntity(entities);
DoSpawn(spawnData, mat);
entities.Dispose();
spawners.Dispose();
}
}
} |
using System.Collections.Generic;
using System.Linq;
using CarSalesSystem.Data;
namespace CarSalesSystem.Services.Categories
{
public class CategoryService : ICategoryService
{
private readonly CarSalesDbContext data;
public CategoryService(CarSalesDbContext data)
=> this.data = data;
public ICollection<VehicleCategory> GetVehicleCategories()
{
return this.data.VehicleCategories.ToList();
}
}
}
|
using System.ComponentModel;
namespace GroupMaker
{
public enum RelationshipTypeEnum
{
[Description("[Match With]")] MATCH,
[Description("[Don't Match With]")] DO_NOT_MATCH
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.