content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
namespace db_mapper.Common {
public class AppSettingsProvider : IAppSettingsProvider {
private readonly IConfigurationRoot configuration;
public AppSettingsProvider(string file = "appSettings.json") {
var filePath = Path.Combine(Environment.CurrentDirectory, file);
configuration = new ConfigurationBuilder()
.AddJsonFile(filePath)
.Build();
}
public string GetValue(string key) {
return configuration[key];
}
public int GetInt(string key) {
return int.Parse(GetValue(key));
}
public double GetDouble(string key) {
return double.Parse(GetValue(key));
}
public string GetConnectionString(string key = "Default") {
return configuration.GetConnectionString(key);
}
public T GetObject<T>(string key) {
return configuration.GetSection(key).Get<T>();
}
}
}
| 23.421053 | 67 | 0.732584 | [
"MIT"
] | jpshrader/db-mapper | Common/AppSettingsProvider.cs | 892 | C# |
namespace OnlyT.Utils
{
#pragma warning disable SA1121 // Use built-in type alias
// ReSharper disable BuiltInTypeReferenceStyle
// ReSharper disable IdentifierTypo
// ReSharper disable StyleCop.SA1602
// ReSharper disable InconsistentNaming
// ReSharper disable StyleCop.SA1121
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable FieldCanBeMadeReadOnly.Global
// ReSharper disable UnusedMember.Global
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Media.Imaging;
/// <summary>
/// Misc Native methods
/// </summary>
internal static class NativeMethods
{
private const int MAX_PATH = 260;
public enum SHSTOCKICONID : uint
{
SIID_DOCNOASSOC = 0,
SIID_DOCASSOC = 1,
SIID_APPLICATION = 2,
SIID_FOLDER = 3,
SIID_FOLDEROPEN = 4,
SIID_DRIVE525 = 5,
SIID_DRIVE35 = 6,
SIID_DRIVEREMOVE = 7,
SIID_DRIVEFIXED = 8,
SIID_DRIVENET = 9,
SIID_DRIVENETDISABLED = 10,
SIID_DRIVECD = 11,
SIID_DRIVERAM = 12,
SIID_WORLD = 13,
SIID_SERVER = 15,
SIID_PRINTER = 16,
SIID_MYNETWORK = 17,
SIID_FIND = 22,
SIID_HELP = 23,
SIID_SHARE = 28,
SIID_LINK = 29,
SIID_SLOWFILE = 30,
SIID_RECYCLER = 31,
SIID_RECYCLERFULL = 32,
SIID_MEDIACDAUDIO = 40,
SIID_LOCK = 47,
SIID_AUTOLIST = 49,
SIID_PRINTERNET = 50,
SIID_SERVERSHARE = 51,
SIID_PRINTERFAX = 52,
SIID_PRINTERFAXNET = 53,
SIID_PRINTERFILE = 54,
SIID_STACK = 55,
SIID_MEDIASVCD = 56,
SIID_STUFFEDFOLDER = 57,
SIID_DRIVEUNKNOWN = 58,
SIID_DRIVEDVD = 59,
SIID_MEDIADVD = 60,
SIID_MEDIADVDRAM = 61,
SIID_MEDIADVDRW = 62,
SIID_MEDIADVDR = 63,
SIID_MEDIADVDROM = 64,
SIID_MEDIACDAUDIOPLUS = 65,
SIID_MEDIACDRW = 66,
SIID_MEDIACDR = 67,
SIID_MEDIACDBURN = 68,
SIID_MEDIABLANKCD = 69,
SIID_MEDIACDROM = 70,
SIID_AUDIOFILES = 71,
SIID_IMAGEFILES = 72,
SIID_VIDEOFILES = 73,
SIID_MIXEDFILES = 74,
SIID_FOLDERBACK = 75,
SIID_FOLDERFRONT = 76,
SIID_SHIELD = 77,
SIID_WARNING = 78,
SIID_INFO = 79,
SIID_ERROR = 80,
SIID_KEY = 81,
SIID_SOFTWARE = 82,
SIID_RENAME = 83,
SIID_DELETE = 84,
SIID_MEDIAAUDIODVD = 85,
SIID_MEDIAMOVIEDVD = 86,
SIID_MEDIAENHANCEDCD = 87,
SIID_MEDIAENHANCEDDVD = 88,
SIID_MEDIAHDDVD = 89,
SIID_MEDIABLURAY = 90,
SIID_MEDIAVCD = 91,
SIID_MEDIADVDPLUSR = 92,
SIID_MEDIADVDPLUSRW = 93,
SIID_DESKTOPPC = 94,
SIID_MOBILEPC = 95,
SIID_USERS = 96,
SIID_MEDIASMARTMEDIA = 97,
SIID_MEDIACOMPACTFLASH = 98,
SIID_DEVICECELLPHONE = 99,
SIID_DEVICECAMERA = 100,
SIID_DEVICEVIDEOCAMERA = 101,
SIID_DEVICEAUDIOPLAYER = 102,
SIID_NETWORKCONNECT = 103,
SIID_INTERNET = 104,
SIID_ZIPFILE = 105,
SIID_SETTINGS = 106,
SIID_DRIVEHDDVD = 132,
SIID_DRIVEBD = 133,
SIID_MEDIAHDDVDROM = 134,
SIID_MEDIAHDDVDR = 135,
SIID_MEDIAHDDVDRAM = 136,
SIID_MEDIABDROM = 137,
SIID_MEDIABDR = 138,
SIID_MEDIABDRE = 139,
SIID_CLUSTEREDDRIVE = 140,
SIID_MAX_ICONS = 175
}
[Flags]
public enum SHGSI : uint
{
SHGSI_ICONLOCATION = 0,
SHGSI_ICON = 0x000000100,
SHGSI_SYSICONINDEX = 0x000004000,
SHGSI_LINKOVERLAY = 0x000008000,
SHGSI_SELECTED = 0x000010000,
SHGSI_LARGEICON = 0x000000000,
SHGSI_SMALLICON = 0x000000001,
SHGSI_SHELLICONSIZE = 0x000000004
}
[DllImport("user32.dll")]
public static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll")]
public static extern bool GetWindowPlacement(IntPtr hWnd, out WINDOWPLACEMENT lpwndpl);
[DllImport("Shell32.dll", SetLastError = false)]
public static extern Int32 SHGetStockIconInfo(SHSTOCKICONID siid, SHGSI uFlags, ref SHSTOCKICONINFO psii);
public static BitmapSource GetElevatedShieldBitmap()
{
var sii = new SHSTOCKICONINFO
{
cbSize = (UInt32)Marshal.SizeOf(typeof(SHSTOCKICONINFO))
};
Marshal.ThrowExceptionForHR(SHGetStockIconInfo(
SHSTOCKICONID.SIID_SHIELD,
SHGSI.SHGSI_ICON | SHGSI.SHGSI_SMALLICON,
ref sii));
var shieldSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
sii.hIcon,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
DestroyIcon(sii.hIcon);
return shieldSource;
}
[DllImport("user32.dll", SetLastError = true)]
private static extern bool DestroyIcon(IntPtr hIcon);
[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHSTOCKICONINFO
{
public UInt32 cbSize;
public IntPtr hIcon;
public Int32 iSysIconIndex;
public Int32 iIcon;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
public string szPath;
}
}
#pragma warning restore SA1121 // Use built-in type alias
}
| 33.027174 | 114 | 0.561461 | [
"MIT"
] | diagdave1/OnlyT-1 | OnlyT/Utils/NativeMethods.cs | 6,079 | C# |
using System;
using Microsoft.EntityFrameworkCore;
using SmokeApp_Storage.Models;
using Serilog;
using Xunit;
//using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Linq;
namespace SmokeAppConsoleForTesting
{
class Program
{
static void Main(string[] args)
{
using (SmokeDBContext context = new SmokeDBContext())
{
var users = context.Users.FromSqlRaw<User>("SELECT * FROM Users").ToList();
foreach (var x in users)
{
Console.WriteLine($"The Users in the Database are FirstName: {x.FirstName} LastName: {x.LastName} Email: {x.Email} DOB: {x.Dob}");
}
}
Console.WriteLine("Hello World!");
}
/*
[Fact]
public async Task Test1()
{
Log.Logger = new LoggerConfiguration().WriteTo.File(_logFilePath).CreateLogger();
apiKey = "529258b2f69a47c79b806e2c88a9c75f";
client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip });
client.DefaultRequestHeaders.Add("Api_Key", apiKey);
client.Timeout = TimeSpan.FromMinutes(10);
Api_E_Game games = await SendRequestAsync<Api_E_Game>(Endpoint + $"games?key={apiKey}");
}*/
}
}
| 26.265306 | 140 | 0.682984 | [
"MIT"
] | 08162021-dotnet-uta/BlakeDrostRepo1 | projects/project_2/SmokeApp/SmokeAppConsoleForTesting/Program.cs | 1,289 | C# |
using BPSLib.Util;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BPS_UnitTest.Util
{
[TestClass]
public class BPSPathTest
{
[TestMethod]
public void NormalizeTest()
{
// Arrange
string path = "c:\\users\\name.bps";
// Act
string normalized = BPSPath.Normalize("c:\\users\\name");
// Assert
Assert.AreEqual(path, normalized);
}
[TestMethod]
public void NormalizeTest_WithoutChange()
{
// Arrange
string path = "c:\\users\\name.bps";
// Act
string normalized = BPSPath.Normalize("c:\\users\\name.bps");
// Assert
Assert.AreEqual(path, normalized);
}
[TestMethod]
public void RemoveExtensionTest()
{
// Arrange
string path = "c:\\users\\name";
// Act
string normalized = BPSPath.RemoveExtension("c:\\users\\name.bps");
// Assert
Assert.AreEqual(path, normalized);
}
[TestMethod]
public void RemoveExtensionTest_WithoutChange()
{
// Arrange
string path = "c:\\users\\name";
// Act
string normalized = BPSPath.RemoveExtension("c:\\users\\name");
// Assert
Assert.AreEqual(path, normalized);
}
}
}
| 18.209677 | 70 | 0.65279 | [
"MIT"
] | BPS-Lib/BPS-3 | BPS Project/BPS UnitTest/Util/BPSPathTest.cs | 1,131 | C# |
namespace FluentILUnitTests.Resources
{
public interface ITestInterface
{
string GetSetProperty { get; set; }
}
} | 19 | 43 | 0.676692 | [
"MIT"
] | arlm/FluentIL | test/FluentILUnitTests/Resources/ITestInterface.cs | 133 | C# |
namespace Loon.Java
{
using System;
using System.Collections.Generic;
using System.IO;
using Loon.Java.Generics;
using Loon.Core;
public class SequenceInputStream : InputStream
{
Loon.Java.Generics.JavaListInterface.IIterator<Stream> e;
InputStream ins;
public SequenceInputStream(Loon.Java.Generics.JavaListInterface.IIterator<Stream> e)
{
this.e = e;
try
{
NextStream();
}
catch (Exception ex)
{
Console.Error.WriteLine("panic" + ex.Message);
}
}
public SequenceInputStream(InputStream s1, InputStream s2)
{
List<Stream> v = new List<Stream>(2);
v.Add(s1);
v.Add(s2);
e = new Loon.Java.Generics.IteratorAdapter<Stream>(v.GetEnumerator());
try
{
NextStream();
}
catch (IOException ex)
{
Console.Error.WriteLine("panic" + ex.Message);
}
}
void NextStream()
{
if (ins != null)
{
ins.Close();
}
if (e.HasNext())
{
ins = e.Next();
if (ins == null)
{
throw new Exception();
}
}
else
{
ins = null;
}
}
public override int Available()
{
if (ins == null)
{
return 0;
}
return ins.Available();
}
public override int Read()
{
if (ins == null)
{
return -1;
}
int c = ins.Read();
if (c == -1)
{
NextStream();
return Read();
}
return c;
}
public override int Read(byte[] b, int off, int len)
{
if (ins == null)
{
return -1;
}
else if (b == null)
{
throw new Exception();
}
else if (off < 0 || len < 0 || len > b.Length - off)
{
throw new Exception();
}
else if (len == 0)
{
return 0;
}
int n = ins.Read(b, off, len);
if (n <= 0)
{
NextStream();
return Read(b, off, len);
}
return n;
}
public override void Close()
{
do
{
NextStream();
} while (ins != null);
}
}
}
| 22.132813 | 92 | 0.364278 | [
"Apache-2.0"
] | TheMadTitanSkid/LGame | C#/Loon2Unity/Loon.Java/SequenceInputStream.cs | 2,833 | C# |
using BurningKnight.assets.prefabs;
using BurningKnight.level.rooms.entrance;
using BurningKnight.level.tile;
namespace BurningKnight.level.hall {
public class HallRoom : ExitRoom {
public const string PrefabName = "hub";
private Prefab prefab;
public HallRoom() {
prefab = Prefabs.Get(PrefabName);
}
public override void Paint(Level level) {
Painter.Clip = null;
Painter.Fill(level, this, Tile.Chasm);
Painter.Prefab(level, PrefabName, Left + 1, Top + 1);
}
public override void PaintFloor(Level level) {
}
public override int GetMinWidth() {
return prefab.Level.Width;
}
public override int GetMaxWidth() {
return prefab.Level.Width + 1;
}
public override int GetMinHeight() {
return prefab.Level.Height;
}
public override int GetMaxHeight() {
return prefab.Level.Height + 1;
}
public override bool ConvertToEntity() {
return false;
}
}
} | 21.931818 | 57 | 0.666321 | [
"MIT"
] | Cuber01/BurningKnight | BurningKnight/level/hall/HallRoom.cs | 965 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//-----------------------------------------------------------------------
// <copyright file="MetaModel.Methods.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved. THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// </copyright>
// <summary>Helper methods for the MetaModel class.</summary>
//-----------------------------------------------------------------------
#region Using Directives
using System.IO;
using System.Xml.Serialization;
#endregion
namespace Microsoft.AzureIntegrationMigration.BizTalk.Types.Entities.Orchestrations
{
/// <summary>
/// Helper methods for the <see cref="MetaModel"/> class.
/// </summary>
public partial class MetaModel
{
/// <summary>
/// Returns a <see cref="MetaModel"/> object deserialized from XML.
/// </summary>
/// <param name="xml">The XML to create the MetaModel from.</param>
/// <returns>The <see cref="MetaModel"/> object as defined in the supplied XML.</returns>
public static MetaModel FromXml(string xml)
{
MetaModel metaModel;
var xmlSerializer = new XmlSerializer(typeof(MetaModel));
using (var r = new StringReader(xml))
{
metaModel = (MetaModel)xmlSerializer.Deserialize(r);
}
return metaModel;
}
}
}
| 37.883721 | 279 | 0.604665 | [
"MIT"
] | 345James/aimbiztalk | src/Microsoft.AzureIntegrationMigration.BizTalk.Types/Entities/Orchestrations/MetaModel.Methods.cs | 1,631 | C# |
/* Poly2Tri
* Copyright (c) 2009-2010, Poly2Tri Contributors
* http://code.google.com/p/poly2tri/
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Poly2Tri nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Changes from the Java version
// Replaced get/set Next/Previous with attributes
// Future possibilities
// Documentation!
namespace Poly2Tri.Triangulation.Polygon
{
public class PolygonPoint : TriangulationPoint
{
public PolygonPoint(double x, double y) : base(x, y) { }
public PolygonPoint Next { get; set; }
public PolygonPoint Previous { get; set; }
public static explicit operator UnityEngine.Vector3(PolygonPoint p)
{
return new UnityEngine.Vector3(p.Xf, 0, p.Yf);
}
public static explicit operator PolygonPoint(UnityEngine.Vector3 p)
{
return new PolygonPoint(p.x, p.z);
}
}
}
| 40.789474 | 84 | 0.729032 | [
"MIT"
] | RosaryMala/BlaseballStadiumViewer | Assets/Scripts/libs/Poly2Tri/Triangulation/Polygon/PolygonPoint.cs | 2,327 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace RotaMe.Data.Models
{
public class EventNeed : BaseModel<int>
{
[Required]
public int EventId { get; set; }
public Event Event { get; set; }
public DateTime Date { get; set; }
[Required]
public int MinimalUsers { get; set; }
[Required]
public int MaximumUsers { get; set; }
public ICollection<Note> Notes { get; set; } = new List<Note>();
}
}
| 19.925926 | 72 | 0.605948 | [
"MIT"
] | MDaskalovAtBE/rotaMe | Data/RotaMe.Data.Models/EventNeed.cs | 540 | C# |
using LeagueDraft.Data;
using LeagueDraft.Models;
using LeagueDraft.Services.Implementations;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace LeagueDraft.Tests.Service
{
public class ItemServiceTests
{
[Fact]
public async Task GetRandomBuildAsync_WithCorrectData_ShouldReturnRandomBuildWithBoots()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomBuildAsync();
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Boots));
}
[Fact]
public async Task GetRandomBuildAsync_WithCorrectData_ShouldReturnRandomBuildWithSixItems()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomBuildAsync();
Assert.Equal(6, getRandomBuild.Count());
}
[Fact]
public async Task GetRandomBuildAsync_WithIncorrectData_ShouldntReturnCompleteRandomBuild()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
var getRandomBuild = await itemService.GetRandomBuildAsync();
Assert.True(getRandomBuild.Count() < 6);
}
[Fact]
public async Task GetRandomJungleBuildAsync_WithCorrectData_ShouldReturnRandomJungleBuildWithBoots()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomJungleBuildAsync();
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Boots));
}
[Fact]
public async Task GetRandomJungleBuildAsync_WithCorrectData_ShouldReturnRandomJungleBuildWithJungleItem()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomJungleBuildAsync();
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Jungle));
}
[Fact]
public async Task GetRandomJungleBuildAsync_WithCorrectData_ShouldReturnRandomJungleBuildWithSixItems()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomJungleBuildAsync();
Assert.Equal(6, getRandomBuild.Count());
}
[Fact]
public async Task GetRandomJungleBuildAsync_WithIncorrectData_ShouldntReturnCompleteRandomJungleBuild()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
var getRandomBuild = await itemService.GetRandomJungleBuildAsync();
Assert.True(getRandomBuild.Count() < 6);
}
[Fact]
public async Task GetRandomSupportBuildAsync_WithCorrectData_ShouldReturnRandomSupportBuildWithBoots()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomSupportBuildAsync();
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Boots));
}
[Fact]
public async Task GetRandomSupportBuildAsync_WithCorrectData_ShouldReturnRandomSupportBuildWithJSupportItem()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomSupportBuildAsync();
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Support));
}
[Fact]
public async Task GetRandomSupportBuildAsync_WithCorrectData_ShouldReturnRandomSupportBuildWithSixItems()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
var getRandomBuild = await itemService.GetRandomSupportBuildAsync();
Assert.Equal(6, getRandomBuild.Count());
}
[Fact]
public async Task GetRandomSupportBuildAsync_WithIncorrectData_ShouldntReturnCompleteRandomSupportBuild()
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
var getRandomBuild = await itemService.GetRandomSupportBuildAsync();
Assert.True(getRandomBuild.Count() < 6);
}
[Theory]
[InlineData(1)]
[InlineData(3)]
[InlineData(4)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForTopOrMidOrBotPositonWithBoots(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Boots));
}
[Theory]
[InlineData(1)]
[InlineData(3)]
[InlineData(4)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForTopOrMidOrBotPositon(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.Equal(6, getRandomBuild.Count());
}
[Theory]
[InlineData(1)]
[InlineData(3)]
[InlineData(4)]
public async Task GetRandomBuildForPositionAsync_WithInorrectData_ShouldntReturnCompleteRandomBuildForTopOrMidOrBotPositon(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.True(getRandomBuild.Count() < 6);
}
[Theory]
[InlineData(2)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForJunglePositonWithBoots(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Boots));
}
[Theory]
[InlineData(2)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForJunglePositonWithJungleItem(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Jungle));
}
[Theory]
[InlineData(2)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForJunglePositonWithSixItems(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.True(getRandomBuild.Count() == 6);
}
[Theory]
[InlineData(2)]
public async Task GetRandomBuildForPositionAsync_WithIncorrectData_ShouldntReturnCompleteRandomBuildForJunglePositon(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.True(getRandomBuild.Count() == 6);
}
[Theory]
[InlineData(5)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForSupportPositonWithBoots(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Boots));
}
[Theory]
[InlineData(5)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForSupportPositonWithSupportItem(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.Contains(getRandomBuild, x => x.Type.Equals(ItemType.Support));
}
[Theory]
[InlineData(5)]
public async Task GetRandomBuildForPositionAsync_WithCorrectData_ShouldReturnRandomBuildForSupportPositonWithSixItems(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.True(getRandomBuild.Count() == 6);
}
[Theory]
[InlineData(5)]
public async Task GetRandomBuildForPositionAsync_WithIncorrectData_ShouldntReturnCompleteRandomBuildForSupportPositon(int id)
{
var options = new DbContextOptionsBuilder<LeagueDraftDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
var context = new LeagueDraftDbContext(options);
var itemService = new ItemService(context);
SeedTestItems(context);
SeedTestPositions(context);
var getRandomBuild = await itemService.GetRandomBuildForPositionAsync(id);
Assert.True(getRandomBuild.Count() == 6);
}
private List<Item> GetTestItems()
{
return new List<Item>()
{
new Item
{
Name="testBoots",
Type = ItemType.Boots
},
new Item
{
Name="testJungleItem",
Type = ItemType.Jungle
},
new Item
{
Name="testSupportItem",
Type = ItemType.Support
},
new Item
{
Name="testItemOne",
Type = ItemType.Other
},
new Item
{
Name="testItemTwo",
Type = ItemType.Other
},
new Item
{
Name="testItemThree",
Type = ItemType.Other
},
new Item
{
Name="testItemFour",
Type = ItemType.Other
},
new Item
{
Name="testItemFive",
Type = ItemType.Other
}
};
}
private void SeedTestItems(LeagueDraftDbContext context)
{
context.Items.AddRange(GetTestItems());
context.SaveChanges();
}
private List<Position> GetTestPositions()
{
return new List<Position>()
{
new Position
{
Id=1,
Name="Top"
},
new Position
{
Id=2,
Name="Jungle"
},
new Position
{
Id=3,
Name="Mid"
},
new Position
{
Id=4,
Name="Bottom"
},
new Position
{
Id=5,
Name="Support"
}
};
}
private void SeedTestPositions(LeagueDraftDbContext context)
{
context.Positions.AddRange(GetTestPositions());
context.SaveChanges();
}
}
}
| 33.725714 | 138 | 0.603185 | [
"MIT"
] | Valentinles/League-Draft | src/LeagueDraft.Tests/Service/ItemServiceTests.cs | 17,708 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the codeguruprofiler-2019-07-18.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CodeGuruProfiler.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeGuruProfiler.Model.Internal.MarshallTransformations
{
/// <summary>
/// BatchGetFrameMetricData Request Marshaller
/// </summary>
public class BatchGetFrameMetricDataRequestMarshaller : IMarshaller<IRequest, BatchGetFrameMetricDataRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((BatchGetFrameMetricDataRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(BatchGetFrameMetricDataRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeGuruProfiler");
request.Headers["Content-Type"] = "application/json";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2019-07-18";
request.HttpMethod = "POST";
if (!publicRequest.IsSetProfilingGroupName())
throw new AmazonCodeGuruProfilerException("Request object does not have required field ProfilingGroupName set");
request.AddPathResource("{profilingGroupName}", StringUtils.FromString(publicRequest.ProfilingGroupName));
if (publicRequest.IsSetEndTime())
request.Parameters.Add("endTime", StringUtils.FromDateTimeToISO8601(publicRequest.EndTime));
if (publicRequest.IsSetPeriod())
request.Parameters.Add("period", StringUtils.FromString(publicRequest.Period));
if (publicRequest.IsSetStartTime())
request.Parameters.Add("startTime", StringUtils.FromDateTimeToISO8601(publicRequest.StartTime));
if (publicRequest.IsSetTargetResolution())
request.Parameters.Add("targetResolution", StringUtils.FromString(publicRequest.TargetResolution));
request.ResourcePath = "/profilingGroups/{profilingGroupName}/frames/-/metrics";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetFrameMetrics())
{
context.Writer.WritePropertyName("frameMetrics");
context.Writer.WriteArrayStart();
foreach(var publicRequestFrameMetricsListValue in publicRequest.FrameMetrics)
{
context.Writer.WriteObjectStart();
var marshaller = FrameMetricMarshaller.Instance;
marshaller.Marshall(publicRequestFrameMetricsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
request.UseQueryString = true;
return request;
}
private static BatchGetFrameMetricDataRequestMarshaller _instance = new BatchGetFrameMetricDataRequestMarshaller();
internal static BatchGetFrameMetricDataRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static BatchGetFrameMetricDataRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.449612 | 161 | 0.637792 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/CodeGuruProfiler/Generated/Model/Internal/MarshallTransformations/BatchGetFrameMetricDataRequestMarshaller.cs | 5,218 | C# |
using CreativeCoders.Core.ObjectLinking;
using JetBrains.Annotations;
namespace CreativeCoders.Mvvm.Ribbon.Controls
{
[PublicAPI]
public abstract class RibbonBaseButtonViewModel : RibbonCommandControlViewModel
{
private RibbonButtonSize _size;
private string _largeIcon;
private string _smallIcon;
protected RibbonBaseButtonViewModel() {}
protected RibbonBaseButtonViewModel(ActionViewModel action) : base(action) {}
public RibbonButtonSize Size
{
get => _size;
set => Set(ref _size, value);
}
[PropertyLink(typeof(ActionViewModel), nameof(ActionViewModel.LargeIcon), Direction = LinkDirection.TwoWay, InitWithTargetValue = true)]
public string LargeIcon
{
get => _largeIcon;
set => Set(ref _largeIcon, value);
}
[PropertyLink(typeof(ActionViewModel), nameof(ActionViewModel.SmallIcon), Direction = LinkDirection.TwoWay, InitWithTargetValue = true)]
public string SmallIcon
{
get => _smallIcon;
set => Set(ref _smallIcon, value);
}
}
}
| 29.225 | 144 | 0.644996 | [
"Apache-2.0"
] | CreativeCodersTeam/Core | source/Mvvm/CreativeCoders.Mvvm.Ribbon/Controls/RibbonBaseButtonViewModel.cs | 1,171 | C# |
namespace PuzzleCMS.Core.Multitenancy
{
using System;
using System.Collections.Generic;
/// <summary>
/// Context of the tenant.
/// </summary>
/// <typeparam name="TTenant">Tenant object.</typeparam>
public class TenantContext<TTenant> : IDisposable
{
private bool disposed;
/// <summary>
/// Initializes a new instance of the <see cref="TenantContext{TTenant}"/> class.
/// </summary>
/// <param name="tenant">Tenant object.</param>
/// <param name="position">position</param>
public TenantContext(TTenant tenant,int position)
{
if (tenant == null)
{
throw new ArgumentNullException($"Argument {nameof(tenant)} must not be null");
}
if (position < 0)
{
throw new ArgumentException($"Argument {nameof(position)} cannot be negative.");
}
Position = position;
Tenant = tenant;
Properties = new Dictionary<string, object>();
}
/// <summary>
/// Gets uniqueId that identify the tenant.
/// </summary>
public string Id { get; } = Guid.NewGuid().ToString();
/// <summary>
/// Gets uniqueId that identify the tenant.
/// </summary>
public int Position { get; private set; }
/// <summary>
/// Gets tenant object.
/// </summary>
public TTenant Tenant { get; private set; }
/// <summary>
/// Gets additional store data for a tenant.
/// </summary>
public IDictionary<string, object> Properties { get; }
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
foreach (KeyValuePair<string, object> prop in Properties)
{
TryDisposeProperty(prop.Value as IDisposable);
}
TryDisposeProperty(Tenant as IDisposable);
}
disposed = true;
}
private void TryDisposeProperty(IDisposable obj)
{
if (obj == null)
{
return;
}
try
{
obj.Dispose();
}
catch (ObjectDisposedException)
{
}
}
}
}
| 26.115385 | 96 | 0.47975 | [
"MIT"
] | Courio-Dev/UnobtrusiveMultitenancy | src/PuzzleCMS.Core/PuzzleCMS.Core.Multitenancy/TenantContext`1.cs | 2,718 | C# |
using ArticleDemo.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace ArticleDemo.MVC.UI.Core
{
public class CustomActionFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// 角色名称,具有访问该Action权限的角色
/// 多个角色使用英文逗号(,)分隔
/// </summary>
public string Roles { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
//登录页面不做权限判断
RouteValueDictionary routeDic = filterContext.RouteData.Values;
if (routeDic["controller"].ToString().ToLower().Equals("login")
&& routeDic["action"].ToString().ToLower().Equals("signinview"))
{
return;
}
//当前未登录,重定向到登录页
if (ContextObjects.CurrentUser == null)
{
filterContext.Result = new RedirectResult("/Login/SignInView");
return;
}
//是否具有访问权限,默认为false
bool isAuthorize = false;
//已登录用户,判断权限
//ContextObjects.CurrentUser.Roles 当登录时从数据库读取
//若当前用户无角色配置,则无访问权限
if (!string.IsNullOrEmpty(ContextObjects.CurrentUser.Roles))
{
//特性中配置的角色,具有访问该action权限的角色
string[] requireRoles = Roles.Split(',');
//当前用户所具有的角色
string[] userRoles = ContextObjects.CurrentUser.Roles.Split(',');
//判断是否有匹配角色
foreach (string rRole in requireRoles)
{
if (userRoles.Contains(rRole)) { isAuthorize = true; break; }
}
}
if (!isAuthorize)
{
ContentResult content = new ContentResult();
content.Content = "对不起,您无访问权限!";
//content.Content = @"<script type='text/javascript'>alert('对不起,您无访问权限!');</script>";
filterContext.Result = content;
}
}
}
} | 30.869565 | 101 | 0.542254 | [
"Apache-2.0"
] | imwyw/.net | Src/ArticleDemo/ArticleDemo.MVC.UI/Core/CustomActionFilterAttribute.cs | 2,452 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.CloudAPI.Transform;
using Aliyun.Acs.CloudAPI.Transform.V20160714;
using System.Collections.Generic;
namespace Aliyun.Acs.CloudAPI.Model.V20160714
{
public class DescribeRegionsRequest : RpcAcsRequest<DescribeRegionsResponse>
{
public DescribeRegionsRequest()
: base("CloudAPI", "2016-07-14", "DescribeRegions", "apigateway", "openAPI")
{
}
private string securityToken;
private string action;
private string language;
private string accessKeyId;
public string SecurityToken
{
get
{
return securityToken;
}
set
{
securityToken = value;
DictionaryUtil.Add(QueryParameters, "SecurityToken", value);
}
}
public string Action
{
get
{
return action;
}
set
{
action = value;
DictionaryUtil.Add(QueryParameters, "Action", value);
}
}
public string Language
{
get
{
return language;
}
set
{
language = value;
DictionaryUtil.Add(QueryParameters, "Language", value);
}
}
public string AccessKeyId
{
get
{
return accessKeyId;
}
set
{
accessKeyId = value;
DictionaryUtil.Add(QueryParameters, "AccessKeyId", value);
}
}
public override DescribeRegionsResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext)
{
return DescribeRegionsResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 24.237624 | 115 | 0.678513 | [
"Apache-2.0"
] | fossabot/aliyun-openapi-net-sdk | aliyun-net-sdk-cloudapi/CloudAPI/Model/V20160714/DescribeRegionsRequest.cs | 2,448 | C# |
using Android.Content;
using Plugin.Toast.Droid;
using System;
using System.Runtime.Serialization;
using System.Threading;
namespace Plugin.Toast
{
public sealed partial class ToastId : IEquatable<ToastId>
{
int id;
string tag;
/// <summary>
/// First part of identifier used by
/// <see cref="AndroidNotificationManager.NotificationManager"/>
/// </summary>
[DataMember]
public int Id
{
get => id;
[Obsolete(KObsoleteMessage, true)]
set => id = value;
}
/// <summary>
/// Second part of identifier used by
/// <see cref="AndroidNotificationManager.NotificationManager"/>
/// </summary>
[DataMember]
public string Tag
{
get => tag;
[Obsolete(KObsoleteMessage, true)]
set => tag = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="ToastId"/> class.
/// </summary>
/// <param name="id">First part of identifier used by
/// <see cref="AndroidNotificationManager.NotificationManager"/></param>
/// <param name="tag">Second part of identifier used by
/// <see cref="AndroidNotificationManager.NotificationManager"/></param>
public ToastId(int id, string tag)
{
this.id = id;
this.tag = tag;
}
(int id, string tag) AsTuple() => (Id, Tag);
static int idGenerator;
/// <summary>
/// Creates a new <see cref="ToastId"/> with unique pair of values
/// </summary>
/// <returns>new <see cref="ToastId"/></returns>
public static ToastId New()
=> new ToastId(Interlocked.Increment(ref idGenerator), Guid.NewGuid().ToString());
const int KInvalidId = -1;
/// <summary>
/// Construct <see cref="ToastId"/> from <see cref="Intent"/>.
/// </summary>
/// <param name="intent">Intent to check</param>
/// <returns><see cref="ToastId"/> if the required data was found in the <see cref="Intent"/>, otherwise null</returns>
public static ToastId? FromIntent(Intent? intent)
{
if (intent != null)
{
int notificationId = intent.Extras?.GetInt(IntentConstants.KNotificationId, KInvalidId) ?? KInvalidId;
string? notificationTag = intent.Extras?.GetString(IntentConstants.KNotifcationTag);
if (notificationId != KInvalidId && notificationTag != null)
return new ToastId(notificationId, notificationTag);
}
return null;
}
/// <summary>
/// Write <see cref="ToastId"/> to <see cref="Intent"/>
/// </summary>
/// <param name="intent">Intent to store data</param>
public void ToIntent(Intent intent)
{
intent.PutExtra(IntentConstants.KNotifcationTag, Tag);
intent.PutExtra(IntentConstants.KNotificationId, Id);
}
bool PlatformEquals(ToastId? other) => other != null && AsTuple() == other.AsTuple();
bool PlatformEquals(object? obj) => PlatformEquals(obj as ToastId);
private int PlatformGetHashCode() => (Id, Tag).GetHashCode();
private string PlatformToString() => string.Format("Id: {0}, Tag: {1}", Id, Tag);
private int GetPlatformPersistentHashCode()
=> CombineHashCode(CombineHashCode(KMagicSeed, Id), Tag);
}
}
| 35.42 | 127 | 0.572276 | [
"MIT"
] | anton-yashin/Plugin.Toast | src/Plugin.Toast/ToastId.android.cs | 3,544 | C# |
#region License
//
// Copyright (c) 2013, Kooboo team
//
// Licensed under the BSD License
// See the file LICENSE.txt for details.
//
#endregion
using System;
using System.Linq;
using System.Collections.Generic;
using Kooboo.CMS.Sites.Models;
using Kooboo.CMS.Sites.View;
using Kooboo.Globalization;
using Kooboo.CMS.Sites.Caching;
using System.Web;
using Kooboo.CMS.Sites.Services;
namespace Kooboo.CMS.Sites.Globalization
{
public static class SiteLabel
{
#region Cache
static string cacheKey = "SiteLabelRepository";
[Obsolete]
public static IElementRepository GetElementRepository(Site site)
{
var repository = site.ObjectCache().Get(cacheKey);
if (repository == null)
{
repository = new Kooboo.Globalization.Repository.CacheElementRepository(() => Kooboo.CMS.Common.Runtime.EngineContext.Current.Resolve<IElementRepositoryFactory>().CreateRepository(site));
site.ObjectCache().Add(cacheKey, repository, new System.Runtime.Caching.CacheItemPolicy()
{
SlidingExpiration = TimeSpan.Parse("00:30:00")
});
}
return (IElementRepository)repository;
}
[Obsolete]
public static void ClearCache(Site site)
{
site.ObjectCache().Remove(cacheKey);
}
#endregion
#region Label with inline-editing.
/// <summary>
/// Label with inline-editing.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static IHtmlString Label(this string defaultValue)
{
return Label(defaultValue, defaultValue);
}
/// <summary>
/// Label with inline-editing.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <param name="key">The key.</param>
/// <param name="category">The category.</param>
/// <returns></returns>
public static IHtmlString Label(this string defaultValue, string key, string category = "")
{
//var pageViewContext = Page_Context.Current;
//pageViewContext.CheckContext();
return Label(defaultValue, key, category, Site.Current);
}
/// <summary>
/// Label with inline-editing.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <param name="key">The key.</param>
/// <param name="category">The category.</param>
/// <param name="site">The site.</param>
/// <returns></returns>
public static IHtmlString Label(this string defaultValue, string key, string category, Site site)
{
string value = LabelValue(defaultValue, key, category, site);
if (Kooboo.Settings.IsWebApplication && Page_Context.Current.Initialized && Page_Context.Current.EnabledInlineEditing(EditingType.Label))
{
value = string.Format("<var start=\"true\" editType=\"label\" dataType=\"{0}\" key=\"{1}\" category=\"{2}\" style=\"display:none;\"></var>{3}<var end=\"true\" style=\"display:none;\"></var>"
, Kooboo.CMS.Sites.View.FieldDataType.Text.ToString()
, HttpUtility.HtmlEncode(key)
, HttpUtility.HtmlEncode(category)
, value);
}
return new HtmlString(value);
}
#endregion
#region RawLabel Label without inline editing.
/// <summary>
/// Raws the label. Label without inline editing.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <returns></returns>
public static IHtmlString RawLabel(this string defaultValue)
{
return RawLabel(defaultValue, defaultValue);
}
/// <summary>
/// Raws the label. Label without inline editing.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <param name="key">The key.</param>
/// <param name="category">The category.</param>
/// <returns></returns>
public static IHtmlString RawLabel(this string defaultValue, string key, string category = "")
{
return RawLabel(defaultValue, key, category, Site.Current);
}
/// <summary>
/// Raws the label. Label without inline editing.
/// </summary>
/// <param name="defaultValue">The default value.</param>
/// <param name="key">The key.</param>
/// <param name="category">The category.</param>
/// <param name="site">The site.</param>
/// <returns></returns>
public static IHtmlString RawLabel(this string defaultValue, string key, string category, Site site)
{
return new HtmlString(LabelValue(defaultValue, key, category, site));
}
#endregion
private static string LabelValue(string defaultValue, string key, string category, Site site)
{
if (string.IsNullOrEmpty(key) && string.IsNullOrEmpty(category))
{
return defaultValue;
}
string editor = null;
if (HttpContext.Current != null)
{
editor = HttpContext.Current.User.Identity.Name;
}
var labelManager = ServiceFactory.LabelManager;
var label = labelManager.Get(site, category, key);
string value = defaultValue;
if (label == null)
{
label = new Label(site, category, key, defaultValue) { UtcCreationDate = DateTime.UtcNow, LastestEditor = editor };
labelManager.Add(site, label);
}
else
{
value = label.Value;
}
return value;
}
}
}
| 36.791411 | 206 | 0.575121 | [
"BSD-3-Clause"
] | Bringsy/Kooboo.CMS | Kooboo.CMS/Kooboo.CMS.Sites/Globalization/SiteLabel.cs | 5,999 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Linq;
namespace Geb.Image.Formats.MetaData.Profiles.Icc
{
/// <summary>
/// This type represents an array of unsigned 64bit integers.
/// </summary>
internal sealed class IccUInt64ArrayTagDataEntry : IccTagDataEntry, IEquatable<IccUInt64ArrayTagDataEntry>
{
/// <summary>
/// Initializes a new instance of the <see cref="IccUInt64ArrayTagDataEntry"/> class.
/// </summary>
/// <param name="data">The array data</param>
public IccUInt64ArrayTagDataEntry(ulong[] data)
: this(data, IccProfileTag.Unknown)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="IccUInt64ArrayTagDataEntry"/> class.
/// </summary>
/// <param name="data">The array data</param>
/// <param name="tagSignature">Tag Signature</param>
public IccUInt64ArrayTagDataEntry(ulong[] data, IccProfileTag tagSignature)
: base(IccTypeSignature.UInt64Array, tagSignature)
{
Guard.NotNull(data, nameof(data));
this.Data = data;
}
/// <summary>
/// Gets the array data
/// </summary>
public ulong[] Data { get; }
/// <inheritdoc/>
public override bool Equals(IccTagDataEntry other)
{
return other is IccUInt64ArrayTagDataEntry entry && this.Equals(entry);
}
/// <inheritdoc/>
public bool Equals(IccUInt64ArrayTagDataEntry other)
{
if (other == null)
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return base.Equals(other) && this.Data.SequenceEqual(other.Data);
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
return obj is IccUInt64ArrayTagDataEntry && this.Equals((IccUInt64ArrayTagDataEntry)obj);
}
/// <inheritdoc/>
public override int GetHashCode()
{
unchecked
{
return (base.GetHashCode() * 397) ^ (this.Data?.GetHashCode() ?? 0);
}
}
}
} | 29.011494 | 110 | 0.540412 | [
"MIT"
] | xiaotie/GebImage | src/Geb.Image/Formats/MetaData/Profiles/ICC/TagDataEntries/IccUInt64ArrayTagDataEntry.cs | 2,526 | C# |
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
namespace Dangl.WebDocumentation.Models
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<Guid>, Guid>
{
public ApplicationDbContext(DbContextOptions options) : base(options) { }
public DbSet<DocumentationProject> DocumentationProjects { get; set; }
public DbSet<DocumentationProjectVersion> DocumentationProjectVersions { get; set; }
public DbSet<ProjectVersionAssetFile> ProjectVersionAssetFiles { get; set; }
public DbSet<UserProjectAccess> UserProjects { get; set; }
public DbSet<UserProjectNotification> UserProjectNotifications { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
DocumentationProjectVersion.OnModelCreating(builder);
ProjectVersionAssetFile.OnModelCreating(builder);
// Make the ApiKey unique so it can be used as a single identifier for a project
builder.Entity<DocumentationProject>()
.HasIndex(entity => entity.ApiKey)
.IsUnique();
// Composite key for UserProjectAccess
builder.Entity<UserProjectAccess>()
.HasKey(entity => new { entity.ProjectId, entity.UserId });
// Composite key for UserProjectNotification
builder.Entity<UserProjectNotification>()
.HasKey(entity => new { entity.ProjectId, entity.UserId });
builder.Entity<UserProjectAccess>()
.HasOne(entity => entity.Project)
.WithMany(project => project.UserAccess)
.OnDelete(DeleteBehavior.Cascade);
builder.Entity<ApplicationUser>()
.HasMany(user => user.Roles)
.WithOne()
.HasForeignKey(r => r.UserId);
}
}
}
| 40.42 | 100 | 0.656111 | [
"MIT"
] | GeorgDangl/WebDocu | src/Dangl.WebDocumentation/Models/ApplicationDbContext.cs | 2,023 | C# |
using CCXT.NET.Shared.Coin;
using CCXT.NET.Shared.Coin.Private;
using CCXT.NET.Shared.Coin.Types;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CCXT.NET.Bitflyer.Private
{
/// <summary>
///
/// </summary>
public class PrivateApi : CCXT.NET.Shared.Coin.Private.PrivateApi, IPrivateApi
{
private readonly string __connect_key;
private readonly string __secret_key;
/// <summary>
///
/// </summary>
public PrivateApi(string connect_key, string secret_key)
{
__connect_key = connect_key;
__secret_key = secret_key;
}
/// <summary>
///
/// </summary>
public override XApiClient privateClient
{
get
{
if (base.privateClient == null)
base.privateClient = new BitflyerClient("private", __connect_key, __secret_key);
return base.privateClient;
}
}
/// <summary>
///
/// </summary>
public override CCXT.NET.Shared.Coin.Public.PublicApi publicApi
{
get
{
if (base.publicApi == null)
base.publicApi = new CCXT.NET.Bitflyer.Public.PublicApi();
return base.publicApi;
}
}
/// <summary>
/// Get Bitcoin/Ethereum Deposit Addresses
/// </summary>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public override async ValueTask<Addresses> FetchAddressesAsync(Dictionary<string, object> args = null)
{
var _result = new Addresses();
var _markets = await publicApi.LoadMarketsAsync();
if (_markets.success == true)
{
privateClient.ExchangeInfo.ApiCallWait(TradeType.Private);
var _params = privateClient.MergeParamsAndArgs(args);
var _json_value = await privateClient.CallApiGet1Async("/v1/me/getaddresses", _params);
#if DEBUG
_result.rawJson = _json_value.Content;
#endif
var _json_result = privateClient.GetResponseMessage(_json_value.Response);
if (_json_result.success == true)
{
var _addresses = privateClient.DeserializeObject<List<BAddressItem>>(_json_value.Content);
{
foreach (var _address in _addresses)
{
var _market = _markets.GetMarketByBaseId(_address.currency);
if (_market != null)
{
_address.currency = _market.baseName;
_result.result.Add(_address);
}
}
}
}
_result.SetResult(_json_result);
}
else
{
_result.SetResult(_markets);
}
return _result;
}
/// <summary>
/// Get Bitcoin/Ether Deposit History
/// Get Bitcoin/Ether Transaction History
/// </summary>
/// <param name="timeframe">time frame interval (optional): default "1d"</param>
/// <param name="since">return committed data since given time (milli-seconds) (optional): default 0</param>
/// <param name="limits">You can set the maximum number of transactions you want to get with this parameter</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public override async ValueTask<Transfers> FetchAllTransfersAsync(string timeframe = "1d", long since = 0, int limits = 20, Dictionary<string, object> args = null)
{
var _result = new Transfers();
var _markets = await publicApi.LoadMarketsAsync();
if (_markets.success == true)
{
var _timestamp = privateClient.ExchangeInfo.GetTimestamp(timeframe);
var _timeframe = privateClient.ExchangeInfo.GetTimeframe(timeframe);
var _params = new Dictionary<string, object>();
{
//var _till_time = CUnixTime.NowMilli;
//var _from_time = (since > 0) ? since : _till_time - _timestamp * 1000 * limits; // 가져올 갯수 만큼 timeframe * limits 간격으로 데이터 양 계산
// bitflyer의 before, after는 id
//_params.Add("after", _from_time);
//_params.Add("before", _till_time);
_params.Add("count", limits);
privateClient.MergeParamsAndArgs(_params, args);
}
// TransactionType.Deposit
{
privateClient.ExchangeInfo.ApiCallWait(TradeType.Private);
var _json_value = await privateClient.CallApiGet1Async("/v1/me/getcoinins", _params);
#if DEBUG
_result.rawJson += _json_value.Content;
#endif
var _json_result = privateClient.GetResponseMessage(_json_value.Response);
if (_json_result.success == true)
{
var _json_data = privateClient.DeserializeObject<List<BDepositItem>>(_json_value.Content);
{
var _deposits = _json_data
.Where(t => t.timestamp >= since)
.OrderByDescending(t => t.timestamp)
.Take(limits);
foreach (var _d in _deposits)
{
_result.result.Add(_d);
}
}
}
_result.SetResult(_json_result);
}
// TransactionType.Withdrawal
if (_result.success == true)
{
privateClient.ExchangeInfo.ApiCallWait(TradeType.Private);
var _json_value = await privateClient.CallApiGet1Async("/v1/me/getcoinouts", _params);
#if DEBUG
_result.rawJson += _json_value.Content;
#endif
var _json_result = privateClient.GetResponseMessage(_json_value.Response);
if (_json_result.success == true)
{
var _json_data = privateClient.DeserializeObject<List<BWithdrawItem>>(_json_value.Content);
{
var _withdraws = _json_data
.Where(t => t.timestamp >= since)
.OrderByDescending(t => t.timestamp)
.Take(limits);
foreach (var _w in _withdraws)
{
_result.result.Add(_w);
}
}
}
_result.SetResult(_json_result);
}
}
else
{
_result.SetResult(_markets);
}
return _result;
}
/// <summary>
/// Get Account Asset Balance
/// </summary>
/// <param name="base_name">The type of trading base-currency of which information you want to query for.</param>
/// <param name="quote_name">The type of trading quote-currency of which information you want to query for.</param>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public override async ValueTask<Balance> FetchBalanceAsync(string base_name, string quote_name, Dictionary<string, object> args = null)
{
var _result = new Balance();
var _currency_id = await publicApi.LoadCurrencyIdAsync(base_name);
if (_currency_id.success == true)
{
privateClient.ExchangeInfo.ApiCallWait(TradeType.Private);
var _params = privateClient.MergeParamsAndArgs(args);
var _json_value = await privateClient.CallApiGet1Async("/v1/me/getbalance", _params);
#if DEBUG
_result.rawJson = _json_value.Content;
#endif
var _json_result = privateClient.GetResponseMessage(_json_value.Response);
if (_json_result.success == true)
{
var _balances = privateClient.DeserializeObject<List<BBalanceItem>>(_json_value.Content);
{
foreach (var _balance in _balances)
{
if (_balance.currency.ToLower() != _currency_id.result.ToLower())
continue;
_balance.currency = base_name;
_balance.used = _balance.total - _balance.free;
_result.result = _balance;
break;
}
}
}
_result.SetResult(_json_result);
}
else
{
_result.SetResult(_currency_id);
}
return _result;
}
/// <summary>
/// Get Account Asset Balance
/// </summary>
/// <param name="args">Add additional attributes for each exchange</param>
/// <returns></returns>
public override async ValueTask<Balances> FetchBalancesAsync(Dictionary<string, object> args = null)
{
var _result = new Balances();
var _markets = await publicApi.LoadMarketsAsync();
if (_markets.success == true)
{
privateClient.ExchangeInfo.ApiCallWait(TradeType.Private);
var _params = privateClient.MergeParamsAndArgs(args);
var _json_value = await privateClient.CallApiGet1Async("/v1/me/getbalance", _params);
#if DEBUG
_result.rawJson = _json_value.Content;
#endif
var _json_result = privateClient.GetResponseMessage(_json_value.Response);
if (_json_result.success == true)
{
var _json_data = privateClient.DeserializeObject<List<BBalanceItem>>(_json_value.Content);
{
foreach (var _currency_id in _markets.CurrencyNames)
{
var _balances = _json_data.Where(b => b.currency == _currency_id.Key);
foreach (var _balance in _balances)
{
_balance.currency = _currency_id.Value;
_balance.used = _balance.total - _balance.free;
_result.result.Add(_balance);
}
}
}
}
_result.SetResult(_json_result);
}
else
{
_result.SetResult(_markets);
}
return _result;
}
}
} | 38.658863 | 171 | 0.498573 | [
"MIT"
] | ccxt-net/ccxt.net | src/exchanges/jpn/bitflyer/private/privateApi.cs | 11,599 | C# |
namespace Encapsulation
{
internal class LastChange
{
public LastChange(int value, Point valueLocation, Point zeroLocation)
{
Value = value;
NewValueLocation = valueLocation;
NewZeroLocation = zeroLocation;
}
public int Value { get; }
public Point NewValueLocation { get; }
public Point NewZeroLocation { get; }
}
} | 26.75 | 78 | 0.574766 | [
"MIT"
] | EvgeniyGor/UlearnHomeworks | src/Challenges/Encapsulation/LastChange.cs | 430 | C# |
using PasswordQueryTool.Backend.Services.Parsing.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace PasswordQueryTool.Backend.Services.Parsing.Services.Interfaces
{
public interface IFileService
{
public Task<bool> FileExists(string filename);
public Task<IEnumerable<FileModel>> GetAllFiles();
public Task GetFileStream(string filename, Func<Stream, Task> executor);
public Task GetFileStream(string filename, long offset, long length, Func<Stream, Task> executor);
}
} | 30.578947 | 106 | 0.753873 | [
"MIT"
] | Konstantin-tr/PassSearch | PasswordQueryTool/PasswordQueryTool.Backend.Services.Parsing/Services/Interfaces/IFileService.cs | 583 | C# |
using System;
using DryIoc.Microsoft.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Prism.DryIoc;
using Prism.Ioc;
using Shiny;
using Shiny.Notifications;
using Shiny.Testing;
using Samples.Infrastructure;
using Samples.Jobs;
using Samples.HttpTransfers;
using Samples.Beacons;
using Samples.BluetoothLE;
using Samples.Geofences;
using Samples.Gps;
using Samples.Push;
using Samples.Notifications;
using Samples.Stores;
[assembly: GenerateStaticClasses("Samples")]
namespace Samples
{
public class SampleStartup : ShinyStartup
{
public override void ConfigureLogging(ILoggingBuilder builder, IPlatform platform)
{
builder.AddSqliteLogging(LogLevel.Warning);
//builder.AddFirebase(LogLevel.Warning);
//builder.AddAppCenter(Secrets.Values.AppCenterKey, LogLevel.Warning);
}
public override void ConfigureServices(IServiceCollection services, IPlatform platform)
{
services.UseSqliteStore();
//services.UseSqliteStorage();
services.AddSingleton<AppNotifications>();
services.AddSingleton<IDialogs, Dialogs>();
// your infrastructure
services.AddSingleton<SampleSqliteConnection>();
services.AddSingleton<CoreDelegateServices>();
services.AddSingleton<IAppSettings, AppSettings>();
// startup tasks
services.AddSingleton<GlobalExceptionHandler>();
services.AddSingleton<JobLoggerTask>();
// register all of the shiny stuff you want to use
//services.UseJobForegroundService(TimeSpan.FromSeconds(30));
services.UseHttpTransfers<HttpTransferDelegate>();
services.UseBeaconRanging();
services.UseBeaconMonitoring<BeaconDelegate>(new Shiny.Beacons.BeaconMonitorConfig().UseEstimote());
services.UseBleClient<BleClientDelegate>();
services.UseBleHosting();
services.UseSpeechRecognition();
services.UseAllSensors();
services.UseNfc();
services.UseTestMotionActivity();
//services.UseMotionActivity();
services.RegisterJob(typeof(SampleJob), runInForeground: true);
services.UseGeofencing<GeofenceDelegate>();
//services.UseGpsDirectGeofencing<LocationDelegates>();
services.UseGps<GpsDelegate>();
services.UseNotifications<NotificationDelegate>(null, new[] {
Channel.Create(
"Test",
ChannelAction.Create("Reply", ChannelActionType.TextReply),
ChannelAction.Create("Yes"),
ChannelAction.Create("No", ChannelActionType.Destructive)
),
Channel.Create(
"ChatName",
ChannelAction.Create("Answer", ChannelActionType.TextReply)
),
Channel.Create(
"ChatAnswer",
ChannelAction.Create("Yes"),
ChannelAction.Create("No", ChannelActionType.Destructive)
)
});
//services.UsePush<PushDelegate>();
#if ONESIGNAL
services.UseOneSignalPush<PushDelegate>(Secrets.Values.OneSignalAppId);
#elif FIREBASE
services.UseFirebaseMessaging<PushDelegate>();
#else
services.UsePushAzureNotificationHubs<PushDelegate>(
Secrets.Values.AzureNotificationHubListenerConnectionString,
Secrets.Values.AzureNotificationHubName
);
#endif
}
public override IServiceProvider CreateServiceProvider(IServiceCollection services)
{
// This registers and initializes the Container with Prism ensuring
// that both Shiny & Prism use the same container
ContainerLocator.SetContainerExtension(() => new DryIocContainerExtension());
var container = ContainerLocator.Container.GetContainer();
DryIocAdapter.Populate(container, services);
return container.GetServiceProvider();
}
}
}
| 36.634783 | 112 | 0.644909 | [
"MIT"
] | dave-sekula/shiny | samples/Samples/SampleStartup.cs | 4,215 | C# |
namespace Rosalia.TestingSupport.Helpers
{
using System;
using System.IO;
using Moq;
using NUnit.Framework;
using NUnit.Framework.Internal;
using Rosalia.Core;
using Rosalia.Core.Api;
using Rosalia.Core.Engine.Execution;
using Rosalia.Core.Environment;
using Rosalia.Core.Interception;
using Rosalia.Core.Logging;
using Rosalia.Core.Tasks;
using Rosalia.Core.Tasks.Results;
using Rosalia.FileSystem;
using Rosalia.TaskLib.Standard;
using Rosalia.TaskLib.Standard.Tasks;
using Rosalia.TestingSupport.FileSystem;
public static class TaskExtensions
{
public static ResultWrapper<Nothing> Execute(this IWorkflow workflow, IDirectory workDirectory = null, params Identity[] tasks)
{
return new SubflowTask<Nothing>(workflow, new Identities(tasks)).Execute();
}
public static ResultWrapper<T> Execute<T>(this ITask<T> task, IDirectory workDirectory = null) where T : class
{
var spyLogRenderer = new SpyLogRenderer();
var logRenderer = new CompositeLogRenderer(
new SimpleLogRenderer(),
spyLogRenderer);
ITaskResult<T> result = task.Execute(CreateContext(workDirectory, logRenderer).CreateFor(new Identity("TestTask")));
return new ResultWrapper<T>(
result,
spyLogRenderer);
}
public static TaskContext CreateContext(
IDirectory workDirectory = null,
ILogRenderer logRenderer = null,
IEnvironment environment = null,
ITaskInterceptor interceptor = null)
{
return new TaskContext(
new SequenceExecutionStrategy(),
logRenderer ?? new SimpleLogRenderer(),
workDirectory ?? new DirectoryStub(Directory.GetCurrentDirectory()),
environment ?? new DefaultEnvironment(),
interceptor ?? new LoggingInterceptor());
}
public static void AssertCommand<TResult>(this ExternalToolTask<TResult> task, Action<string, string> assertAction) where TResult : class
{
AssertCommand<TResult>(task, null, assertAction);
}
public static void AssertCommand<TResult>(this ExternalToolTask<TResult> task, IDirectory workDirectoryStub, Action<string, string> assertAction) where TResult : class
{
task.UnswallowedExceptionTypes = new[]
{
typeof (NUnitException),
typeof (ResultStateException)
};
var processStarter = new Mock<IProcessStarter>();
processStarter
.Setup(x => x.StartProcess(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<Action<string>>(),
It.IsAny<Action<string>>()))
.Callback((string path, string arguments, string workDirectory, Action<string> onInfo, Action<string> onError) =>
{
assertAction(path, arguments);
});
task.ProcessStarter = processStarter.Object;
//task.Execute(workDirectoryStub).AssertSuccess();
}
public static void AssertProcessOutputParsing<TResult>(
this ExternalToolTask<TResult> task,
string processOutput,
Action<ResultWrapper<TResult>> assertResultAction) where TResult : class
{
var processStarter = new Mock<IProcessStarter>();
processStarter
.Setup(x => x.StartProcess(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<Action<string>>(),
It.IsAny<Action<string>>()))
.Callback((string path, string arguments, string workDirectory, Action<string> onInfo, Action<string> onError) =>
{
if (!string.IsNullOrEmpty(processOutput))
{
foreach (var line in processOutput.Split(new[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
onInfo(line);
}
}
});
if (task.ToolPath == null)
{
task.ToolPath = "fakeToolPath"; // tool path is required for most of external tasks
}
task.ProcessStarter = processStarter.Object;
var taskResult = Execute(task);
assertResultAction(taskResult);
}
}
} | 38.471545 | 175 | 0.575655 | [
"MIT"
] | guryanovev/Rosalia | Src/Rosalia.TestingSupport/Helpers/TaskExtensions.cs | 4,734 | C# |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace PlaywrightSharp.Transport.Channels
{
internal class DialogChannel : Channel<Dialog>
{
public DialogChannel(string guid, Connection connection, Dialog owner) : base(guid, connection, owner)
{
}
internal Task AcceptAsync(string promptText)
=> Connection.SendMessageToServer<PageChannel>(
Guid,
"accept",
new Dictionary<string, object>
{
["promptText"] = promptText,
});
internal Task DismissAsync() => Connection.SendMessageToServer<PageChannel>(Guid, "dismiss", null);
}
}
| 29.08 | 110 | 0.606602 | [
"MIT"
] | Meir017/playwright-sharp | src/PlaywrightSharp/Transport/Channels/DialogChannel.cs | 727 | C# |
using System.Collections.Generic;
using System.Security.Claims;
using ToDoListApi.Entities;
namespace ToDoListApi.Repositories
{
public interface ITokenRepository
{
void SaveRefreshToken(RefreshToken refreshToken);
void RemoveRefreshToken(string token);
bool CanRefresh(string token);
void RevokeRefreshToken(string token);
string UpdateRefreshToken(string token, string updateToken);
ICollection<Claim> GetUserClaims(string token);
}
} | 32 | 69 | 0.71875 | [
"MIT"
] | szymenn/ToDoDo-backend | src/ToDoListApi/Repositories/ITokenRepository.cs | 512 | C# |
namespace Foodies
{
partial class DailySales
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend();
System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DailySales));
this.label1 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Arial", 20F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(536, 50);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(512, 32);
this.label1.TabIndex = 1;
this.label1.Text = "DAILY SALES DATA REPRESENTATION";
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.RoyalBlue;
this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBox1.Location = new System.Drawing.Point(346, 730);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(60, 60);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.BackColor = System.Drawing.Color.Goldenrod;
this.pictureBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pictureBox2.Location = new System.Drawing.Point(693, 730);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(60, 60);
this.pictureBox2.TabIndex = 3;
this.pictureBox2.TabStop = false;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(412, 750);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(218, 16);
this.label2.TabIndex = 4;
this.label2.Text = "TOTAL QUANTITY PER INVOICE";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Arial", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(759, 750);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(208, 16);
this.label3.TabIndex = 5;
this.label3.Text = "TOTAL AMOUNT PER INVOICE";
//
// chart1
//
this.chart1.BorderlineColor = System.Drawing.Color.Black;
this.chart1.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
chartArea1.Name = "ChartArea1";
this.chart1.ChartAreas.Add(chartArea1);
legend1.Name = "Legend1";
this.chart1.Legends.Add(legend1);
this.chart1.Location = new System.Drawing.Point(111, 112);
this.chart1.Name = "chart1";
series1.ChartArea = "ChartArea1";
series1.Legend = "Legend1";
series1.LegendText = "TOTAL QUANTITY PER INVOICE";
series1.Name = "TotalQty";
series2.ChartArea = "ChartArea1";
series2.Legend = "Legend1";
series2.LegendText = "TOTAL AMOUNT PER INVOICE";
series2.Name = "TotalAmount";
this.chart1.Series.Add(series1);
this.chart1.Series.Add(series2);
this.chart1.Size = new System.Drawing.Size(1375, 580);
this.chart1.TabIndex = 0;
this.chart1.Text = "chart1";
//
// DailySales
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(1600, 837);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.label1);
this.Controls.Add(this.chart1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "DailySales";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "DAILY SALES";
this.Load += new System.EventHandler(this.SalesDemo_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.DataVisualization.Charting.Chart chart1;
}
} | 50.038462 | 151 | 0.611453 | [
"MIT"
] | ashirafzal/Foodies | Foodies/DailySales.Designer.cs | 7,808 | C# |
namespace TIKSN.Shell
{
public interface IShellCommandContext
{
bool ShouldContinue(string query, string caption);
bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll);
bool ShouldProcess(string target, string action);
bool ShouldProcess(string target);
bool ShouldProcess(string verboseDescription, string verboseWarning, string caption);
}
}
| 27.125 | 95 | 0.71659 | [
"MIT"
] | tiksn/TIKSN-Framework | TIKSN.Core/Shell/IShellCommandContext.cs | 434 | C# |
using CafeLib.Core.IoC;
using CafeLib.Mobile.Extensions;
using CafeLib.Mobile.ViewModels;
using Xamarin.Forms;
// ReSharper disable UnusedMember.Global
namespace CafeLib.Mobile.Views
{
public abstract class CafeFlyoutPage : FlyoutPage, IPageBase, ISoftNavigationPage
{
/// <summary>
/// The viewmodel bound to the page.
/// </summary>
protected IServiceResolver Resolver => Application.Current.Resolve<IServiceResolver>();
/// <summary>
/// Get the view model bound to the page.
/// </summary>
/// <typeparam name="TViewModel">view model type</typeparam>
public TViewModel GetViewModel<TViewModel>() where TViewModel : BaseViewModel
{
return (TViewModel)(BindingContext as BaseViewModel);
}
/// <summary>
/// Set the binding context to the view model
/// </summary>
/// <typeparam name="TViewModel">view model type</typeparam>
/// <param name="viewModel">viewmodel instance</param>
public void SetViewModel<TViewModel>(TViewModel viewModel) where TViewModel : BaseViewModel
{
BindingContext = viewModel;
}
/// <summary>
/// Process OnAppearing lifecycle event.
/// </summary>
protected override async void OnAppearing()
{
base.OnAppearing();
if (GetMasterDetailViewModel()?.AppearingCommand == null) return;
await GetMasterDetailViewModel().AppearingCommand.ExecuteAsync();
}
/// <summary>
/// Process OnDisappearing lifecycle event.
/// </summary>
protected override void OnDisappearing()
{
base.OnDisappearing();
if (GetMasterDetailViewModel()?.DisappearingCommand == null) return;
GetMasterDetailViewModel()?.DisappearingCommand.ExecuteAsync();
}
/// <summary>
/// Process OnLoad lifecycle event.
/// </summary>
protected virtual void OnLoad()
{
GetMasterDetailViewModel()?.LoadCommand.Execute(null);
}
/// <summary>
/// Process OnUnload lifecycle event.
/// </summary>
protected virtual void OnUnload()
{
GetMasterDetailViewModel()?.UnloadCommand.Execute(null);
}
/// <summary>
/// Process hardware back button press event.
/// </summary>s
/// <returns>true: ignore behavior; false: default behavior</returns>
protected override bool OnBackButtonPressed()
{
return GetMasterDetailViewModel()?.BackButtonPressed.Execute(NavigationSource.Hardware) ?? false;
}
/// <summary>
/// Process software back button press event.
/// </summary>
/// <returns>true: ignore behavior; false: default behavior</returns>
public bool OnSoftBackButtonPressed()
{
return GetMasterDetailViewModel()?.BackButtonPressed.Execute(NavigationSource.Software) ?? false;
}
/// <summary>
/// Return the proper view model from master-detail context.
/// </summary>
/// <returns></returns>
private BaseViewModel GetMasterDetailViewModel()
{
switch (Detail)
{
case NavigationPage navPage:
return navPage.CurrentPage.GetViewModel<BaseViewModel>();
case null:
return GetViewModel<BaseViewModel>();
case not null:
return Detail.GetViewModel<BaseViewModel>();
}
}
}
} | 33.972222 | 109 | 0.587899 | [
"MIT"
] | chrissolutions/CafeLib | Mobile/CafeLib.Mobile/Views/CafeFlyoutPage.cs | 3,671 | C# |
using System;
namespace GenieLamp.Genies.DbSchemaImport
{
public class MetaInfoColumnsMatch
{
public MetaInfoColumnsMatch()
{
}
public MetaInfoColumn Child { get; set; }
public MetaInfoColumn Parent { get; set; }
}
}
| 15.5 | 45 | 0.681452 | [
"MIT"
] | arbinada-com/genie-lamp | Sources/GenieLamp.Genies/GenieLamp.Genies.DbSchemaImport/MetaInfo/MetaInfoColumnsMatch.cs | 248 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Internal;
using Newtonsoft.Json;
namespace Microsoft.AspNetCore.Http.Connections
{
public static class NegotiateProtocol
{
private const string ConnectionIdPropertyName = "connectionId";
private const string UrlPropertyName = "url";
private const string AccessTokenPropertyName = "accessToken";
private const string AvailableTransportsPropertyName = "availableTransports";
private const string TransportPropertyName = "transport";
private const string TransferFormatsPropertyName = "transferFormats";
private const string ErrorPropertyName = "error";
// Used to detect ASP.NET SignalR Server connection attempt
private const string ProtocolVersionPropertyName = "ProtocolVersion";
public static void WriteResponse(NegotiationResponse response, IBufferWriter<byte> output)
{
var textWriter = Utf8BufferTextWriter.Get(output);
try
{
using (var jsonWriter = JsonUtils.CreateJsonTextWriter(textWriter))
{
jsonWriter.WriteStartObject();
if (!string.IsNullOrEmpty(response.Url))
{
jsonWriter.WritePropertyName(UrlPropertyName);
jsonWriter.WriteValue(response.Url);
}
if (!string.IsNullOrEmpty(response.AccessToken))
{
jsonWriter.WritePropertyName(AccessTokenPropertyName);
jsonWriter.WriteValue(response.AccessToken);
}
if (!string.IsNullOrEmpty(response.ConnectionId))
{
jsonWriter.WritePropertyName(ConnectionIdPropertyName);
jsonWriter.WriteValue(response.ConnectionId);
}
jsonWriter.WritePropertyName(AvailableTransportsPropertyName);
jsonWriter.WriteStartArray();
if (response.AvailableTransports != null)
{
foreach (var availableTransport in response.AvailableTransports)
{
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName(TransportPropertyName);
jsonWriter.WriteValue(availableTransport.Transport);
jsonWriter.WritePropertyName(TransferFormatsPropertyName);
jsonWriter.WriteStartArray();
if (availableTransport.TransferFormats != null)
{
foreach (var transferFormat in availableTransport.TransferFormats)
{
jsonWriter.WriteValue(transferFormat);
}
}
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
}
}
jsonWriter.WriteEndArray();
jsonWriter.WriteEndObject();
jsonWriter.Flush();
}
}
finally
{
Utf8BufferTextWriter.Return(textWriter);
}
}
public static NegotiationResponse ParseResponse(Stream content)
{
try
{
using (var reader = JsonUtils.CreateJsonTextReader(new StreamReader(content)))
{
JsonUtils.CheckRead(reader);
JsonUtils.EnsureObjectStart(reader);
string connectionId = null;
string url = null;
string accessToken = null;
List<AvailableTransport> availableTransports = null;
string error = null;
var completed = false;
while (!completed && JsonUtils.CheckRead(reader))
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
var memberName = reader.Value.ToString();
switch (memberName)
{
case UrlPropertyName:
url = JsonUtils.ReadAsString(reader, UrlPropertyName);
break;
case AccessTokenPropertyName:
accessToken = JsonUtils.ReadAsString(reader, AccessTokenPropertyName);
break;
case ConnectionIdPropertyName:
connectionId = JsonUtils.ReadAsString(reader, ConnectionIdPropertyName);
break;
case AvailableTransportsPropertyName:
JsonUtils.CheckRead(reader);
JsonUtils.EnsureArrayStart(reader);
availableTransports = new List<AvailableTransport>();
while (JsonUtils.CheckRead(reader))
{
if (reader.TokenType == JsonToken.StartObject)
{
availableTransports.Add(ParseAvailableTransport(reader));
}
else if (reader.TokenType == JsonToken.EndArray)
{
break;
}
}
break;
case ErrorPropertyName:
error = JsonUtils.ReadAsString(reader, ErrorPropertyName);
break;
case ProtocolVersionPropertyName:
throw new InvalidOperationException("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");
default:
reader.Skip();
break;
}
break;
case JsonToken.EndObject:
completed = true;
break;
default:
throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading negotiation response JSON.");
}
}
if (url == null && error == null)
{
// if url isn't specified or there isn't an error, connectionId and available transports are required
if (connectionId == null)
{
throw new InvalidDataException($"Missing required property '{ConnectionIdPropertyName}'.");
}
if (availableTransports == null)
{
throw new InvalidDataException($"Missing required property '{AvailableTransportsPropertyName}'.");
}
}
return new NegotiationResponse
{
ConnectionId = connectionId,
Url = url,
AccessToken = accessToken,
AvailableTransports = availableTransports,
Error = error,
};
}
}
catch (Exception ex)
{
throw new InvalidDataException("Invalid negotiation response received.", ex);
}
}
private static AvailableTransport ParseAvailableTransport(JsonTextReader reader)
{
var availableTransport = new AvailableTransport();
while (JsonUtils.CheckRead(reader))
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
var memberName = reader.Value.ToString();
switch (memberName)
{
case TransportPropertyName:
availableTransport.Transport = JsonUtils.ReadAsString(reader, TransportPropertyName);
break;
case TransferFormatsPropertyName:
JsonUtils.CheckRead(reader);
JsonUtils.EnsureArrayStart(reader);
var completed = false;
availableTransport.TransferFormats = new List<string>();
while (!completed && JsonUtils.CheckRead(reader))
{
switch (reader.TokenType)
{
case JsonToken.String:
availableTransport.TransferFormats.Add(reader.Value.ToString());
break;
case JsonToken.EndArray:
completed = true;
break;
default:
throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading transfer formats JSON.");
}
}
break;
default:
reader.Skip();
break;
}
break;
case JsonToken.EndObject:
if (availableTransport.Transport == null)
{
throw new InvalidDataException($"Missing required property '{TransportPropertyName}'.");
}
if (availableTransport.TransferFormats == null)
{
throw new InvalidDataException($"Missing required property '{TransferFormatsPropertyName}'.");
}
return availableTransport;
default:
throw new InvalidDataException($"Unexpected token '{reader.TokenType}' when reading available transport JSON.");
}
}
throw new InvalidDataException("Unexpected end when reading JSON.");
}
}
}
| 46.734127 | 268 | 0.442388 | [
"Apache-2.0"
] | 0xced/AspNetCore | src/SignalR/src/Microsoft.AspNetCore.Http.Connections.Common/NegotiateProtocol.cs | 11,777 | C# |
using System;
using ClearHl7.Extensions;
using ClearHl7.Helpers;
namespace ClearHl7.V251.Types
{
/// <summary>
/// HL7 Version 2 MOP - Money Or Percentage.
/// </summary>
public class MoneyOrPercentage : IType
{
/// <inheritdoc/>
public bool IsSubcomponent { get; set; }
/// <summary>
/// MOP.1 - Money or Percentage Indicator.
/// <para>Suggested: 0148 Money Or Percentage Indicator -> ClearHl7.Codes.V251.CodeMoneyOrPercentageIndicator</para>
/// </summary>
public string MoneyOrPercentageIndicator { get; set; }
/// <summary>
/// MOP.2 - Money or Percentage Quantity.
/// </summary>
public decimal? MoneyOrPercentageQuantity { get; set; }
/// <summary>
/// MOP.3 - Monetary Denomination.
/// </summary>
public string MonetaryDenomination { get; set; }
/// <inheritdoc/>
public void FromDelimitedString(string delimitedString)
{
FromDelimitedString(delimitedString, null);
}
/// <inheritdoc/>
public void FromDelimitedString(string delimitedString, Separators separators)
{
Separators seps = separators ?? new Separators().UsingConfigurationValues();
string[] separator = IsSubcomponent ? seps.SubcomponentSeparator : seps.ComponentSeparator;
string[] segments = delimitedString == null
? Array.Empty<string>()
: delimitedString.Split(separator, StringSplitOptions.None);
MoneyOrPercentageIndicator = segments.Length > 0 && segments[0].Length > 0 ? segments[0] : null;
MoneyOrPercentageQuantity = segments.Length > 1 && segments[1].Length > 0 ? segments[1].ToNullableDecimal() : null;
MonetaryDenomination = segments.Length > 2 && segments[2].Length > 0 ? segments[2] : null;
}
/// <inheritdoc/>
public string ToDelimitedString()
{
System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
string separator = IsSubcomponent ? Configuration.SubcomponentSeparator : Configuration.ComponentSeparator;
return string.Format(
culture,
StringHelper.StringFormatSequence(0, 3, separator),
MoneyOrPercentageIndicator,
MoneyOrPercentageQuantity.HasValue ? MoneyOrPercentageQuantity.Value.ToString(Consts.NumericFormat, culture) : null,
MonetaryDenomination
).TrimEnd(separator.ToCharArray());
}
}
}
| 40.626866 | 148 | 0.601029 | [
"MIT"
] | kamlesh-microsoft/clear-hl7-net | src/ClearHl7/V251/Types/MoneyOrPercentage.cs | 2,724 | C# |
using System.Threading.Tasks;
using Abp.Application.Services;
using Roc.CMS.Authorization.Accounts.Dto;
namespace Roc.CMS.Authorization.Accounts
{
public interface IAccountAppService : IApplicationService
{
Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input);
Task<int?> ResolveTenantId(ResolveTenantIdInput input);
Task<RegisterOutput> Register(RegisterInput input);
Task SendPasswordResetCode(SendPasswordResetCodeInput input);
Task<ResetPasswordOutput> ResetPassword(ResetPasswordInput input);
Task SendEmailActivationLink(SendEmailActivationLinkInput input);
Task ActivateEmail(ActivateEmailInput input);
Task<ImpersonateOutput> Impersonate(ImpersonateInput input);
Task<ImpersonateOutput> BackToImpersonator();
Task<SwitchToLinkedAccountOutput> SwitchToLinkedAccount(SwitchToLinkedAccountInput input);
}
}
| 31.333333 | 98 | 0.773404 | [
"MIT"
] | RocChing/Roc.CMS | src/Roc.CMS.Application.Shared/Authorization/Accounts/IAccountAppService.cs | 942 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the swf-2012-01-25.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleWorkflow.Model
{
/// <summary>
/// Used to filter the closed workflow executions in visibility APIs by their close status.
/// </summary>
public partial class CloseStatusFilter
{
private CloseStatus _status;
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// <b>Required.</b> The close status that must match the close status of an execution
/// for it to meet the criteria of this filter.
/// </para>
/// </summary>
public CloseStatus Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
}
} | 29.912281 | 101 | 0.652199 | [
"Apache-2.0"
] | Bynder/aws-sdk-net | sdk/src/Services/SimpleWorkflow/Generated/Model/CloseStatusFilter.cs | 1,705 | C# |
using OcrWaterMeter.Server.Database;
var dbFolder = Environment.GetEnvironmentVariable("DATADIR");
var liteDbName = Path.Combine(string.IsNullOrEmpty(dbFolder) ? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) : dbFolder, "WaterMeter.db");
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
WebRootPath = "wwwroot",
Args = args,
});
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddLiteDb(liteDbName);
builder.WebHost.UseStaticWebAssets();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// app.UseHsts();
}
// app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.MapGet("/version", () => Environment.GetEnvironmentVariable("BUILDNUMBER") ?? "unknown version");
app.MapGet("/build", () => Environment.GetEnvironmentVariable("BUILDID") ?? "unknown buildid");
app.MapGet("/commit", () => Environment.GetEnvironmentVariable("SOURCE_COMMIT") ?? "unknown version");
app.Run();
| 27.921569 | 161 | 0.749298 | [
"Apache-2.0"
] | TheR00st3r/OcrWaterMeter | OcrWaterMeter/Server/Program.cs | 1,424 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace ODataValidator.Rule
{
#region Namespaces
using System;
using System.ComponentModel.Composition;
using Newtonsoft.Json.Linq;
using ODataValidator.RuleEngine;
using ODataValidator.RuleEngine.Common;
#endregion
/// <summary>
/// Class of extension rule for Entry.Core.4081
/// </summary>
[Export(typeof(ExtensionRule))]
public class EntryCore4081 : ExtensionRule
{
/// <summary>
/// Gets Category property
/// </summary>
public override string Category
{
get
{
return "core";
}
}
/// <summary>
/// Gets rule name
/// </summary>
public override string Name
{
get
{
return "Entry.Core.4081";
}
}
/// <summary>
/// Gets rule description
/// </summary>
public override string Description
{
get
{
return "NaN, INF and -INF values are represented as strings.";
}
}
/// <summary>
/// Gets rule specification in OData document
/// </summary>
public override string V4SpecificationSection
{
get
{
return "7.1";
}
}
/// <summary>
/// Gets the version.
/// </summary>
public override ODataVersion? Version
{
get
{
return ODataVersion.V3_V4;
}
}
/// <summary>
/// Gets location of help information of the rule
/// </summary>
public override string HelpLink
{
get
{
return null;
}
}
/// <summary>
/// Gets the error message for validation failure
/// </summary>
public override string ErrorMessage
{
get
{
return this.Description;
}
}
/// <summary>
/// Gets the requirement level.
/// </summary>
public override RequirementLevel RequirementLevel
{
get
{
return RequirementLevel.Must;
}
}
/// <summary>
/// Gets the payload type to which the rule applies.
/// </summary>
public override PayloadType? PayloadType
{
get
{
return RuleEngine.PayloadType.Entry;
}
}
/// <summary>
/// Gets the payload format to which the rule applies.
/// </summary>
public override PayloadFormat? PayloadFormat
{
get
{
return RuleEngine.PayloadFormat.JsonLight;
}
}
/// <summary>
/// Gets the RequireMetadata property to which the rule applies.
/// </summary>
public override bool? RequireMetadata
{
get
{
return null;
}
}
/// <summary>
/// Gets the flag whether this rule applies to offline context
/// </summary>
public override bool? IsOfflineContext
{
get
{
return null;
}
}
/// <summary>
/// Verifies the extension rule.
/// </summary>
/// <param name="context">The Interop service context</param>
/// <param name="info">out parameter to return violation information when rule does not pass</param>
/// <returns>true if rule passes; false otherwise</returns>
public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
bool? passed = null;
info = null;
JObject entry;
context.ResponsePayload.TryToJObject(out entry);
if (entry != null && entry.Type == JTokenType.Object)
{
var o = (JObject)entry;
// Get all the properties in current entry.
var jProps = o.Children();
foreach (JProperty jProp in jProps)
{
if ("NaN" == jProp.Value.ToString() || "INF" == jProp.Value.ToString() || "-INF" == jProp.Value.ToString())
{
if (jProp.Value.Type == JTokenType.String)
{
passed = true;
}
else
{
passed = false;
info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
break;
}
}
}
}
return passed;
}
}
}
| 27.42 | 132 | 0.443837 | [
"MIT"
] | OData/ValidationTool | src/CodeRules/Entry/EntryCore4081.cs | 5,486 | C# |
namespace BusinessConversation.CHN.Hotel
{
public class CSVQuizMCDataHolder
{
public readonly string location = ""; // 장소
public readonly string lesson = ""; // 레슨
public readonly string index = ""; // OX, 객관식
public readonly string question = ""; // 문제
public readonly string explain = ""; // 지문
public readonly string choice_01 = ""; // 답안 01
public readonly string choice_02 = ""; // 답안 02
public readonly string choice_03 = ""; // 답안 03
public readonly string choice_04 = ""; // 답안 04
public readonly string answer = ""; // 정답
public readonly string commentary = ""; // 해설
public CSVQuizMCDataHolder(string location, string lesson, string index,
string question, string explain,
string choice_01, string choice_02, string choice_03, string choice_04,
string answer, string commentary)
{
this.location = location;
this.lesson = lesson;
this.index = index;
this.question = question;
this.explain = explain;
this.choice_01 = choice_01;
this.choice_02 = choice_02;
this.choice_03 = choice_03;
this.choice_04 = choice_04;
this.answer = answer;
this.commentary = commentary;
}
public string GetChoiceStringWithIndex(int index)
{
switch (index)
{
case 0:
return choice_01;
case 1:
return choice_02;
case 2:
return choice_03;
case 3:
return choice_04;
default:
return string.Empty;
}
}
}
}
| 34.678571 | 107 | 0.493306 | [
"Apache-2.0"
] | JungukHom/BusinessConversation | Assets/Scripts/IO/CSV/Quiz/MultipleChoice/CSVQuizMCDataHolder.cs | 1,990 | C# |
using RissoleDatabaseHelper.Core.Attributes;
using RissoleDatabaseHelper.Core.Enums;
using System;
using System.Text;
namespace RissoleDatabaseHelper.Core.Models
{
internal class RissoleKey
{
public RissoleKey(PrimaryKeyAttribute keyAttribute)
{
Type = KeyType.PrimaryKey;
}
public RissoleKey(ForeignKeyAttribute keyAttribute)
{
Table = keyAttribute.Table;
Column = keyAttribute.Column;
Type = KeyType.ForeignKey;
}
public string Table { get; set; }
public string Column { get; set; }
public KeyType Type { get; set; }
}
}
| 24.407407 | 59 | 0.631259 | [
"MIT"
] | JiarongGu/RissoleDatabaseHelper | src/RissoleDatabaseHelper.Core/Models/RissoleKey.cs | 661 | C# |
namespace TrafficManager.Manager.Impl {
using ColossalFramework.Globalization;
using ColossalFramework.Math;
using ColossalFramework;
using CSUtil.Commons;
using JetBrains.Annotations;
using System;
using TrafficManager.API.Manager;
using TrafficManager.API.Traffic.Data;
using TrafficManager.API.Traffic.Enums;
using TrafficManager.Custom.AI;
using TrafficManager.Custom.PathFinding;
using TrafficManager.State.ConfigData;
using TrafficManager.State;
using TrafficManager.UI;
using TrafficManager.Util;
using UnityEngine;
public class AdvancedParkingManager
: AbstractFeatureManager,
IAdvancedParkingManager
{
private readonly Spiral _spiral;
public static readonly AdvancedParkingManager Instance
= new AdvancedParkingManager(SingletonLite<Spiral>.instance);
public AdvancedParkingManager(Spiral spiral) {
_spiral = spiral ?? throw new ArgumentNullException(nameof(spiral));
}
protected override void OnDisableFeatureInternal() {
for (var citizenInstanceId = 0;
citizenInstanceId < ExtCitizenInstanceManager.Instance.ExtInstances.Length;
++citizenInstanceId) {
ExtPathMode pathMode = ExtCitizenInstanceManager
.Instance.ExtInstances[citizenInstanceId].pathMode;
switch (pathMode) {
case ExtPathMode.RequiresWalkingPathToParkedCar:
case ExtPathMode.CalculatingWalkingPathToParkedCar:
case ExtPathMode.WalkingToParkedCar:
case ExtPathMode.ApproachingParkedCar: {
// citizen requires a path to their parked car: release instance to prevent
// it from floating
Services.CitizenService.ReleaseCitizenInstance((ushort)citizenInstanceId);
break;
}
case ExtPathMode.RequiresCarPath:
case ExtPathMode.RequiresMixedCarPathToTarget:
case ExtPathMode.CalculatingCarPathToKnownParkPos:
case ExtPathMode.CalculatingCarPathToTarget:
case ExtPathMode.DrivingToKnownParkPos:
case ExtPathMode.DrivingToTarget: {
if (Services.CitizenService.CheckCitizenInstanceFlags(
(ushort)citizenInstanceId,
CitizenInstance.Flags.Character)) {
// citizen instance requires a car but is walking: release instance to
// prevent it from floating
Services.CitizenService.ReleaseCitizenInstance(
(ushort)citizenInstanceId);
}
break;
}
}
}
ExtCitizenManager.Instance.Reset();
ExtCitizenInstanceManager.Instance.Reset();
}
protected override void OnEnableFeatureInternal() {
}
public bool EnterParkedCar(ushort instanceId,
ref CitizenInstance instanceData,
ushort parkedVehicleId,
out ushort vehicleId) {
#if DEBUG
bool citizenDebug =
(DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == instanceData.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == instanceData.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
Log._DebugIf(
logParkingAi,
() => $"CustomHumanAI.EnterParkedCar({instanceId}, ..., {parkedVehicleId}) called.");
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
VehicleManager vehManager = Singleton<VehicleManager>.instance;
NetManager netManager = Singleton<NetManager>.instance;
CitizenManager citManager = Singleton<CitizenManager>.instance;
Vector3 parkedVehPos = vehManager.m_parkedVehicles.m_buffer[parkedVehicleId].m_position;
Quaternion parkedVehRot =
vehManager.m_parkedVehicles.m_buffer[parkedVehicleId].m_rotation;
VehicleInfo vehicleInfo = vehManager.m_parkedVehicles.m_buffer[parkedVehicleId].Info;
if (!CustomPathManager._instance.m_pathUnits.m_buffer[instanceData.m_path]
.GetPosition(0, out PathUnit.Position vehLanePathPos)) {
Log._DebugIf(
logParkingAi,
() => $"CustomHumanAI.EnterParkedCar({instanceId}): Could not get first car " +
$"path position of citizen instance {instanceId}!");
vehicleId = 0;
return false;
}
uint vehLaneId = PathManager.GetLaneID(vehLanePathPos);
Log._DebugIf(
extendedLogParkingAi,
() => $"CustomHumanAI.EnterParkedCar({instanceId}): Determined vehicle " +
$"position for citizen instance {instanceId}: seg. {vehLanePathPos.m_segment}, " +
$"lane {vehLanePathPos.m_lane}, off {vehLanePathPos.m_offset} (lane id {vehLaneId})");
netManager.m_lanes.m_buffer[vehLaneId].GetClosestPosition(
parkedVehPos,
out Vector3 vehLanePos,
out float vehLaneOff);
var vehLaneOffset = (byte)Mathf.Clamp(Mathf.RoundToInt(vehLaneOff * 255f), 0, 255);
// movement vector from parked vehicle position to road position
// Vector3 forwardVector =
// parkedVehPos + Vector3.ClampMagnitude(vehLanePos - parkedVehPos, 5f);
if (vehManager.CreateVehicle(
out vehicleId,
ref Singleton<SimulationManager>.instance.m_randomizer,
vehicleInfo,
parkedVehPos,
TransferManager.TransferReason.None,
false,
false)) {
// update frame data
Vehicle.Frame frame = vehManager.m_vehicles.m_buffer[vehicleId].m_frame0;
frame.m_rotation = parkedVehRot;
vehManager.m_vehicles.m_buffer[vehicleId].m_frame0 = frame;
vehManager.m_vehicles.m_buffer[vehicleId].m_frame1 = frame;
vehManager.m_vehicles.m_buffer[vehicleId].m_frame2 = frame;
vehManager.m_vehicles.m_buffer[vehicleId].m_frame3 = frame;
vehicleInfo.m_vehicleAI.FrameDataUpdated(
vehicleId,
ref vehManager.m_vehicles.m_buffer[vehicleId],
ref frame);
// update vehicle target position
vehManager.m_vehicles.m_buffer[vehicleId].m_targetPos0 = new Vector4(
vehLanePos.x,
vehLanePos.y,
vehLanePos.z,
2f);
// update other fields
vehManager.m_vehicles.m_buffer[vehicleId].m_flags =
vehManager.m_vehicles.m_buffer[vehicleId].m_flags | Vehicle.Flags.Stopped;
vehManager.m_vehicles.m_buffer[vehicleId].m_path = instanceData.m_path;
vehManager.m_vehicles.m_buffer[vehicleId].m_pathPositionIndex = 0;
vehManager.m_vehicles.m_buffer[vehicleId].m_lastPathOffset = vehLaneOffset;
vehManager.m_vehicles.m_buffer[vehicleId].m_transferSize =
(ushort)(instanceData.m_citizen & 65535u);
if (!vehicleInfo.m_vehicleAI.TrySpawn(
vehicleId,
ref vehManager.m_vehicles.m_buffer[vehicleId])) {
Log._DebugIf(
logParkingAi,
() => $"CustomHumanAI.EnterParkedCar({instanceId}): Could not " +
$"spawn a {vehicleInfo.m_vehicleType} for citizen instance {instanceId}!");
return false;
}
// change instances
InstanceID parkedVehInstance = InstanceID.Empty;
parkedVehInstance.ParkedVehicle = parkedVehicleId;
InstanceID vehInstance = InstanceID.Empty;
vehInstance.Vehicle = vehicleId;
Singleton<InstanceManager>.instance.ChangeInstance(parkedVehInstance, vehInstance);
// set vehicle id for citizen instance
instanceData.m_path = 0u;
citManager.m_citizens.m_buffer[instanceData.m_citizen]
.SetParkedVehicle(instanceData.m_citizen, 0);
citManager.m_citizens.m_buffer[instanceData.m_citizen]
.SetVehicle(instanceData.m_citizen, vehicleId, 0u);
// update citizen instance flags
instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath;
instanceData.m_flags &= ~CitizenInstance.Flags.EnteringVehicle;
instanceData.m_flags &= ~CitizenInstance.Flags.TryingSpawnVehicle;
instanceData.m_flags &= ~CitizenInstance.Flags.BoredOfWaiting;
instanceData.m_waitCounter = 0;
// unspawn citizen instance
instanceData.Unspawn(instanceId);
if (extendedLogParkingAi) {
Log._Debug(
$"CustomHumanAI.EnterParkedCar({instanceId}): Citizen instance " +
$"{instanceId} is now entering vehicle {vehicleId}. Set vehicle " +
$"target position to {vehLanePos} (segment={vehLanePathPos.m_segment}, " +
$"lane={vehLanePathPos.m_lane}, offset={vehLanePathPos.m_offset})");
}
return true;
}
// failed to find a road position
Log._DebugIf(
logParkingAi,
() => $"CustomHumanAI.EnterParkedCar({instanceId}): Could not " +
$"find a road position for citizen instance {instanceId} near " +
$"parked vehicle {parkedVehicleId}!");
return false;
}
public ExtSoftPathState UpdateCitizenPathState(ushort citizenInstanceId,
ref CitizenInstance citizenInstance,
ref ExtCitizenInstance extInstance,
ref ExtCitizen extCitizen,
ref Citizen citizen,
ExtPathState mainPathState) {
#if DEBUG
bool citizenDebug =
(DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == citizenInstanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == citizenInstance.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == citizenInstance.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == citizenInstance.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}) called.");
if (mainPathState == ExtPathState.Calculating) {
// main path is still calculating, do not check return path
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): still calculating main path. returning CALCULATING.");
return ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
}
IExtCitizenInstanceManager extCitInstMan = Constants.ManagerFactory.ExtCitizenInstanceManager;
// if (!Constants.ManagerFactory.ExtCitizenInstanceManager.IsValid(citizenInstanceId)) {
// // no citizen
//#if DEBUG
// if (debug)
// Log._Debug($"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., {mainPathState}): no citizen found!");
//#endif
// return ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
// }
if (mainPathState == ExtPathState.None || mainPathState == ExtPathState.Failed) {
// main path failed or non-existing
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): mainPathSate is {mainPathState}.");
if (mainPathState == ExtPathState.Failed) {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, " +
$"..., {mainPathState}): Checking if path-finding may be repeated.");
return OnCitizenPathFindFailure(
citizenInstanceId,
ref citizenInstance,
ref extInstance,
ref extCitizen);
}
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): Resetting instance and returning FAILED.");
extCitInstMan.Reset(ref extInstance);
return ExtSoftPathState.FailedHard;
}
// main path state is READY
// main path calculation succeeded: update return path state and check its state if necessary
extCitInstMan.UpdateReturnPathState(ref extInstance);
var success = true;
switch (extInstance.returnPathState) {
case ExtPathState.None:
default: {
// no return path calculated: ignore
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): return path state is None. Ignoring and " +
"returning main path state.");
break;
}
case ExtPathState.Calculating: // OK
{
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): return path state is still calculating.");
return ExtSoftPathState.Calculating;
}
case ExtPathState.Failed: // OK
{
// no walking path from parking position to target found. flag main path as 'failed'.
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): Return path FAILED.");
success = false;
break;
}
case ExtPathState.Ready: {
// handle valid return path
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCitizenPathState({citizenInstanceId}, ..., " +
$"{mainPathState}): Path is READY.");
break;
}
}
extCitInstMan.ReleaseReturnPath(ref extInstance);
return success
? OnCitizenPathFindSuccess(
citizenInstanceId,
ref citizenInstance,
ref extInstance,
ref extCitizen,
ref citizen)
: OnCitizenPathFindFailure(
citizenInstanceId,
ref citizenInstance,
ref extInstance,
ref extCitizen);
}
public ExtSoftPathState UpdateCarPathState(ushort vehicleId,
ref Vehicle vehicleData,
ref CitizenInstance driverInstance,
ref ExtCitizenInstance driverExtInstance,
ExtPathState mainPathState) {
IExtCitizenInstanceManager extCitInstMan = Constants.ManagerFactory.ExtCitizenInstanceManager;
#if DEBUG
bool citizenDebug
= (DebugSettings.VehicleId == 0
|| DebugSettings.VehicleId == vehicleId)
&& (DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == driverExtInstance.instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == driverInstance.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == driverInstance.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == driverInstance.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}) called.");
if (mainPathState == ExtPathState.Calculating) {
// main path is still calculating, do not check return path
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): still calculating main path. returning CALCULATING.");
return ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
}
// if (!driverExtInstance.IsValid()) {
// // no driver
// #if DEBUG
// if (debug)
// Log._Debug($"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., {mainPathState}): no driver found!");
// #endif
// return mainPathState;
// }
// ExtCitizenInstance driverExtInstance = ExtCitizenInstanceManager.Instance.GetExtInstance(
// CustomPassengerCarAI.GetDriverInstance(vehicleId, ref vehicleData));
if (!extCitInstMan.IsValid(driverExtInstance.instanceId)) {
// no driver
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): no driver found!");
return ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
}
if (Constants.ManagerFactory.ExtVehicleManager.ExtVehicles[vehicleId].vehicleType !=
ExtVehicleType.PassengerCar) {
// non-passenger cars are not handled
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): not a passenger car!");
extCitInstMan.Reset(ref driverExtInstance);
return ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
}
if (mainPathState == ExtPathState.None || mainPathState == ExtPathState.Failed) {
// main path failed or non-existing: reset return path
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): mainPathSate is {mainPathState}.");
if (mainPathState == ExtPathState.Failed) {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Checking if path-finding may be repeated.");
extCitInstMan.ReleaseReturnPath(ref driverExtInstance);
return OnCarPathFindFailure(vehicleId,
ref vehicleData,
ref driverInstance,
ref driverExtInstance);
}
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Resetting instance and returning FAILED.");
extCitInstMan.Reset(ref driverExtInstance);
return ExtSoftPathState.FailedHard;
}
// main path state is READY
// main path calculation succeeded: update return path state and check its state
extCitInstMan.UpdateReturnPathState(ref driverExtInstance);
switch (driverExtInstance.returnPathState) {
case ExtPathState.None:
default: {
// no return path calculated: ignore
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): return path state is None. " +
"Setting pathMode=DrivingToTarget and returning main path state.");
driverExtInstance.pathMode = ExtPathMode.DrivingToTarget;
return ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
}
case ExtPathState.Calculating: {
// return path not read yet: wait for it
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): return path state is still calculating.");
return ExtSoftPathState.Calculating;
}
case ExtPathState.Failed: {
// no walking path from parking position to target found. flag main path as 'failed'.
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Return path {driverExtInstance.returnPathId} " +
"FAILED. Forcing path-finding to fail.");
}
extCitInstMan.Reset(ref driverExtInstance);
return ExtSoftPathState.FailedHard;
}
case ExtPathState.Ready: {
// handle valid return path
extCitInstMan.ReleaseReturnPath(ref driverExtInstance);
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Path is ready for vehicle {vehicleId}, " +
$"citizen instance {driverExtInstance.instanceId}! " +
$"CurrentPathMode={driverExtInstance.pathMode}");
}
byte laneTypes = CustomPathManager
._instance.m_pathUnits.m_buffer[vehicleData.m_path]
.m_laneTypes;
bool usesPublicTransport =
(laneTypes & (byte)(NetInfo.LaneType.PublicTransport)) != 0;
if (usesPublicTransport &&
(driverExtInstance.pathMode == ExtPathMode.CalculatingCarPathToKnownParkPos
|| driverExtInstance.pathMode == ExtPathMode.CalculatingCarPathToAltParkPos))
{
driverExtInstance.pathMode = ExtPathMode.CalculatingCarPathToTarget;
driverExtInstance.parkingSpaceLocation = ExtParkingSpaceLocation.None;
driverExtInstance.parkingSpaceLocationId = 0;
}
switch (driverExtInstance.pathMode) {
case ExtPathMode.CalculatingCarPathToAltParkPos: {
driverExtInstance.pathMode = ExtPathMode.DrivingToAltParkPos;
driverExtInstance.parkingPathStartPosition = null;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Path to an alternative parking position is " +
$"READY for vehicle {vehicleId}! CurrentPathMode={driverExtInstance.pathMode}");
}
break;
}
case ExtPathMode.CalculatingCarPathToTarget: {
driverExtInstance.pathMode = ExtPathMode.DrivingToTarget;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Car path is READY for vehicle {vehicleId}! " +
$"CurrentPathMode={driverExtInstance.pathMode}");
}
break;
}
case ExtPathMode.CalculatingCarPathToKnownParkPos: {
driverExtInstance.pathMode = ExtPathMode.DrivingToKnownParkPos;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.UpdateCarPathState({vehicleId}, ..., " +
$"{mainPathState}): Car path to known parking position is READY " +
$"for vehicle {vehicleId}! CurrentPathMode={driverExtInstance.pathMode}");
}
break;
}
}
return ExtSoftPathState.Ready;
}
}
}
public ParkedCarApproachState CitizenApproachingParkedCarSimulationStep(
ushort instanceId,
ref CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
Vector3 physicsLodRefPos,
ref VehicleParked parkedCar)
{
#if DEBUG
bool citizenDebug =
(DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == instanceData.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == instanceData.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
bool logParkingAi = false;
bool extendedLogParkingAi = false;
#endif
if ((instanceData.m_flags & CitizenInstance.Flags.WaitingPath) != CitizenInstance.Flags.None) {
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.CheckCitizenReachedParkedCar({instanceId}): " +
$"citizen instance {instanceId} is waiting for path-finding to complete.");
return ParkedCarApproachState.None;
}
// ExtCitizenInstance extInstance = ExtCitizenInstanceManager.Instance.GetExtInstance(instanceId);
if (extInstance.pathMode != ExtPathMode.ApproachingParkedCar &&
extInstance.pathMode != ExtPathMode.WalkingToParkedCar) {
if (extendedLogParkingAi) {
Log._Debug(
"AdvancedParkingManager.CitizenApproachingParkedCarSimulationStep" +
$"({instanceId}): citizen instance {instanceId} is not reaching " +
$"a parked car ({extInstance.pathMode})");
}
return ParkedCarApproachState.None;
}
if ((instanceData.m_flags & CitizenInstance.Flags.Character) == CitizenInstance.Flags.None) {
return ParkedCarApproachState.None;
}
Vector3 lastFramePos = instanceData.GetLastFramePosition();
Vector3 doorPosition = parkedCar.GetClosestDoorPosition(
parkedCar.m_position,
VehicleInfo.DoorType.Enter);
if (extInstance.pathMode == ExtPathMode.WalkingToParkedCar) {
// check if path is complete
if (instanceData.m_pathPositionIndex != 255 &&
(instanceData.m_path == 0
|| !CustomPathManager._instance.m_pathUnits.m_buffer[instanceData.m_path]
.GetPosition(instanceData.m_pathPositionIndex >> 1,
out _)))
{
extInstance.pathMode = ExtPathMode.ApproachingParkedCar;
extInstance.lastDistanceToParkedCar =
(instanceData.GetLastFramePosition() - doorPosition).sqrMagnitude;
if (logParkingAi) {
Log._Debug(
"AdvancedParkingManager.CitizenApproachingParkedCarSimulationStep" +
$"({instanceId}): citizen instance {instanceId} was walking to " +
"parked car and reached final path position. " +
$"Switched PathMode to {extInstance.pathMode}.");
}
}
}
if (extInstance.pathMode != ExtPathMode.ApproachingParkedCar) {
return ParkedCarApproachState.None;
}
Vector3 doorTargetDir = doorPosition - lastFramePos;
Vector3 doorWalkVector = doorPosition;
float doorTargetDirMagnitude = doorTargetDir.magnitude;
if (doorTargetDirMagnitude > 1f) {
float speed = Mathf.Max(doorTargetDirMagnitude - 5f, doorTargetDirMagnitude * 0.5f);
doorWalkVector = lastFramePos + (doorTargetDir * (speed / doorTargetDirMagnitude));
}
instanceData.m_targetPos = new Vector4(doorWalkVector.x, doorWalkVector.y, doorWalkVector.z, 0.5f);
instanceData.m_targetDir = VectorUtils.XZ(doorTargetDir);
CitizenApproachingParkedCarSimulationStep(instanceId, ref instanceData, physicsLodRefPos);
float doorSqrDist = (instanceData.GetLastFramePosition() - doorPosition).sqrMagnitude;
if (doorSqrDist > GlobalConfig.Instance.ParkingAI.MaxParkedCarInstanceSwitchSqrDistance) {
// citizen is still too far away from the parked car
ExtPathMode oldPathMode = extInstance.pathMode;
if (doorSqrDist > extInstance.lastDistanceToParkedCar + 1024f) {
// distance has increased dramatically since the last time
if (logParkingAi) {
Log._Debug(
"AdvancedParkingManager.CitizenApproachingParkedCarSimulationStep" +
$"({instanceId}): Citizen instance {instanceId} is currently " +
"reaching their parked car but distance increased! " +
$"dist={doorSqrDist}, LastDistanceToParkedCar" +
$"={extInstance.lastDistanceToParkedCar}.");
}
#if DEBUG
if (DebugSwitch.ParkingAIDistanceIssue.Get()) {
Log._Debug(
"AdvancedParkingManager.CitizenApproachingParkedCarSimulationStep" +
$"({instanceId}): FORCED PAUSE. Distance increased! " +
$"Citizen instance {instanceId}. dist={doorSqrDist}");
Singleton<SimulationManager>.instance.SimulationPaused = true;
}
#endif
CitizenInstance.Frame frameData = instanceData.GetLastFrameData();
frameData.m_position = doorPosition;
instanceData.SetLastFrameData(frameData);
extInstance.pathMode = ExtPathMode.RequiresCarPath;
return ParkedCarApproachState.Approached;
}
if (doorSqrDist < extInstance.lastDistanceToParkedCar) {
extInstance.lastDistanceToParkedCar = doorSqrDist;
}
if (extendedLogParkingAi) {
Log._Debug(
"AdvancedParkingManager.CitizenApproachingParkedCarSimulationStep" +
$"({instanceId}): Citizen instance {instanceId} is currently " +
$"reaching their parked car (dist={doorSqrDist}, " +
$"LastDistanceToParkedCar={extInstance.lastDistanceToParkedCar}). " +
$"CurrentDepartureMode={extInstance.pathMode}");
}
return ParkedCarApproachState.Approaching;
}
extInstance.pathMode = ExtPathMode.RequiresCarPath;
if (logParkingAi) {
Log._Debug(
"AdvancedParkingManager.CitizenApproachingParkedCarSimulationStep" +
$"({instanceId}): Citizen instance {instanceId} reached parking position " +
$"(dist={doorSqrDist}). Calculating remaining path now. " +
$"CurrentDepartureMode={extInstance.pathMode}");
}
return ParkedCarApproachState.Approached;
}
protected void CitizenApproachingParkedCarSimulationStep(ushort instanceId,
ref CitizenInstance instanceData,
Vector3 physicsLodRefPos) {
if ((instanceData.m_flags & CitizenInstance.Flags.Character) == CitizenInstance.Flags.None) {
return;
}
CitizenInstance.Frame lastFrameData = instanceData.GetLastFrameData();
int oldGridX = Mathf.Clamp(
(int)((lastFrameData.m_position.x / CitizenManager.CITIZENGRID_CELL_SIZE) +
(CitizenManager.CITIZENGRID_RESOLUTION / 2f)),
0,
CitizenManager.CITIZENGRID_RESOLUTION - 1);
int oldGridY = Mathf.Clamp(
(int)((lastFrameData.m_position.z / CitizenManager.CITIZENGRID_CELL_SIZE) +
(CitizenManager.CITIZENGRID_RESOLUTION / 2f)),
0,
CitizenManager.CITIZENGRID_RESOLUTION - 1);
bool lodPhysics = Vector3.SqrMagnitude(physicsLodRefPos - lastFrameData.m_position) >= 62500f;
CitizenApproachingParkedCarSimulationStep(instanceId, ref instanceData, ref lastFrameData, lodPhysics);
int newGridX = Mathf.Clamp(
(int)((lastFrameData.m_position.x / CitizenManager.CITIZENGRID_CELL_SIZE) +
(CitizenManager.CITIZENGRID_RESOLUTION / 2f)),
0,
CitizenManager.CITIZENGRID_RESOLUTION - 1);
int newGridY = Mathf.Clamp(
(int)((lastFrameData.m_position.z / CitizenManager.CITIZENGRID_CELL_SIZE) +
(CitizenManager.CITIZENGRID_RESOLUTION / 2f)),
0,
CitizenManager.CITIZENGRID_RESOLUTION - 1);
if ((newGridX != oldGridX || newGridY != oldGridY) &&
(instanceData.m_flags & CitizenInstance.Flags.Character) !=
CitizenInstance.Flags.None) {
Singleton<CitizenManager>.instance.RemoveFromGrid(
instanceId,
ref instanceData,
oldGridX,
oldGridY);
Singleton<CitizenManager>.instance.AddToGrid(
instanceId,
ref instanceData,
newGridX,
newGridY);
}
if (instanceData.m_flags != CitizenInstance.Flags.None) {
instanceData.SetFrameData(
Singleton<SimulationManager>.instance.m_currentFrameIndex,
lastFrameData);
}
}
[UsedImplicitly]
protected void CitizenApproachingParkedCarSimulationStep(ushort instanceId,
ref CitizenInstance instanceData,
ref CitizenInstance.Frame frameData,
bool lodPhysics) {
frameData.m_position += frameData.m_velocity * 0.5f;
Vector3 targetDiff = (Vector3)instanceData.m_targetPos - frameData.m_position;
Vector3 targetVelDiff = targetDiff - frameData.m_velocity;
float targetVelDiffMag = targetVelDiff.magnitude;
targetVelDiff *= 2f / Mathf.Max(targetVelDiffMag, 2f);
frameData.m_velocity += targetVelDiff;
frameData.m_velocity -= Mathf.Max(
0f,
Vector3.Dot(
(frameData.m_position + frameData.m_velocity) -
(Vector3)instanceData.m_targetPos,
frameData.m_velocity)) /
Mathf.Max(0.01f, frameData.m_velocity.sqrMagnitude) *
frameData.m_velocity;
if (frameData.m_velocity.sqrMagnitude > 0.01f) {
frameData.m_rotation = Quaternion.LookRotation(frameData.m_velocity);
}
}
public bool CitizenApproachingTargetSimulationStep(ushort instanceId,
ref CitizenInstance instanceData,
ref ExtCitizenInstance extInstance) {
IExtCitizenInstanceManager extCitInstMan = Constants.ManagerFactory.ExtCitizenInstanceManager;
#if DEBUG
bool citizenDebug =
(DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == instanceData.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == instanceData.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
if ((instanceData.m_flags & CitizenInstance.Flags.WaitingPath) !=
CitizenInstance.Flags.None) {
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.CitizenApproachingTargetSimulationStep({instanceId}): " +
$"citizen instance {instanceId} is waiting for path-finding to complete.");
return false;
}
// ExtCitizenInstance extInstance = ExtCitizenInstanceManager.Instance.GetExtInstance(instanceId);
if (extInstance.pathMode != ExtPathMode.WalkingToTarget &&
extInstance.pathMode != ExtPathMode.TaxiToTarget) {
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.CitizenApproachingTargetSimulationStep({instanceId}): " +
$"citizen instance {instanceId} is not reaching target ({extInstance.pathMode})");
}
return false;
}
if ((instanceData.m_flags & CitizenInstance.Flags.Character) ==
CitizenInstance.Flags.None) {
return false;
}
// check if path is complete
if (instanceData.m_pathPositionIndex != 255
&& (instanceData.m_path == 0
|| !CustomPathManager._instance.m_pathUnits.m_buffer[instanceData.m_path]
.GetPosition(
instanceData.m_pathPositionIndex >> 1,
out _))) {
extCitInstMan.Reset(ref extInstance);
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.CitizenApproachingTargetSimulationStep({instanceId}): " +
$"Citizen instance {instanceId} reached target. " +
$"CurrentDepartureMode={extInstance.pathMode}");
}
return true;
}
return false;
}
/// <summary>
/// Handles a path-finding success for activated Parking AI.
/// </summary>
/// <param name="instanceId">Citizen instance id</param>
/// <param name="instanceData">Citizen instance data</param>
/// <param name="extInstance">Extended citizen instance data</param>
/// <param name="extCitizen">Extended citizen data</param>
/// <param name="citizenData">Citizen data</param>
/// <returns>soft path state</returns>
protected ExtSoftPathState OnCitizenPathFindSuccess(ushort instanceId,
ref CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
ref ExtCitizen extCitizen,
ref Citizen citizenData) {
IExtCitizenInstanceManager extCitInstMan = Constants.ManagerFactory.ExtCitizenInstanceManager;
IExtBuildingManager extBuildingMan = Constants.ManagerFactory.ExtBuildingManager;
#if DEBUG
bool citizenDebug =
(DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == instanceData.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == instanceData.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
bool logParkingAi = false;
bool extendedLogParkingAi = false;
#endif
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Path-finding succeeded for citizen instance {instanceId}. " +
$"Path: {instanceData.m_path} vehicle={citizenData.m_vehicle}");
}
if (citizenData.m_vehicle == 0) {
// citizen does not already have a vehicle assigned
if (extInstance.pathMode == ExtPathMode.TaxiToTarget) {
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"Citizen uses a taxi. Decreasing public transport demand and " +
"returning READY.");
// cim uses taxi
if (instanceData.m_sourceBuilding != 0) {
extBuildingMan.RemovePublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_sourceBuilding],
GlobalConfig.Instance.ParkingAI.PublicTransportDemandUsageDecrement,
true);
}
if (instanceData.m_targetBuilding != 0) {
extBuildingMan.RemovePublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_targetBuilding],
GlobalConfig.Instance.ParkingAI.PublicTransportDemandUsageDecrement,
false);
}
extCitizen.transportMode |= ExtTransportMode.PublicTransport;
return ExtSoftPathState.Ready;
}
ushort parkedVehicleId = citizenData.m_parkedVehicle;
var sqrDistToParkedVehicle = 0f;
if (parkedVehicleId != 0) {
// calculate distance to parked vehicle
VehicleManager vehicleManager = Singleton<VehicleManager>.instance;
VehicleParked parkedVehicle = vehicleManager.m_parkedVehicles.m_buffer[parkedVehicleId];
Vector3 doorPosition = parkedVehicle.GetClosestDoorPosition(
parkedVehicle.m_position,
VehicleInfo.DoorType.Enter);
sqrDistToParkedVehicle = (instanceData.GetLastFramePosition() - doorPosition)
.sqrMagnitude;
}
byte laneTypes = CustomPathManager
._instance.m_pathUnits.m_buffer[instanceData.m_path].m_laneTypes;
uint vehicleTypes = CustomPathManager
._instance.m_pathUnits.m_buffer[instanceData.m_path]
.m_vehicleTypes;
bool usesPublicTransport =
(laneTypes & (byte)NetInfo.LaneType.PublicTransport) != 0;
bool usesCar = (laneTypes & (byte)(NetInfo.LaneType.Vehicle
| NetInfo.LaneType.TransportVehicle)) != 0
&& (vehicleTypes & (ushort)VehicleInfo.VehicleType.Car) != 0;
if (usesPublicTransport && usesCar &&
(extInstance.pathMode == ExtPathMode.CalculatingCarPathToKnownParkPos ||
extInstance.pathMode == ExtPathMode.CalculatingCarPathToAltParkPos)) {
// when using public transport together with a car (assuming a
// "source -> walk -> drive -> walk -> use public transport -> walk -> target"
// path) discard parking space information since the cim has to park near the
// public transport stop (instead of parking in the vicinity of the target building).
// TODO we could check if the path looks like "source -> walk -> use public transport -> walk -> drive -> [walk ->] target" (in this case parking space information would still be valid)
Log._DebugIf(
extendedLogParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"Citizen uses their car together with public transport. " +
"Discarding parking space information and setting path mode to " +
"CalculatingCarPathToTarget.");
extInstance.pathMode = ExtPathMode.CalculatingCarPathToTarget;
extInstance.parkingSpaceLocation = ExtParkingSpaceLocation.None;
extInstance.parkingSpaceLocationId = 0;
}
switch (extInstance.pathMode) {
case ExtPathMode.None: // citizen starts at source building
default: {
return OnCitizenPathFindSuccess_Default(
instanceId,
instanceData,
ref extInstance,
ref extCitizen,
logParkingAi,
usesCar,
parkedVehicleId,
extBuildingMan,
usesPublicTransport);
}
// citizen has not yet entered their car (but is close to do so) and tries to
// reach the target directly
case ExtPathMode.CalculatingCarPathToTarget:
// citizen has not yet entered their (but is close to do so) car and tries to
// reach a parking space in the vicinity of the target
case ExtPathMode.CalculatingCarPathToKnownParkPos:
// citizen has not yet entered their car (but is close to do so) and tries to
// reach an alternative parking space in the vicinity of the target
case ExtPathMode.CalculatingCarPathToAltParkPos:
{
return OnCitizenPathFindSuccess_CarPath(
instanceId,
ref instanceData,
ref extInstance,
ref extCitizen,
usesCar,
logParkingAi,
parkedVehicleId,
extCitInstMan,
sqrDistToParkedVehicle,
extendedLogParkingAi,
usesPublicTransport,
extBuildingMan);
}
case ExtPathMode.CalculatingWalkingPathToParkedCar: {
return OnCitizenPathFindSuccess_ToParkedCar(
instanceId,
instanceData,
ref extInstance,
parkedVehicleId,
logParkingAi,
extCitInstMan);
}
case ExtPathMode.CalculatingWalkingPathToTarget: {
return OnCitizenPathFindSuccess_ToTarget(
instanceId,
instanceData,
ref extInstance,
logParkingAi);
}
}
}
// citizen has a vehicle assigned
Log._DebugOnlyWarningIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"Citizen has a vehicle assigned but this method does not handle this " +
"situation. Forcing path-find to fail.");
extCitInstMan.Reset(ref extInstance);
return ExtSoftPathState.FailedHard;
}
private static ExtSoftPathState OnCitizenPathFindSuccess_ToTarget(
ushort instanceId,
CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
bool logParkingAi) {
// final walking path to target has been calculated
extInstance.pathMode = ExtPathMode.WalkingToTarget;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} is now travelling by foot to their final " +
$"target. CurrentDepartureMode={extInstance.pathMode}, " +
$"targetPos={instanceData.m_targetPos} " +
$"lastFramePos={instanceData.GetLastFramePosition()}");
}
return ExtSoftPathState.Ready;
}
private static ExtSoftPathState OnCitizenPathFindSuccess_ToParkedCar(
ushort instanceId,
CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
ushort parkedVehicleId,
bool logParkingAi,
IExtCitizenInstanceManager extCitInstMan) {
// path to parked vehicle has been calculated...
if (parkedVehicleId == 0) {
// ... but the parked vehicle has vanished
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} shall walk to their parked vehicle but it " +
"disappeared. Retrying path-find for walking.");
extCitInstMan.Reset(ref extInstance);
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToTarget;
return ExtSoftPathState.FailedSoft;
}
extInstance.pathMode = ExtPathMode.WalkingToParkedCar;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} is now on their way to its parked vehicle. " +
$"CurrentDepartureMode={extInstance.pathMode}, " +
$"targetPos={instanceData.m_targetPos} " +
$"lastFramePos={instanceData.GetLastFramePosition()}");
}
return ExtSoftPathState.Ready;
}
private ExtSoftPathState
OnCitizenPathFindSuccess_CarPath(ushort instanceId,
ref CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
ref ExtCitizen extCitizen,
bool usesCar,
bool logParkingAi,
ushort parkedVehicleId,
IExtCitizenInstanceManager extCitInstMan,
float sqrDistToParkedVehicle,
bool extendedLogParkingAi,
bool usesPublicTransport,
IExtBuildingManager extBuildingMan)
{
if (usesCar) {
// parked car should be reached now
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Path for citizen instance {instanceId} contains passenger car section and " +
"citizen should stand in front of their car.");
if (extInstance.atOutsideConnection) {
switch (extInstance.pathMode) {
// car path calculated starting at road outside connection: success
case ExtPathMode.CalculatingCarPathToAltParkPos: {
extInstance.pathMode = ExtPathMode.DrivingToAltParkPos;
extInstance.parkingPathStartPosition = null;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"Path to an alternative parking position is READY! " +
$"CurrentPathMode={extInstance.pathMode}");
}
break;
}
case ExtPathMode.CalculatingCarPathToTarget: {
extInstance.pathMode = ExtPathMode.DrivingToTarget;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Car path is READY! CurrentPathMode={extInstance.pathMode}");
}
break;
}
case ExtPathMode.CalculatingCarPathToKnownParkPos: {
extInstance.pathMode = ExtPathMode.DrivingToKnownParkPos;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"Car path to known parking position is READY! " +
$"CurrentPathMode={extInstance.pathMode}");
}
break;
}
}
extInstance.atOutsideConnection = false; // citizen leaves outside connection
return ExtSoftPathState.Ready;
}
if (parkedVehicleId == 0) {
// error! could not find/spawn parked car
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} still does not have a parked vehicle! " +
"Retrying: Cim should walk to target");
extCitInstMan.Reset(ref extInstance);
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToTarget;
return ExtSoftPathState.FailedSoft;
}
if (sqrDistToParkedVehicle >
4f * GlobalConfig.Instance.ParkingAI.MaxParkedCarInstanceSwitchSqrDistance) {
// error! parked car is too far away
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} cannot enter parked vehicle because it is " +
$"too far away (sqrDistToParkedVehicle={sqrDistToParkedVehicle})! " +
"Retrying: Cim should walk to parked car");
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToParkedCar;
return ExtSoftPathState.FailedSoft;
}
// path using passenger car has been calculated
if (EnterParkedCar(
instanceId,
ref instanceData,
parkedVehicleId,
out ushort vehicleId))
{
extInstance.pathMode =
extInstance.pathMode == ExtPathMode.CalculatingCarPathToTarget
? ExtPathMode.DrivingToTarget
: ExtPathMode.DrivingToKnownParkPos;
extCitizen.transportMode |= ExtTransportMode.Car;
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} has entered their car and is now " +
$"travelling by car (vehicleId={vehicleId}). " +
$"CurrentDepartureMode={extInstance.pathMode}, " +
$"targetPos={instanceData.m_targetPos} " +
$"lastFramePos={instanceData.GetLastFramePosition()}");
}
return ExtSoftPathState.Ignore;
}
// error! parked car could not be entered (reached vehicle limit?): try to walk to target
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Entering parked vehicle {parkedVehicleId} failed for citizen " +
$"instance {instanceId}. Trying to walk to target. " +
$"CurrentDepartureMode={extInstance.pathMode}");
}
extCitInstMan.Reset(ref extInstance);
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToTarget;
return ExtSoftPathState.FailedSoft;
}
// citizen does not need a car for the calculated path...
switch (extInstance.pathMode) {
case ExtPathMode.CalculatingCarPathToTarget: {
// ... and the path can be reused for walking
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"A direct car path was queried that does not contain a car section. " +
"Switching path mode to walking.");
extCitInstMan.Reset(ref extInstance);
if (usesPublicTransport) {
// decrease public tranport demand
if (instanceData.m_sourceBuilding != 0) {
extBuildingMan.RemovePublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_sourceBuilding],
GlobalConfig.Instance.ParkingAI.PublicTransportDemandUsageDecrement,
true);
}
if (instanceData.m_targetBuilding != 0) {
extBuildingMan.RemovePublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_targetBuilding],
GlobalConfig.Instance.ParkingAI.PublicTransportDemandUsageDecrement,
false);
}
extCitizen.transportMode |= ExtTransportMode.PublicTransport;
}
extInstance.pathMode = ExtPathMode.WalkingToTarget;
return ExtSoftPathState.Ready;
}
case ExtPathMode.CalculatingCarPathToKnownParkPos:
case ExtPathMode.CalculatingCarPathToAltParkPos:
default: {
// ... and a path to a parking spot was calculated: dismiss path and
// restart path-finding for walking
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"A parking space car path was queried but it turned out that no car is " +
"needed. Retrying path-finding for walking.");
extCitInstMan.Reset(ref extInstance);
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToTarget;
return ExtSoftPathState.FailedSoft;
}
}
}
private ExtSoftPathState
OnCitizenPathFindSuccess_Default(ushort instanceId,
CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
ref ExtCitizen extCitizen,
bool logParkingAi,
bool usesCar,
ushort parkedVehicleId,
IExtBuildingManager extBuildingMan,
bool usesPublicTransport)
{
if (extInstance.pathMode != ExtPathMode.None) {
if (logParkingAi) {
Log._DebugOnlyWarning(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Unexpected path mode {extInstance.pathMode}! {extInstance}");
}
}
ParkingAI parkingAiConf = GlobalConfig.Instance.ParkingAI;
if (usesCar) {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Path for citizen instance {instanceId} contains passenger car " +
"section. Ensuring that citizen is allowed to use their car.");
ushort sourceBuildingId = instanceData.m_sourceBuilding;
ushort homeId = Singleton<CitizenManager>
.instance.m_citizens.m_buffer[instanceData.m_citizen]
.m_homeBuilding;
if (parkedVehicleId == 0) {
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen {instanceData.m_citizen} (citizen instance {instanceId}), " +
$"source building {sourceBuildingId} does not have a parked " +
$"vehicle! CurrentPathMode={extInstance.pathMode}");
}
// try to spawn parked vehicle in the vicinity of the starting point.
VehicleInfo vehicleInfo = null;
if (instanceData.Info.m_agePhase > Citizen.AgePhase.Child) {
// get a random car info (due to the fact we are using a
// different randomizer, car assignment differs from the
// selection in ResidentAI.GetVehicleInfo/TouristAI.GetVehicleInfo
// method, but this should not matter since we are reusing
// parked vehicle infos there)
vehicleInfo =
Singleton<VehicleManager>.instance.GetRandomVehicleInfo(
ref Singleton<SimulationManager>.instance.m_randomizer,
ItemClass.Service.Residential,
ItemClass.SubService.ResidentialLow,
ItemClass.Level.Level1);
}
if (vehicleInfo != null) {
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen {instanceData.m_citizen} (citizen instance {instanceId}), " +
$"source building {sourceBuildingId} is using their own passenger car. " +
$"CurrentPathMode={extInstance.pathMode}");
}
// determine current position vector
Vector3 currentPos;
ushort currentBuildingId = Singleton<CitizenManager>
.instance.m_citizens.m_buffer[instanceData.m_citizen]
.GetBuildingByLocation();
Building[] buildingsBuffer = Singleton<BuildingManager>.instance.m_buildings.m_buffer;
if (currentBuildingId != 0) {
currentPos = buildingsBuffer[currentBuildingId].m_position;
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Taking current position from current building {currentBuildingId} " +
$"for citizen {instanceData.m_citizen} (citizen instance {instanceId}): " +
$"{currentPos} CurrentPathMode={extInstance.pathMode}");
}
} else {
currentBuildingId = sourceBuildingId;
currentPos = instanceData.GetLastFramePosition();
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
"Taking current position from last frame position for citizen " +
$"{instanceData.m_citizen} (citizen instance {instanceId}): " +
$"{currentPos}. Home {homeId} pos: " +
$"{buildingsBuffer[homeId].m_position} " +
$"CurrentPathMode={extInstance.pathMode}");
}
}
// spawn a passenger car near the current position
if (AdvancedParkingManager.Instance.TrySpawnParkedPassengerCar(
instanceData.m_citizen,
homeId,
currentPos,
vehicleInfo,
out Vector3 parkPos,
out ParkingError parkReason)) {
parkedVehicleId = Singleton<CitizenManager>
.instance.m_citizens.m_buffer[instanceData.m_citizen]
.m_parkedVehicle;
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Parked vehicle for citizen {instanceData.m_citizen} " +
$"(instance {instanceId}) is {parkedVehicleId} now (parkPos={parkPos}).");
if (currentBuildingId != 0) {
extBuildingMan.ModifyParkingSpaceDemand(
ref extBuildingMan.ExtBuildings[currentBuildingId],
parkPos,
parkingAiConf.MinSpawnedCarParkingSpaceDemandDelta,
parkingAiConf.MaxSpawnedCarParkingSpaceDemandDelta);
}
} else {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$">> Failed to spawn parked vehicle for citizen {instanceData.m_citizen} " +
$"(citizen instance {instanceId}). reason={parkReason}. homePos: " +
$"{buildingsBuffer[homeId].m_position}");
if (parkReason == ParkingError.NoSpaceFound &&
currentBuildingId != 0) {
extBuildingMan.AddParkingSpaceDemand(
ref extBuildingMan.ExtBuildings[currentBuildingId],
parkingAiConf.FailedSpawnParkingSpaceDemandIncrement);
}
}
} else {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen {instanceData.m_citizen} (citizen instance {instanceId}), " +
$"source building {sourceBuildingId}, home {homeId} does not own a vehicle.");
}
}
if (parkedVehicleId != 0) {
// citizen has to reach their parked vehicle first
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Calculating path to reach parked vehicle {parkedVehicleId} for citizen " +
$"instance {instanceId}. targetPos={instanceData.m_targetPos} " +
$"lastFramePos={instanceData.GetLastFramePosition()}");
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToParkedCar;
return ExtSoftPathState.FailedSoft;
}
// error! could not find/spawn parked car
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): " +
$"Citizen instance {instanceId} still does not have a parked vehicle! " +
"Retrying: Cim should walk to target");
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToTarget;
return ExtSoftPathState.FailedSoft;
}
// path does not contain a car section: path can be reused for walking
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindSuccess({instanceId}): A direct car " +
"path OR initial path was queried that does not contain a car section. " +
"Switching path mode to walking.");
if (usesPublicTransport) {
// decrease public tranport demand
if (instanceData.m_sourceBuilding != 0) {
extBuildingMan.RemovePublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_sourceBuilding],
parkingAiConf.PublicTransportDemandUsageDecrement,
true);
}
if (instanceData.m_targetBuilding != 0) {
extBuildingMan.RemovePublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_targetBuilding],
parkingAiConf.PublicTransportDemandUsageDecrement,
false);
}
extCitizen.transportMode |= ExtTransportMode.PublicTransport;
}
extInstance.pathMode = ExtPathMode.WalkingToTarget;
return ExtSoftPathState.Ready;
}
/// <summary>
/// Handles a path-finding failure for citizen instances and activated Parking AI.
/// </summary>
/// <param name="instanceId">Citizen instance id</param>
/// <param name="instanceData">Citizen instance data</param>
/// <param name="extInstance">extended citizen instance information</param>
/// <param name="extCitizen">extended citizen information</param>
/// <returns>if true path-finding may be repeated (path mode has been updated), false otherwise</returns>
protected ExtSoftPathState OnCitizenPathFindFailure(ushort instanceId,
ref CitizenInstance instanceData,
ref ExtCitizenInstance extInstance,
ref ExtCitizen extCitizen) {
IExtCitizenInstanceManager extCitInstMan = Constants.ManagerFactory.ExtCitizenInstanceManager;
IExtBuildingManager extBuildingMan = Constants.ManagerFactory.ExtBuildingManager;
#if DEBUG
bool citizenDebug
= (DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == instanceData.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == instanceData.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): Path-finding " +
$"failed for citizen instance {extInstance.instanceId}. " +
$"CurrentPathMode={extInstance.pathMode}");
}
// update public transport demands
if (extInstance.pathMode == ExtPathMode.None ||
extInstance.pathMode == ExtPathMode.CalculatingWalkingPathToTarget ||
extInstance.pathMode == ExtPathMode.CalculatingWalkingPathToParkedCar ||
extInstance.pathMode == ExtPathMode.TaxiToTarget) {
// could not reach target building by walking/driving/public transport: increase
// public transport demand
if ((instanceData.m_flags & CitizenInstance.Flags.CannotUseTransport) ==
CitizenInstance.Flags.None) {
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): " +
"Increasing public transport demand of target building " +
$"{instanceData.m_targetBuilding} and source building " +
$"{instanceData.m_sourceBuilding}");
}
if (instanceData.m_targetBuilding != 0) {
extBuildingMan.AddPublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_targetBuilding],
GlobalConfig.Instance.ParkingAI.PublicTransportDemandIncrement,
false);
}
if (instanceData.m_sourceBuilding != 0) {
extBuildingMan.AddPublicTransportDemand(
ref extBuildingMan.ExtBuildings[instanceData.m_sourceBuilding],
GlobalConfig.Instance.ParkingAI.PublicTransportDemandIncrement,
true);
}
}
}
// relocate parked car if abandoned
if (extInstance.pathMode == ExtPathMode.CalculatingWalkingPathToParkedCar) {
// parked car is unreachable
Citizen[] citizensBuffer = Singleton<CitizenManager> .instance.m_citizens.m_buffer;
ushort parkedVehicleId = citizensBuffer[instanceData.m_citizen].m_parkedVehicle;
if (parkedVehicleId != 0) {
// parked car is present
ushort homeId = 0;
Services.CitizenService.ProcessCitizen(
extCitizen.citizenId,
(uint citId, ref Citizen cit) => {
homeId = cit.m_homeBuilding;
return true;
});
// calculate distance between citizen and parked car
var movedCar = false;
Vector3 citizenPos = instanceData.GetLastFramePosition();
var parkedToCitizen = 0f;
Vector3 oldParkedVehiclePos = default;
Services.VehicleService.ProcessParkedVehicle(
parkedVehicleId,
(ushort parkedVehId, ref VehicleParked parkedVehicle) => {
oldParkedVehiclePos = parkedVehicle.m_position;
parkedToCitizen = (parkedVehicle.m_position - citizenPos).magnitude;
if (parkedToCitizen > GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToHome) {
// parked car is far away from current location
// -> relocate parked car and try again
movedCar = TryMoveParkedVehicle(
parkedVehicleId,
ref parkedVehicle,
citizenPos,
GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToHome,
homeId);
}
return true;
});
if (movedCar) {
// successfully moved the parked car to a closer location
// -> retry path-finding
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToParkedCar;
Vector3 parkedPos = Singleton<VehicleManager>.instance.m_parkedVehicles
.m_buffer[parkedVehicleId]
.m_position;
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): " +
$"Relocated parked car {parkedVehicleId} to a closer location (old pos/distance: " +
$"{oldParkedVehiclePos}/{parkedToCitizen}, new pos/distance: " +
$"{parkedPos}/{(parkedPos - citizenPos).magnitude}) " +
$"for citizen @ {citizenPos}. Retrying path-finding. " +
$"CurrentPathMode={extInstance.pathMode}");
}
return ExtSoftPathState.FailedSoft;
}
// could not move car
// -> despawn parked car, walk to target or use public transport
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): " +
$"Releasing unreachable parked vehicle {parkedVehicleId} for citizen " +
$"instance {extInstance.instanceId}. CurrentPathMode={extInstance.pathMode}");
}
Singleton<VehicleManager>.instance.ReleaseParkedVehicle(parkedVehicleId);
}
}
// check if path-finding may be repeated
var ret = ExtSoftPathState.FailedHard;
switch (extInstance.pathMode) {
case ExtPathMode.CalculatingCarPathToTarget:
case ExtPathMode.CalculatingCarPathToKnownParkPos:
case ExtPathMode.CalculatingWalkingPathToParkedCar: {
// try to walk to target
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): " +
"Path failed but it may be retried to walk to the target.");
extInstance.pathMode = ExtPathMode.RequiresWalkingPathToTarget;
ret = ExtSoftPathState.FailedSoft;
break;
}
default: {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): " +
"Path failed and walking to target is not an option. Resetting ext. instance.");
extCitInstMan.Reset(ref extInstance);
break;
}
}
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCitizenPathFindFailure({instanceId}): " +
$"Setting CurrentPathMode for citizen instance {extInstance.instanceId} " +
$"to {extInstance.pathMode}, ret={ret}");
}
// reset current transport mode for hard failures
if (ret == ExtSoftPathState.FailedHard) {
extCitizen.transportMode = ExtTransportMode.None;
}
return ret;
}
/// <summary>
/// Handles a path-finding failure for citizen instances and activated Parking AI.
/// </summary>
/// <param name="vehicleId">Vehicle id</param>
/// <param name="vehicleData">Vehicle data</param>
/// <param name="driverInstanceData">Driver citizen instance data</param>
/// <param name="driverExtInstance">extended citizen instance information of driver</param>
/// <returns>if true path-finding may be repeated (path mode has been updated), false otherwise</returns>
[UsedImplicitly]
protected ExtSoftPathState OnCarPathFindFailure(ushort vehicleId,
ref Vehicle vehicleData,
ref CitizenInstance driverInstanceData,
ref ExtCitizenInstance driverExtInstance) {
IExtCitizenInstanceManager extCitizenInstanceManager = Constants.ManagerFactory.ExtCitizenInstanceManager;
#if DEBUG
bool citizenDebug
= (DebugSettings.VehicleId == 0
|| DebugSettings.VehicleId == vehicleId)
&& (DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == driverExtInstance.instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == driverInstanceData.m_citizen)
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == driverInstanceData.m_sourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == driverInstanceData.m_targetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCarPathFindFailure({vehicleId}): Path-finding failed " +
$"for driver citizen instance {driverExtInstance.instanceId}. " +
$"CurrentPathMode={driverExtInstance.pathMode}");
}
// update parking demands
switch (driverExtInstance.pathMode) {
case ExtPathMode.None:
case ExtPathMode.CalculatingCarPathToAltParkPos:
case ExtPathMode.CalculatingCarPathToKnownParkPos: {
// could not reach target building by driving: increase parking space demand
if (extendedLogParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCarPathFindFailure({vehicleId}): " +
"Increasing parking space demand of target building " +
$"{driverInstanceData.m_targetBuilding}");
}
if (driverInstanceData.m_targetBuilding != 0) {
IExtBuildingManager extBuildingManager = Constants.ManagerFactory.ExtBuildingManager;
extBuildingManager.AddParkingSpaceDemand(
ref extBuildingManager.ExtBuildings[driverInstanceData.m_targetBuilding],
GlobalConfig.Instance.ParkingAI.FailedParkingSpaceDemandIncrement);
}
break;
}
}
// check if path-finding may be repeated
var ret = ExtSoftPathState.FailedHard;
switch (driverExtInstance.pathMode) {
case ExtPathMode.CalculatingCarPathToAltParkPos:
case ExtPathMode.CalculatingCarPathToKnownParkPos: {
// try to drive directly to the target if public transport is allowed
if ((driverInstanceData.m_flags & CitizenInstance.Flags.CannotUseTransport) ==
CitizenInstance.Flags.None) {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCarPathFindFailure({vehicleId}): " +
"Path failed but it may be retried to drive directly to the target " +
"/ using public transport.");
driverExtInstance.pathMode = ExtPathMode.RequiresMixedCarPathToTarget;
ret = ExtSoftPathState.FailedSoft;
}
break;
}
default: {
Log._DebugIf(
logParkingAi,
() => $"AdvancedParkingManager.OnCarPathFindFailure({vehicleId}): Path failed " +
"and a direct target is not an option. Resetting driver ext. instance.");
extCitizenInstanceManager.Reset(ref driverExtInstance);
break;
}
}
if (logParkingAi) {
Log._Debug(
$"AdvancedParkingManager.OnCarPathFindFailure({vehicleId}): Setting " +
$"CurrentPathMode for driver citizen instance {driverExtInstance.instanceId} " +
$"to {driverExtInstance.pathMode}, ret={ret}");
}
return ret;
}
public bool TryMoveParkedVehicle(ushort parkedVehicleId,
ref VehicleParked parkedVehicle,
Vector3 refPos,
float maxDistance,
ushort homeId) {
bool found;
Vector3 parkPos;
Quaternion parkRot;
found = Instance.FindParkingSpaceInVicinity(
refPos,
Vector3.zero,
parkedVehicle.Info,
homeId,
0,
maxDistance,
out _,
out _,
out parkPos,
out parkRot,
out _);
if (found) {
Singleton<VehicleManager>.instance.RemoveFromGrid(parkedVehicleId, ref parkedVehicle);
parkedVehicle.m_position = parkPos;
parkedVehicle.m_rotation = parkRot;
Singleton<VehicleManager>.instance.AddToGrid(parkedVehicleId, ref parkedVehicle);
}
return found;
}
public bool FindParkingSpaceForCitizen(Vector3 endPos,
VehicleInfo vehicleInfo,
ref ExtCitizenInstance extDriverInstance,
ushort homeId,
bool goingHome,
ushort vehicleId,
bool allowTourists,
out Vector3 parkPos,
ref PathUnit.Position endPathPos,
out bool calculateEndPos) {
IExtCitizenInstanceManager extCitInstMan = Constants.ManagerFactory.ExtCitizenInstanceManager;
#if DEBUG
CitizenInstance[] citizensBuffer = Singleton<CitizenManager> .instance.m_instances.m_buffer;
ushort ctzTargetBuilding = citizensBuffer[extDriverInstance.instanceId] .m_targetBuilding;
ushort ctzSourceBuilding = citizensBuffer[extDriverInstance.instanceId] .m_sourceBuilding;
bool citizenDebug
= (DebugSettings.VehicleId == 0
|| DebugSettings.VehicleId == vehicleId)
&& (DebugSettings.CitizenInstanceId == 0
|| DebugSettings.CitizenInstanceId == extDriverInstance.instanceId)
&& (DebugSettings.CitizenId == 0
|| DebugSettings.CitizenId == extCitInstMan.GetCitizenId(extDriverInstance.instanceId))
&& (DebugSettings.SourceBuildingId == 0
|| DebugSettings.SourceBuildingId == ctzSourceBuilding)
&& (DebugSettings.TargetBuildingId == 0
|| DebugSettings.TargetBuildingId == ctzTargetBuilding);
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
calculateEndPos = true;
parkPos = default;
if (!allowTourists) {
// TODO remove this from this method
uint citizenId = extCitInstMan.GetCitizenId(extDriverInstance.instanceId);
if (citizenId == 0 ||
(Singleton<CitizenManager>.instance.m_citizens.m_buffer[citizenId].m_flags &
Citizen.Flags.Tourist) != Citizen.Flags.None) {
return false;
}
}
if (extendedLogParkingAi) {
Log._Debug(
$"Citizen instance {extDriverInstance.instanceId} " +
$"(CurrentPathMode={extDriverInstance.pathMode}) can still use their passenger " +
"car and is either not a tourist or wants to find an alternative parking spot. " +
"Finding a parking space before starting path-finding.");
}
// find a free parking space
bool success = FindParkingSpaceInVicinity(
endPos,
Vector3.zero,
vehicleInfo,
homeId,
vehicleId,
goingHome
? GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToHome
: GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToBuilding,
out ExtParkingSpaceLocation knownParkingSpaceLocation,
out ushort knownParkingSpaceLocationId,
out parkPos,
out _,
out float parkOffset);
extDriverInstance.parkingSpaceLocation = knownParkingSpaceLocation;
extDriverInstance.parkingSpaceLocationId = knownParkingSpaceLocationId;
if (!success) {
return false;
}
if (extendedLogParkingAi) {
Log._Debug(
$"Found a parking spot for citizen instance {extDriverInstance.instanceId} " +
$"(CurrentPathMode={extDriverInstance.pathMode}) before starting car path: " +
$"{knownParkingSpaceLocation} @ {knownParkingSpaceLocationId}");
}
switch (knownParkingSpaceLocation) {
case ExtParkingSpaceLocation.RoadSide: {
// found segment with parking space
if (logParkingAi) {
Log._Debug(
$"Found segment {knownParkingSpaceLocationId} for road-side parking " +
$"position for citizen instance {extDriverInstance.instanceId}!");
}
// determine nearest sidewalk position for parking position at segment
if (Singleton<NetManager>.instance.m_segments.m_buffer[knownParkingSpaceLocationId]
.GetClosestLanePosition(
parkPos,
NetInfo.LaneType.Pedestrian,
VehicleInfo.VehicleType.None,
out _,
out uint laneId,
out int laneIndex,
out _)) {
endPathPos.m_segment = knownParkingSpaceLocationId;
endPathPos.m_lane = (byte)laneIndex;
endPathPos.m_offset = (byte)(parkOffset * 255f);
calculateEndPos = false;
// extDriverInstance.CurrentPathMode = successMode;
// ExtCitizenInstance.PathMode.CalculatingKnownCarPath;
if (logParkingAi) {
Log._Debug(
"Found an parking spot sidewalk position for citizen instance " +
$"{extDriverInstance.instanceId} @ segment {knownParkingSpaceLocationId}, " +
$"laneId {laneId}, laneIndex {laneIndex}, offset={endPathPos.m_offset}! " +
$"CurrentPathMode={extDriverInstance.pathMode}");
}
return true;
}
if (logParkingAi) {
Log._Debug(
"Could not find an alternative parking spot sidewalk position for " +
$"citizen instance {extDriverInstance.instanceId}! " +
$"CurrentPathMode={extDriverInstance.pathMode}");
}
return false;
}
case ExtParkingSpaceLocation.Building: {
// found a building with parking space
if (Constants.ManagerFactory.ExtPathManager.FindPathPositionWithSpiralLoop(
parkPos,
endPos,
ItemClass.Service.Road,
NetInfo.LaneType.Pedestrian,
VehicleInfo.VehicleType.None,
NetInfo.LaneType.Vehicle | NetInfo.LaneType.TransportVehicle,
VehicleInfo.VehicleType.Car,
false,
false,
GlobalConfig.Instance.ParkingAI.MaxBuildingToPedestrianLaneDistance,
out endPathPos)) {
calculateEndPos = false;
}
if (logParkingAi) {
Log._Debug(
$"Navigating citizen instance {extDriverInstance.instanceId} to parking " +
$"building {knownParkingSpaceLocationId}! segment={endPathPos.m_segment}, " +
$"laneIndex={endPathPos.m_lane}, offset={endPathPos.m_offset}. " +
$"CurrentPathMode={extDriverInstance.pathMode} " +
$"calculateEndPos={calculateEndPos}");
}
return true;
}
default:
return false;
}
}
public bool TrySpawnParkedPassengerCar(uint citizenId,
ushort homeId,
Vector3 refPos,
VehicleInfo vehicleInfo,
out Vector3 parkPos,
out ParkingError reason) {
#if DEBUG
bool citizenDebug = DebugSettings.CitizenId == 0 || DebugSettings.CitizenId == citizenId;
// var logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
// const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
Log._DebugIf(
extendedLogParkingAi && homeId != 0,
() => $"Trying to spawn parked passenger car for citizen {citizenId}, " +
$"home {homeId} @ {refPos}");
bool roadParkSuccess = TrySpawnParkedPassengerCarRoadSide(
citizenId,
refPos,
vehicleInfo,
out Vector3 roadParkPos,
out ParkingError roadParkReason);
bool buildingParkSuccess = TrySpawnParkedPassengerCarBuilding(
citizenId,
homeId,
refPos,
vehicleInfo,
out Vector3 buildingParkPos,
out ParkingError buildingParkReason);
if ((!roadParkSuccess && !buildingParkSuccess)
|| (roadParkSuccess && !buildingParkSuccess)) {
parkPos = roadParkPos;
reason = roadParkReason;
return roadParkSuccess;
}
if (!roadParkSuccess) {
parkPos = buildingParkPos;
reason = buildingParkReason;
return true;
}
if ((roadParkPos - refPos).sqrMagnitude < (buildingParkPos - refPos).sqrMagnitude) {
parkPos = roadParkPos;
reason = roadParkReason;
return true;
}
parkPos = buildingParkPos;
reason = buildingParkReason;
return true;
}
public bool TrySpawnParkedPassengerCarRoadSide(uint citizenId,
Vector3 refPos,
VehicleInfo vehicleInfo,
out Vector3 parkPos,
out ParkingError reason) {
#if DEBUG
bool citizenDebug = DebugSettings.CitizenId == 0 || DebugSettings.CitizenId == citizenId;
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
// bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
// const bool extendedLogParkingAi = false;
#endif
Log._DebugIf(
logParkingAi,
() => $"Trying to spawn parked passenger car at road side for citizen {citizenId} @ {refPos}");
parkPos = Vector3.zero;
if (FindParkingSpaceRoadSide(
0,
refPos,
vehicleInfo.m_generatedInfo.m_size.x,
vehicleInfo.m_generatedInfo.m_size.z,
GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToBuilding,
out parkPos,
out Quaternion parkRot,
out _))
{
// position found, spawn a parked vehicle
if (Singleton<VehicleManager>.instance.CreateParkedVehicle(
out ushort parkedVehicleId,
ref Singleton<SimulationManager>
.instance.m_randomizer,
vehicleInfo,
parkPos,
parkRot,
citizenId))
{
Singleton<CitizenManager>.instance.m_citizens.m_buffer[citizenId]
.SetParkedVehicle(citizenId, parkedVehicleId);
Singleton<VehicleManager>.instance.m_parkedVehicles.m_buffer[parkedVehicleId].m_flags
&= (ushort)(VehicleParked.Flags.All & ~VehicleParked.Flags.Parking);
if (logParkingAi) {
Log._Debug(
"[SUCCESS] Spawned parked passenger car at road side for citizen " +
$"{citizenId}: {parkedVehicleId} @ {parkPos}");
}
reason = ParkingError.None;
return true;
}
reason = ParkingError.LimitHit;
} else {
reason = ParkingError.NoSpaceFound;
}
Log._DebugIf(
logParkingAi,
() => $"[FAIL] Failed to spawn parked passenger car at road side for citizen {citizenId}");
return false;
}
public bool TrySpawnParkedPassengerCarBuilding(uint citizenId,
ushort homeId,
Vector3 refPos,
VehicleInfo vehicleInfo,
out Vector3 parkPos,
out ParkingError reason) {
#if DEBUG
bool citizenDebug = DebugSettings.CitizenId == 0 || DebugSettings.CitizenId == citizenId;
bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
bool extendedLogParkingAi = DebugSwitch.ExtendedParkingAILog.Get() && citizenDebug;
#else
const bool logParkingAi = false;
const bool extendedLogParkingAi = false;
#endif
Log._DebugIf(
extendedLogParkingAi && homeId != 0,
() => "Trying to spawn parked passenger car next to building for citizen " +
$"{citizenId} @ {refPos}");
parkPos = Vector3.zero;
if (FindParkingSpaceBuilding(
vehicleInfo,
homeId,
0,
0,
refPos,
GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToBuilding,
GlobalConfig.Instance.ParkingAI.MaxParkedCarDistanceToBuilding,
out parkPos,
out Quaternion parkRot,
out _))
{
// position found, spawn a parked vehicle
if (Singleton<VehicleManager>.instance.CreateParkedVehicle(
out ushort parkedVehicleId,
ref Singleton<SimulationManager>.instance.m_randomizer,
vehicleInfo,
parkPos,
parkRot,
citizenId))
{
Singleton<CitizenManager>.instance.m_citizens.m_buffer[citizenId]
.SetParkedVehicle(citizenId, parkedVehicleId);
Singleton<VehicleManager>.instance.m_parkedVehicles.m_buffer[parkedVehicleId].m_flags
&= (ushort)(VehicleParked.Flags.All & ~VehicleParked.Flags.Parking);
if (extendedLogParkingAi && homeId != 0) {
Log._Debug(
"[SUCCESS] Spawned parked passenger car next to building for citizen " +
$"{citizenId}: {parkedVehicleId} @ {parkPos}");
}
reason = ParkingError.None;
return true;
}
reason = ParkingError.LimitHit;
} else {
reason = ParkingError.NoSpaceFound;
}
Log._DebugIf(
logParkingAi && homeId != 0,
() => "[FAIL] Failed to spawn parked passenger car next to building " +
$"for citizen {citizenId}");
return false;
}
public bool FindParkingSpaceInVicinity(Vector3 targetPos,
Vector3 searchDir,
VehicleInfo vehicleInfo,
ushort homeId,
ushort vehicleId,
float maxDist,
out ExtParkingSpaceLocation parkingSpaceLocation,
out ushort parkingSpaceLocationId,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset) {
#if DEBUG
bool vehDebug = DebugSettings.VehicleId == 0 || DebugSettings.VehicleId == vehicleId;
bool logParkingAi = DebugSwitch.VehicleParkingAILog.Get() && vehDebug;
#else
const bool logParkingAi = false;
#endif
// TODO check isElectric
Vector3 refPos = targetPos + (searchDir * 16f);
// TODO depending on simulation accuracy, disable searching for both road-side and building parking spaces
ushort parkingSpaceSegmentId = FindParkingSpaceAtRoadSide(
0,
refPos,
vehicleInfo.m_generatedInfo.m_size.x,
vehicleInfo.m_generatedInfo.m_size.z,
maxDist,
true,
out Vector3 roadParkPos,
out Quaternion roadParkRot,
out float roadParkOffset);
ushort parkingBuildingId = FindParkingSpaceBuilding(
vehicleInfo,
homeId,
0,
0,
refPos,
maxDist,
maxDist,
true,
out Vector3 buildingParkPos,
out Quaternion buildingParkRot,
out float buildingParkOffset);
if (parkingSpaceSegmentId != 0) {
if (parkingBuildingId != 0) {
Randomizer rng = Services.SimulationService.Randomizer;
// choose nearest parking position, after a bit of randomization
if ((roadParkPos - targetPos).magnitude < (buildingParkPos - targetPos).magnitude
&& rng.Int32(GlobalConfig.Instance.ParkingAI.VicinityParkingSpaceSelectionRand) != 0) {
// road parking space is closer
Log._DebugIf(
logParkingAi,
() => "Found an (alternative) road-side parking position for " +
$"vehicle {vehicleId} @ segment {parkingSpaceSegmentId} after comparing " +
$"distance with a bulding parking position @ {parkingBuildingId}!");
parkPos = roadParkPos;
parkRot = roadParkRot;
parkOffset = roadParkOffset;
parkingSpaceLocation = ExtParkingSpaceLocation.RoadSide;
parkingSpaceLocationId = parkingSpaceSegmentId;
return true;
}
// choose building parking space
Log._DebugIf(
logParkingAi,
() => $"Found an alternative building parking position for vehicle {vehicleId} " +
$"at building {parkingBuildingId} after comparing distance with a road-side " +
$"parking position @ {parkingSpaceSegmentId}!");
parkPos = buildingParkPos;
parkRot = buildingParkRot;
parkOffset = buildingParkOffset;
parkingSpaceLocation = ExtParkingSpaceLocation.Building;
parkingSpaceLocationId = parkingBuildingId;
return true;
}
// road-side but no building parking space found
Log._DebugIf(
logParkingAi,
() => "Found an alternative road-side parking position for vehicle " +
$"{vehicleId} @ segment {parkingSpaceSegmentId}!");
parkPos = roadParkPos;
parkRot = roadParkRot;
parkOffset = roadParkOffset;
parkingSpaceLocation = ExtParkingSpaceLocation.RoadSide;
parkingSpaceLocationId = parkingSpaceSegmentId;
return true;
}
if (parkingBuildingId != 0) {
// building but no road-side parking space found
Log._DebugIf(
logParkingAi,
() => $"Found an alternative building parking position for vehicle {vehicleId} " +
$"at building {parkingBuildingId}!");
parkPos = buildingParkPos;
parkRot = buildingParkRot;
parkOffset = buildingParkOffset;
parkingSpaceLocation = ExtParkingSpaceLocation.Building;
parkingSpaceLocationId = parkingBuildingId;
return true;
}
// driverExtInstance.CurrentPathMode = ExtCitizenInstance.PathMode.AltParkFailed;
parkingSpaceLocation = ExtParkingSpaceLocation.None;
parkingSpaceLocationId = 0;
parkPos = default;
parkRot = default;
parkOffset = -1f;
Log._DebugIf(
logParkingAi,
() => $"Could not find a road-side or building parking position for vehicle {vehicleId}!");
return false;
}
protected ushort FindParkingSpaceAtRoadSide(ushort ignoreParked,
Vector3 refPos,
float width,
float length,
float maxDistance,
bool randomize,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset) {
#if DEBUG
bool logParkingAi = DebugSwitch.VehicleParkingAILog.Get();
#else
const bool logParkingAi = false;
#endif
parkPos = Vector3.zero;
parkRot = Quaternion.identity;
parkOffset = 0f;
var centerI = (int)((refPos.z / BuildingManager.BUILDINGGRID_CELL_SIZE) +
(BuildingManager.BUILDINGGRID_RESOLUTION / 2f));
var centerJ = (int)((refPos.x / BuildingManager.BUILDINGGRID_CELL_SIZE) +
(BuildingManager.BUILDINGGRID_RESOLUTION / 2f));
int radius = Math.Max(1, (int)(maxDistance / (BuildingManager.BUILDINGGRID_CELL_SIZE / 2f)) + 1);
NetManager netManager = Singleton<NetManager>.instance;
Randomizer rng = Singleton<SimulationManager>.instance.m_randomizer;
ushort foundSegmentId = 0;
Vector3 myParkPos = parkPos;
Quaternion myParkRot = parkRot;
float myParkOffset = parkOffset;
// Local function used for spiral loop below
bool LoopHandler(int i, int j) {
if (i < 0 || i >= BuildingManager.BUILDINGGRID_RESOLUTION || j < 0 ||
j >= BuildingManager.BUILDINGGRID_RESOLUTION) {
return true;
}
ushort segmentId =
netManager.m_segmentGrid[(i * BuildingManager.BUILDINGGRID_RESOLUTION) + j];
var iterations = 0;
while (segmentId != 0) {
NetInfo segmentInfo = netManager.m_segments.m_buffer[segmentId].Info;
Vector3 segCenter = netManager.m_segments.m_buffer[segmentId].m_bounds.center;
// randomize target position to allow for opposite road-side parking
ParkingAI parkingAiConf = GlobalConfig.Instance.ParkingAI;
segCenter.x +=
Singleton<SimulationManager>.instance.m_randomizer.Int32(
parkingAiConf.ParkingSpacePositionRand) -
(parkingAiConf.ParkingSpacePositionRand / 2u);
segCenter.z +=
Singleton<SimulationManager>.instance.m_randomizer.Int32(
parkingAiConf.ParkingSpacePositionRand) -
(parkingAiConf.ParkingSpacePositionRand / 2u);
if (netManager.m_segments.m_buffer[segmentId].GetClosestLanePosition(
segCenter,
NetInfo.LaneType.Parking,
VehicleInfo.VehicleType.Car,
out Vector3 innerParkPos,
out uint laneId,
out int laneIndex,
out _))
{
NetInfo.Lane laneInfo = segmentInfo.m_lanes[laneIndex];
if (!Options.parkingRestrictionsEnabled ||
ParkingRestrictionsManager.Instance.IsParkingAllowed(
segmentId,
laneInfo.m_finalDirection))
{
if (!Options.vehicleRestrictionsEnabled ||
(VehicleRestrictionsManager.Instance.GetAllowedVehicleTypes(
segmentId,
segmentInfo,
(uint)laneIndex,
laneInfo,
VehicleRestrictionsMode.Configured)
& ExtVehicleType.PassengerCar) != ExtVehicleType.None)
{
if (CustomPassengerCarAI.FindParkingSpaceRoadSide(
ignoreParked,
segmentId,
innerParkPos,
width,
length,
out innerParkPos,
out Quaternion innerParkRot,
out float innerParkOffset))
{
Log._DebugIf(
logParkingAi,
() => "FindParkingSpaceRoadSide: Found a parking space for " +
$"refPos {refPos}, segment center {segCenter} " +
$"@ {innerParkPos}, laneId {laneId}, laneIndex {laneIndex}!");
foundSegmentId = segmentId;
myParkPos = innerParkPos;
myParkRot = innerParkRot;
myParkOffset = innerParkOffset;
if (!randomize || rng.Int32(parkingAiConf
.VicinityParkingSpaceSelectionRand) != 0) {
return false;
}
} // if find parking roadside
} // if allowed vehicle types
} // if parking allowed
} // if closest lane position
segmentId = netManager.m_segments.m_buffer[segmentId].m_nextGridSegment;
if (++iterations >= NetManager.MAX_SEGMENT_COUNT) {
CODebugBase<LogChannel>.Error(
LogChannel.Core,
$"Invalid list detected!\n{Environment.StackTrace}");
break;
}
} // while segmentid
return true;
}
var coords = _spiral.GetCoords(radius);
for (int i = 0; i < radius * radius; i++) {
if (!LoopHandler((int)(centerI + coords[i].x), (int)(centerJ + coords[i].y))) {
break;
}
}
if (foundSegmentId == 0) {
Log._DebugIf(
logParkingAi,
() => $"FindParkingSpaceRoadSide: Could not find a parking space for refPos {refPos}!");
return 0;
}
parkPos = myParkPos;
parkRot = myParkRot;
parkOffset = myParkOffset;
return foundSegmentId;
}
protected ushort FindParkingSpaceBuilding(VehicleInfo vehicleInfo,
ushort homeID,
ushort ignoreParked,
ushort segmentId,
Vector3 refPos,
float maxBuildingDistance,
float maxParkingSpaceDistance,
bool randomize,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset) {
#if DEBUG
bool logParkingAi = DebugSwitch.VehicleParkingAILog.Get();
#else
const bool logParkingAi = false;
#endif
parkPos = Vector3.zero;
parkRot = Quaternion.identity;
parkOffset = -1f;
var centerI = (int)((refPos.z / BuildingManager.BUILDINGGRID_CELL_SIZE) +
(BuildingManager.BUILDINGGRID_RESOLUTION / 2f));
var centerJ = (int)((refPos.x / BuildingManager.BUILDINGGRID_CELL_SIZE) +
BuildingManager.BUILDINGGRID_RESOLUTION / 2f);
int radius = Math.Max(
1,
(int)(maxBuildingDistance / (BuildingManager.BUILDINGGRID_CELL_SIZE / 2f)) + 1);
Randomizer rng = Singleton<SimulationManager>.instance.m_randomizer;
ushort foundBuildingId = 0;
Vector3 myParkPos = parkPos;
Quaternion myParkRot = parkRot;
float myParkOffset = parkOffset;
// Local function used below in SpiralLoop
bool LoopHandler(int i, int j) {
if (i < 0 || i >= BuildingManager.BUILDINGGRID_RESOLUTION || j < 0 ||
j >= BuildingManager.BUILDINGGRID_RESOLUTION) {
return true;
}
ushort buildingId = Singleton<BuildingManager>.instance.m_buildingGrid[
(i * BuildingManager.BUILDINGGRID_RESOLUTION) + j];
var numIterations = 0;
Building[] buildingsBuffer = Singleton<BuildingManager>.instance.m_buildings.m_buffer;
ParkingAI parkingAiConf = GlobalConfig.Instance.ParkingAI;
while (buildingId != 0) {
if (FindParkingSpacePropAtBuilding(
vehicleInfo,
homeID,
ignoreParked,
buildingId,
ref buildingsBuffer[buildingId],
segmentId,
refPos,
ref maxParkingSpaceDistance,
randomize,
out Vector3 innerParkPos,
out Quaternion innerParkRot,
out float innerParkOffset))
{
foundBuildingId = buildingId;
myParkPos = innerParkPos;
myParkRot = innerParkRot;
myParkOffset = innerParkOffset;
if (!randomize
|| rng.Int32(parkingAiConf.VicinityParkingSpaceSelectionRand) != 0)
{
return false;
}
} // if find parking prop at building
buildingId = buildingsBuffer[buildingId].m_nextGridBuilding;
if (++numIterations >= 49152) {
CODebugBase<LogChannel>.Error(
LogChannel.Core,
$"Invalid list detected!\n{Environment.StackTrace}");
break;
}
} // while building id
return true;
}
var coords = _spiral.GetCoords(radius);
for (int i = 0; i < radius * radius; i++) {
if (!LoopHandler((int)(centerI + coords[i].x), (int)(centerJ + coords[i].y))) {
break;
}
}
if (foundBuildingId == 0) {
Log._DebugIf(
logParkingAi && homeID != 0,
() => $"FindParkingSpaceBuilding: Could not find a parking space for homeID {homeID}!");
return 0;
}
parkPos = myParkPos;
parkRot = myParkRot;
parkOffset = myParkOffset;
return foundBuildingId;
}
public bool FindParkingSpacePropAtBuilding(VehicleInfo vehicleInfo,
ushort homeId,
ushort ignoreParked,
ushort buildingId,
ref Building building,
ushort segmentId,
Vector3 refPos,
ref float maxDistance,
bool randomize,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset) {
#if DEBUG
bool logParkingAi = DebugSwitch.VehicleParkingAILog.Get();
#else
const bool logParkingAi = false;
#endif
// int buildingWidth = building.Width;
int buildingLength = building.Length;
// NON-STOCK CODE START
parkOffset = -1f; // only set if segmentId != 0
parkPos = default;
parkRot = default;
if ((building.m_flags & Building.Flags.Created) == Building.Flags.None) {
Log._DebugIf(
logParkingAi,
() => $"Refusing to find parking space at building {buildingId}! Building is not created.");
return false;
}
if ((building.m_problems & Notification.Problem.TurnedOff) != Notification.Problem.None) {
Log._DebugIf(
logParkingAi,
() => $"Refusing to find parking space at building {buildingId}! Building is not active.");
return false;
}
if ((building.m_flags & Building.Flags.Collapsed) != Building.Flags.None) {
Log._DebugIf(
logParkingAi,
() => $"Refusing to find parking space at building {buildingId}! Building is collapsed.");
return false;
}
Randomizer rng = Singleton<SimulationManager>.instance.m_randomizer; // NON-STOCK CODE
bool isElectric = vehicleInfo.m_class.m_subService != ItemClass.SubService.ResidentialLow;
BuildingInfo buildingInfo = building.Info;
Matrix4x4 transformMatrix = default;
var transformMatrixCalculated = false;
var result = false;
if (buildingInfo.m_class.m_service == ItemClass.Service.Residential &&
buildingId != homeId && rng.Int32((uint)Options.getRecklessDriverModulo()) != 0) {
// NON-STOCK CODE
return false;
}
var propMinDistance = 9999f; // NON-STOCK CODE
if (buildingInfo.m_props != null &&
(buildingInfo.m_hasParkingSpaces & VehicleInfo.VehicleType.Car) !=
VehicleInfo.VehicleType.None)
{
foreach (BuildingInfo.Prop prop in buildingInfo.m_props) {
var randomizer = new Randomizer(buildingId << 6 | prop.m_index);
if (randomizer.Int32(100u) >= prop.m_probability ||
buildingLength < prop.m_requiredLength) {
continue;
}
PropInfo propInfo = prop.m_finalProp;
if (propInfo == null) {
continue;
}
propInfo = propInfo.GetVariation(ref randomizer);
if (propInfo.m_parkingSpaces == null || propInfo.m_parkingSpaces.Length == 0) {
continue;
}
if (!transformMatrixCalculated) {
transformMatrixCalculated = true;
Vector3 pos = Building.CalculateMeshPosition(
buildingInfo,
building.m_position,
building.m_angle,
building.Length);
Quaternion q = Quaternion.AngleAxis(
building.m_angle * Mathf.Rad2Deg,
Vector3.down);
transformMatrix.SetTRS(pos, q, Vector3.one);
}
Vector3 position = transformMatrix.MultiplyPoint(prop.m_position);
if (CustomPassengerCarAI.FindParkingSpaceProp(
isElectric,
ignoreParked,
propInfo,
position,
building.m_angle + prop.m_radAngle,
prop.m_fixedHeight,
refPos,
vehicleInfo.m_generatedInfo.m_size.x,
vehicleInfo.m_generatedInfo.m_size.z,
ref propMinDistance,
ref parkPos,
ref parkRot))
{
// NON-STOCK CODE
result = true;
if (randomize
&& propMinDistance <= maxDistance
&& rng.Int32(GlobalConfig.Instance.ParkingAI.VicinityParkingSpaceSelectionRand) == 0)
{
break;
}
}
}
}
if (result && propMinDistance <= maxDistance) {
maxDistance = propMinDistance; // NON-STOCK CODE
if (logParkingAi) {
Log._Debug(
$"Found parking space prop in range ({maxDistance}) at building {buildingId}.");
}
if (segmentId == 0) {
return true;
}
// check if building is accessible from the given segment
Log._DebugIf(
logParkingAi,
() => $"Calculating unspawn position of building {buildingId} for segment {segmentId}.");
building.Info.m_buildingAI.CalculateUnspawnPosition(
buildingId,
ref building,
ref Singleton<SimulationManager>.instance.m_randomizer,
vehicleInfo,
out Vector3 unspawnPos,
out _);
// calculate segment offset
if (Singleton<NetManager>.instance.m_segments.m_buffer[segmentId].GetClosestLanePosition(
unspawnPos,
NetInfo.LaneType.Pedestrian,
VehicleInfo.VehicleType.None,
out Vector3 lanePos,
out uint laneId,
out int laneIndex,
out float laneOffset))
{
Log._DebugIf(
logParkingAi,
() => "Succeeded in finding unspawn position lane offset for building " +
$"{buildingId}, segment {segmentId}, unspawnPos={unspawnPos}! " +
$"lanePos={lanePos}, dist={(lanePos - unspawnPos).magnitude}, " +
$"laneId={laneId}, laneIndex={laneIndex}, laneOffset={laneOffset}");
// if (dist > 16f) {
// if (debug)
// Log._Debug(
// $"Distance between unspawn position and lane position is too big! {dist}
// unspawnPos={unspawnPos} lanePos={lanePos}");
// return false;
// }
parkOffset = laneOffset;
} else {
Log._DebugIf(
logParkingAi,
() => $"Could not find unspawn position lane offset for building {buildingId}, " +
$"segment {segmentId}, unspawnPos={unspawnPos}!");
}
return true;
}
if (result && logParkingAi) {
Log._Debug(
$"Could not find parking space prop in range ({maxDistance}) " +
$"at building {buildingId}.");
}
return false;
}
public bool FindParkingSpaceRoadSideForVehiclePos(VehicleInfo vehicleInfo,
ushort ignoreParked,
ushort segmentId,
Vector3 refPos,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset,
out uint laneId,
out int laneIndex) {
#if DEBUG
bool logParkingAi = DebugSwitch.VehicleParkingAILog.Get();
#else
const bool logParkingAi = false;
#endif
float width = vehicleInfo.m_generatedInfo.m_size.x;
float length = vehicleInfo.m_generatedInfo.m_size.z;
NetManager netManager = Singleton<NetManager>.instance;
if ((netManager.m_segments.m_buffer[segmentId].m_flags & NetSegment.Flags.Created)
!= NetSegment.Flags.None)
{
if (netManager.m_segments.m_buffer[segmentId].GetClosestLanePosition(
refPos,
NetInfo.LaneType.Parking,
VehicleInfo.VehicleType.Car,
out parkPos,
out laneId,
out laneIndex,
out parkOffset))
{
if (!Options.parkingRestrictionsEnabled ||
ParkingRestrictionsManager.Instance.IsParkingAllowed(
segmentId,
netManager.m_segments.m_buffer[segmentId].Info
.m_lanes[laneIndex].m_finalDirection))
{
if (CustomPassengerCarAI.FindParkingSpaceRoadSide(
ignoreParked,
segmentId,
parkPos,
width,
length,
out parkPos,
out parkRot,
out parkOffset)) {
if (logParkingAi) {
Log._Debug(
"FindParkingSpaceRoadSideForVehiclePos: Found a parking space " +
$"for refPos {refPos} @ {parkPos}, laneId {laneId}, " +
$"laneIndex {laneIndex}!");
}
return true;
}
}
}
}
parkPos = default;
parkRot = default;
laneId = 0;
laneIndex = -1;
parkOffset = -1f;
return false;
}
public bool FindParkingSpaceRoadSide(ushort ignoreParked,
Vector3 refPos,
float width,
float length,
float maxDistance,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset) {
return FindParkingSpaceAtRoadSide(
ignoreParked,
refPos,
width,
length,
maxDistance,
false,
out parkPos,
out parkRot,
out parkOffset) != 0;
}
public bool FindParkingSpaceBuilding(VehicleInfo vehicleInfo,
ushort homeId,
ushort ignoreParked,
ushort segmentId,
Vector3 refPos,
float maxBuildingDistance,
float maxParkingSpaceDistance,
out Vector3 parkPos,
out Quaternion parkRot,
out float parkOffset) {
return FindParkingSpaceBuilding(
vehicleInfo,
homeId,
ignoreParked,
segmentId,
refPos,
maxBuildingDistance,
maxParkingSpaceDistance,
false,
out parkPos,
out parkRot,
out parkOffset) != 0;
}
public bool GetBuildingInfoViewColor(ushort buildingId,
ref Building buildingData,
ref ExtBuilding extBuilding,
InfoManager.InfoMode infoMode,
out Color? color) {
color = null;
InfoProperties.ModeProperties[] modeProperties
= Singleton<InfoManager>.instance.m_properties.m_modeProperties;
switch (infoMode) {
case InfoManager.InfoMode.Traffic: {
// parking space demand info view
color = Color.Lerp(
modeProperties[(int)infoMode].m_targetColor,
modeProperties[(int)infoMode].m_negativeColor,
Mathf.Clamp01(extBuilding.parkingSpaceDemand * 0.01f));
return true;
}
case InfoManager.InfoMode.Transport when !(buildingData.Info.m_buildingAI is DepotAI): {
// public transport demand info view
// TODO should not depend on UI class "TrafficManagerTool"
color = Color.Lerp(
modeProperties[(int)InfoManager.InfoMode.Traffic].m_targetColor,
modeProperties[(int)InfoManager.InfoMode.Traffic].m_negativeColor,
Mathf.Clamp01(
(TrafficManagerTool.CurrentTransportDemandViewMode ==
TransportDemandViewMode.Outgoing
? extBuilding.outgoingPublicTransportDemand
: extBuilding.incomingPublicTransportDemand) * 0.01f));
return true;
}
default:
return false;
}
}
public string EnrichLocalizedCitizenStatus(string ret,
ref ExtCitizenInstance extInstance,
ref ExtCitizen extCitizen) {
switch (extInstance.pathMode) {
case ExtPathMode.ApproachingParkedCar:
case ExtPathMode.RequiresCarPath:
case ExtPathMode.RequiresMixedCarPathToTarget: {
ret = Translation.AICitizen.Get("Label:Entering vehicle") + ", " + ret;
break;
}
case ExtPathMode.RequiresWalkingPathToParkedCar:
case ExtPathMode.CalculatingWalkingPathToParkedCar:
case ExtPathMode.WalkingToParkedCar: {
ret = Translation.AICitizen.Get("Label:Walking to car") + ", " + ret;
break;
}
case ExtPathMode.CalculatingWalkingPathToTarget:
case ExtPathMode.TaxiToTarget:
case ExtPathMode.WalkingToTarget: {
if ((extCitizen.transportMode & ExtTransportMode.PublicTransport) != ExtTransportMode.None) {
ret = Translation.AICitizen.Get("Label:Using public transport")
+ ", " + ret;
} else {
ret = Translation.AICitizen.Get("Label:Walking") + ", " + ret;
}
break;
}
case ExtPathMode.CalculatingCarPathToTarget:
case ExtPathMode.CalculatingCarPathToKnownParkPos: {
ret = Translation.AICitizen.Get("Label:Thinking of a good parking spot")
+ ", " + ret;
break;
}
}
return ret;
}
public string EnrichLocalizedCarStatus(string ret, ref ExtCitizenInstance driverExtInstance) {
switch (driverExtInstance.pathMode) {
case ExtPathMode.DrivingToAltParkPos: {
if (driverExtInstance.failedParkingAttempts <= 1) {
ret = Translation.AICar.Get("Label:Driving to a parking spot")
+ ", " + ret;
} else {
ret = Translation.AICar.Get("Label:Driving to another parking spot")
+ " (#" + driverExtInstance.failedParkingAttempts + "), " + ret;
}
break;
}
case ExtPathMode.CalculatingCarPathToKnownParkPos:
case ExtPathMode.DrivingToKnownParkPos: {
ret = Translation.AICar.Get("Label:Driving to a parking spot") + ", " + ret;
break;
}
case ExtPathMode.ParkingFailed:
case ExtPathMode.CalculatingCarPathToAltParkPos: {
ret = Translation.AICar.Get("Label:Looking for a parking spot") + ", " + ret;
break;
}
case ExtPathMode.RequiresWalkingPathToTarget: {
ret = Locale.Get("VEHICLE_STATUS_PARKING") + ", " + ret;
break;
}
}
return ret;
}
}
}
| 49.034872 | 206 | 0.500738 | [
"MIT"
] | Katalyst6/TMPE | TLM/TLM/Manager/Impl/AdvancedParkingManager.cs | 147,644 | C# |
using System.Diagnostics;
namespace Cloudflare.Net.Objects
{
[DebuggerDisplay("{" + nameof(DebuggerDisplay) + "}")]
public class CloudflareError
{
public int Code { get; set; }
public string Message { get; set; }
private string DebuggerDisplay => $"Error: {Code} | {Message}";
}
}
| 20.375 | 71 | 0.616564 | [
"Apache-2.0"
] | thoo0224/Cloudflare.Net | src/Cloudflare.Net/Objects/CloudflareError.cs | 328 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using Verse;
using RimWorld;
using RimWorld.Planet;
namespace Vehicles
{
public static class GizmoHelper
{
/// <summary>
/// Trade dialog for AerialVehicle WorldObject
/// </summary>
/// <param name="aerialVehicle"></param>
/// <param name="faction"></param>
/// <param name="trader"></param>
public static Command_Action AerialVehicleTradeCommand(this AerialVehicleInFlight aerialVehicle, Faction faction = null, TraderKindDef trader = null)
{
Pawn bestNegotiator = WorldHelper.FindBestNegotiator(aerialVehicle.vehicle, faction, trader);
Command_Action command_Action = new Command_Action();
command_Action.defaultLabel = "CommandTrade".Translate();
command_Action.defaultDesc = "CommandTradeDesc".Translate();
command_Action.icon = VehicleTex.TradeCommandTex;
command_Action.action = delegate()
{
Settlement settlement = Find.WorldObjects.SettlementAt(aerialVehicle.Tile);
if (settlement != null && settlement.CanTradeNow)
{
Find.WindowStack.Add(new Dialog_TradeAerialVehicle(aerialVehicle, bestNegotiator, settlement, false));
PawnRelationUtility.Notify_PawnsSeenByPlayer_Letter_Send(settlement.Goods.OfType<Pawn>(), "LetterRelatedPawnsTradingWithSettlement".Translate(Faction.OfPlayer.def.pawnsPlural), LetterDefOf.NeutralEvent, false, true);
}
};
if (bestNegotiator is null)
{
if (trader != null && trader.permitRequiredForTrading != null && !aerialVehicle.vehicle.AllPawnsAboard.Any((Pawn p) => p.royalty != null && p.royalty.HasPermit(trader.permitRequiredForTrading, faction)))
{
command_Action.Disable("CommandTradeFailNeedPermit".Translate(trader.permitRequiredForTrading.LabelCap));
}
else
{
command_Action.Disable("CommandTradeFailNoNegotiator".Translate());
}
}
if (bestNegotiator != null && bestNegotiator.skills.GetSkill(SkillDefOf.Social).TotallyDisabled)
{
command_Action.Disable("CommandTradeFailSocialDisabled".Translate());
}
return command_Action;
}
/// <summary>
/// Trade dialog for AerialVehicle located on a Settlement
/// </summary>
/// <param name="vehicle"></param>
/// <param name="settlement"></param>
public static Command ShuttleTradeCommand(AerialVehicleInFlight vehicle, Settlement settlement)
{
Pawn bestNegotiator = WorldHelper.FindBestNegotiator(vehicle.vehicle, settlement.Faction, settlement.TraderKind);
Command_Action command_Action = new Command_Action
{
defaultLabel = "CommandTrade".Translate(),
defaultDesc = "CommandTradeDesc".Translate(),
icon = VehicleTex.TradeCommandTex,
action = delegate ()
{
if (settlement != null && settlement.CanTradeNow)
{
Find.WindowStack.Add(new Dialog_Trade(bestNegotiator, settlement, false));
PawnRelationUtility.Notify_PawnsSeenByPlayer_Letter_Send(settlement.Goods.OfType<Pawn>(), "LetterRelatedPawnsTradingWithSettlement".Translate(Faction.OfPlayer.def.pawnsPlural), LetterDefOf.NeutralEvent, false, true);
}
}
};
if (bestNegotiator is null)
{
if (settlement.TraderKind != null && settlement.TraderKind.permitRequiredForTrading != null && !vehicle.vehicle.AllPawnsAboard.Any((Pawn p) => p.royalty != null && p.royalty.HasPermit(settlement.TraderKind.permitRequiredForTrading, settlement.Faction)))
{
command_Action.Disable("CommandTradeFailNeedPermit".Translate(settlement.TraderKind.permitRequiredForTrading.LabelCap));
}
else
{
command_Action.Disable("CommandTradeFailNoNegotiator".Translate());
}
}
if (bestNegotiator != null && bestNegotiator.skills.GetSkill(SkillDefOf.Social).TotallyDisabled)
{
command_Action.Disable("CommandTradeFailSocialDisabled".Translate());
}
return command_Action;
}
/// <summary>
/// Draft gizmos for VehiclePawn
/// </summary>
/// <param name="drafter"></param>
public static IEnumerable<Gizmo> DraftGizmos(Pawn_DraftController drafter)
{
Command_Toggle command_Toggle = new Command_Toggle();
command_Toggle.hotKey = KeyBindingDefOf.Command_ColonistDraft;
command_Toggle.isActive = (() => drafter.Drafted);
command_Toggle.toggleAction = delegate()
{
drafter.Drafted = !drafter.Drafted;
PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.Drafting, KnowledgeAmount.SpecificInteraction);
if (drafter.Drafted)
{
LessonAutoActivator.TeachOpportunity(ConceptDefOf.QueueOrders, OpportunityType.GoodToKnow);
}
};
command_Toggle.defaultDesc = "CommandToggleDraftDesc".Translate();
command_Toggle.icon = TexCommand.Draft;
command_Toggle.turnOnSound = SoundDefOf.DraftOn;
command_Toggle.turnOffSound = SoundDefOf.DraftOff;
if (!drafter.Drafted)
{
command_Toggle.defaultLabel = "CommandDraftLabel".Translate();
}
if (drafter.pawn.Downed)
{
command_Toggle.Disable("IsIncapped".Translate(drafter.pawn.LabelShort, drafter.pawn));
}
if (!drafter.Drafted)
{
command_Toggle.tutorTag = "Draft";
}
else
{
command_Toggle.tutorTag = "Undraft";
}
yield return command_Toggle;
if (drafter.Drafted && drafter.pawn.equipment.Primary != null && drafter.pawn.equipment.Primary.def.IsRangedWeapon)
{
yield return new Command_Toggle
{
hotKey = KeyBindingDefOf.Misc6,
isActive = (() => drafter.FireAtWill),
toggleAction = delegate()
{
drafter.FireAtWill = !drafter.FireAtWill;
},
icon = TexCommand.FireAtWill,
defaultLabel = "CommandFireAtWillLabel".Translate(),
defaultDesc = "CommandFireAtWillDesc".Translate(),
tutorTag = "FireAtWillToggle"
};
}
yield break;
}
/// <summary>
/// Resolve designators when changes have been made to <paramref name="designationCategoryDef"/>
/// </summary>
/// <param name="designationCategoryDef"></param>
public static void DesignatorsChanged(DesignationCategoryDef designationCategoryDef)
{
AccessTools.Method(typeof(DesignationCategoryDef), "ResolveDesignators").Invoke(designationCategoryDef, new object[] { });
}
}
}
| 38.018634 | 257 | 0.73256 | [
"MIT"
] | SmashPhil/Boats | Source/Vehicles/Utility/Helpers/GizmoHelper.cs | 6,123 | C# |
/*
* Copyright (c) 2020 BlackArrow
*
* Author:
* Pablo Martinez (https://twitter.com/xassiz)
*
*/
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using System.Net;
using System.Collections;
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
}
public partial class StoredProcedures
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int main(string client_addr, int client_port);
[Microsoft.SqlServer.Server.SqlProcedure]
public static void sp_start_proxy (string path, string client_addr, int client_port)
{
string msg = "ok";
IntPtr pDll = NativeMethods.LoadLibrary(path);
if(pDll == IntPtr.Zero){
msg = "error LoadLibrary";
}
else {
IntPtr func = NativeMethods.GetProcAddress(pDll, "main");
if(func == IntPtr.Zero){
msg = "error GetProcAddress";
}
else {
main m = (main)Marshal.GetDelegateForFunctionPointer(func, typeof(main));
m(client_addr, client_port);
}
NativeMethods.FreeLibrary(pDll);
}
// Create the record and specify the metadata for the columns.
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
// Mark the beginning of the result set.
SqlContext.Pipe.SendResultsStart(record);
// Set values for each column in the row
record.SetString(0, msg);
// Send the row back to the client.
SqlContext.Pipe.SendResultsRow(record);
// Mark the end of the result set.
SqlContext.Pipe.SendResultsEnd();
}
};
| 27.043956 | 133 | 0.598131 | [
"MIT"
] | 0xdf-0xdf/mssqlproxy | assembly.cs | 2,461 | C# |
using System;
using System.IO;
namespace AlviSharp.Serializer.Cmd
{
class MainClass
{
public static void Main (string[] args)
{
//Convert to JSON
string path = args [0];
var text = File.ReadAllText (path);
XmlAlvisSerializer xmlAlivis = new XmlAlvisSerializer ();
var alvisproject = xmlAlivis.Deserialize (text);
JsonAlvisSerializer jsonAlvis = new JsonAlvisSerializer ();
var json = jsonAlvis.Serialize (alvisproject);
Console.WriteLine (json);
}
}
}
| 19.64 | 62 | 0.706721 | [
"MIT"
] | arekbee/AlviSharp | Src/AlviSharp/Run/AlviSharp.Serializer.Cmd/Program.cs | 493 | C# |
namespace Elf.Services.Models;
public class MostRequestedLinkCount
{
public string FwToken { get; set; }
public string Note { get; set; }
public int RequestCount { get; set; }
}
| 19.3 | 41 | 0.689119 | [
"MIT"
] | EdiWang/Elf | src/Elf.Services/Models/MostRequestedLinkCount.cs | 195 | C# |
using StoryBot.Core.Abstractions;
using StoryBot.Core.Extensions;
using StoryBot.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
namespace StoryBot.Vk.Logic
{
public class VkMessageBuilder : IMessageBuilder<MessagesSendParams>
{
/// <summary>
/// Logger
/// </summary>
private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// Command prefix
/// </summary>
private char Prefix { get; }
/// <summary>
/// Default constructor
/// </summary>
/// <param name="prefix"></param>
public VkMessageBuilder(char prefix)
{
Prefix = prefix;
}
public MessagesSendParams BuildContent(StorylineElement storylineElement, List<string> unlockables)
{
StringBuilder stringBuilder = new StringBuilder();
// Add content per-line
foreach (string x in storylineElement.Content)
{
stringBuilder.Append(x + "\n");
}
stringBuilder.Append("\n");
KeyboardBuilder keyboardBuilder = new KeyboardBuilder(false);
// Add options
for (int i = 0; i < storylineElement.Options.Length; i++)
{
var x = storylineElement.Options[i];
// If current progress already contains unlockable skip option
if (unlockables.Contains(x.Unlocks))
continue;
// Needed check
var color = KeyboardButtonColor.Default;
if (x.Needed != null)
{
if (x.Needed.All(unlockables.Contains))
{
color = KeyboardButtonColor.Positive;
}
else continue;
}
// Add option to message and buttons
stringBuilder.Append($"[ {i + 1} ] {x.Content}\n");
keyboardBuilder.AddButton($"[ {i + 1} ]",
(i + 1).ToString(),
color);
}
return new MessagesSendParams
{
Message = stringBuilder.ToString(),
Keyboard = keyboardBuilder.Build()
};
}
public MessagesSendParams BuildAchievement(StoryAchievement achievement)
{
return new MessagesSendParams
{
Message = $"Вы заработали достижение {achievement.Name}!\n - {achievement.Description}\n\n"
};
}
public MessagesSendParams BuildEnding(StoryDocument story, int position)
{
StringBuilder stringBuilder = new StringBuilder();
if (story.Episode != 0) // Prologue check
{
StoryEnding ending = story.Endings[position];
foreach (string x in ending.Content)
{
stringBuilder.Append(x + "\n");
}
int alternativeEndingsCount = story.Endings.Length - 1;
if (position == 0) // Check if ending canonical
{
stringBuilder.Append($"\nПоздравляем, вы получили каноничную концовку \"{ending.Name}\"!\n\n");
stringBuilder.Append($"Вы можете пройти этот эпизод еще раз. Он содержит еще {alternativeEndingsCount} альтернативные концовки.");
}
else // Alternative
{
stringBuilder.Append($"\nПоздравляем, вы получили альтернативную концовку \"{ending.Name}\"!\n\n");
stringBuilder.Append($"Вы можете пройти этот эпизод еще раз. Он содержит еще {alternativeEndingsCount - 1} альтернативные концовки и одну каноничную.");
}
}
else // If it is a prologue
{
stringBuilder.Append("\nПоздравляем, вы завершили пролог!");
}
return new MessagesSendParams
{
Message = stringBuilder.ToString()
};
}
public MessagesSendParams BuildStorySelectDialog(List<StoryDocument> prologues)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Выберите историю из представленных:\n");
KeyboardBuilder keyboardBuilder = new KeyboardBuilder(false);
for (int i = 0; i < prologues.Count; i++)
{
stringBuilder.Append($"[ {i + 1} ] {prologues[i].Name}\n");
keyboardBuilder.AddButton(
$"[ {i + 1} ]",
(i + 1).ToString(),
KeyboardButtonColor.Primary);
}
return new MessagesSendParams
{
Message = stringBuilder.ToString(),
Keyboard = keyboardBuilder.Build()
};
}
public MessagesSendParams BuildEpisodeSelectDialog(List<StoryDocument> episodes, SaveStoryStats storyProgress)
{
StringBuilder stringBuilder = new StringBuilder();
KeyboardBuilder keyboardBuilder = new KeyboardBuilder(false);
stringBuilder.Append($"Выберите эпизод истории \"{episodes[0].Name}\" или используйте команду \"{Prefix}select\" для выбора другой истории:\n\n");
// For prologue
stringBuilder.Append($"Пролог\n");
keyboardBuilder.AddButton(
$"[ Пролог ]",
"0",
KeyboardButtonColor.Primary);
// For other episodes
for (int i = 1; i < episodes.Count; i++)
{
if (storyProgress.Episodes.Count >= i && storyProgress.Episodes[i - 1].ObtainedEndings.Contains(0))
{
var episode = episodes[i];
stringBuilder.Append($"Эпизод {i.ToRoman()}. {episode.Name}\n");
keyboardBuilder.AddButton(
$"[ Эпизод {i.ToRoman()} ]",
i.ToString(),
KeyboardButtonColor.Primary);
}
else
{
break;
}
}
return new MessagesSendParams
{
Message = stringBuilder.ToString(),
Keyboard = keyboardBuilder.Build()
};
}
public MessagesSendParams BuildStats(List<StoryDocument> prologues, List<SaveStoryStats> storiesStats)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Общая статистика:\n\n");
foreach (var prologue in prologues)
{
int completedEpisodes = 0;
var episodes = storiesStats.Find(x => x.StoryId == prologue.StoryId).Episodes;
foreach (var episode in episodes)
{
if (episode.ObtainedEndings.Contains(0))
completedEpisodes++;
}
stringBuilder.Append($"{prologue.StoryId}. {prologue.Name} - Пройдено эпизодов: {completedEpisodes}\n");
}
return new MessagesSendParams
{
Message = stringBuilder.ToString()
};
}
public MessagesSendParams BuildStoryStats(List<StoryDocument> episodes, List<SaveEpisodeStats> episodesStats)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append($"Статистика по \"{episodes[0].Name}\":\n");
try
{
// Prologue
if (episodesStats[0].ObtainedEndings.Contains(0))
{
stringBuilder.Append($"- Пролог. Завершено\n");
}
else
{
stringBuilder.Append($"- Пролог. Не завершено\n");
}
int i = 1;
// Completed
for (; i < episodes.Count; i++)
{
if (!episodesStats[i].ObtainedEndings.Contains(0))
{
break;
}
var episode = episodes[i];
stringBuilder.Append($"- Эпизод {i.ToRoman()}. {episode.Name}: {episodesStats[i].ObtainedEndings.Count}/{episode.Endings.Length} концовок, {episodesStats[i].ObtainedAchievements.Count}/{episode.Achievements.Length} достижений\n");
}
// Not completed
for (; i < episodes.Count; i++)
{
var episode = episodes[i];
stringBuilder.Append($"- Эпизод {i.ToRoman()} [НЕ ОТКРЫТО]");
}
}
catch (NullReferenceException)
{
stringBuilder.Append("\n- Нет данных.");
logger.Warn("No data for stats");
}
return new MessagesSendParams
{
Message = stringBuilder.ToString()
};
}
public MessagesSendParams BuildEpisodeStats(StoryDocument episodeData, SaveEpisodeStats episodeStats)
{
if (episodeData.Episode == 0)
{
return new MessagesSendParams
{
Message = "Нельзя получить статистику по прологу"
};
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append($"Статистика по эпизоду {episodeData.Episode.ToRoman()}. {episodeData.Name}:\n\n");
try
{
stringBuilder.Append($"Полученные концовки ({episodeStats.ObtainedEndings.Count}/{episodeData.Endings.Length}):\n");
for (int i = 0; i < episodeData.Endings.Length; i++)
{
if (episodeStats.ObtainedEndings.Contains(i))
{
string type;
if (i == 0)
type = "ОСН";
else
type = "АЛЬТ";
stringBuilder.Append($"- [{type}] \"{episodeData.Endings[i].Name}\"\n");
}
}
stringBuilder.Append($"\nПолученные достижения ({episodeStats.ObtainedAchievements.Count}/{episodeData.Achievements.Length}):\n");
for (int i = 0; i < episodeData.Achievements.Length; i++)
{
if (episodeStats.ObtainedAchievements.Contains(i))
{
stringBuilder.Append($"- \"{episodeData.Achievements[i].Name}\"\n");
}
}
}
catch (NullReferenceException)
{
stringBuilder.Append("- Нет данных.");
}
return new MessagesSendParams
{
Message = stringBuilder.ToString()
};
}
public MessagesSendParams BuildBeginningMessage()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine("Добро пожаловать!");
stringBuilder.AppendLine();
stringBuilder.AppendLine("Для большего удобства, пользуйтесь клиентом поддерживающим кнопки для ботов ВКонтакте (например официальным).");
stringBuilder.AppendLine("Возможно и управление при помощи сообщений.");
stringBuilder.AppendLine();
stringBuilder.AppendLine("Ваш прогресс будет сохраняться автоматически.");
return new MessagesSendParams
{
Message = stringBuilder.ToString()
};
}
public MessagesSendParams BuildIndexOutOfRangeMessage()
{
return new MessagesSendParams
{
Message = "Выберите вариант из представленных D:"
};
}
public MessagesSendParams BuildSomethingWentWrongMessage(string exception = null)
{
if (string.IsNullOrEmpty(exception)) exception = ":\n" + exception;
return new MessagesSendParams
{
Message = ":( Что-то пошло не так при обработке вашего запроса" + exception
};
}
public MessagesSendParams BuildCommandList()
{
StringBuilder stringBuilder = new StringBuilder("Список команд:\n\n");
stringBuilder.AppendLine(Prefix + "select - Диалог выбора истории (Сбросит прогресс текущего эпизода!)");
stringBuilder.AppendLine();
stringBuilder.AppendLine(Prefix + "repeat - Заново отправляет сообщений с диалогом выбора для текущей истории");
stringBuilder.AppendLine();
stringBuilder.AppendLine(Prefix + "list - Список всех историй и ваша статистика по ним");
stringBuilder.AppendLine(Prefix + "list <номер_истории> - Список всех эпизодов истории и ваша статистика по ним");
stringBuilder.AppendLine(Prefix + "list <номер_истории> <номер_эпизода (0 для пролога)> - Ваша статистика по эпизоду");
return new MessagesSendParams
{
Message = stringBuilder.ToString()
};
}
}
}
| 37.678771 | 250 | 0.523241 | [
"MIT"
] | AWhiteFox/StoryBot | Logic/VkMessageBuilder.cs | 14,642 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the clouddirectory-2017-01-11.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.CloudDirectory.Model
{
/// <summary>
/// Identifies the schema Amazon Resource Name (ARN) and facet name for the typed link.
/// </summary>
public partial class TypedLinkSchemaAndFacetName
{
private string _schemaArn;
private string _typedLinkName;
/// <summary>
/// Gets and sets the property SchemaArn.
/// <para>
/// The Amazon Resource Name (ARN) that is associated with the schema. For more information,
/// see <a>arns</a>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string SchemaArn
{
get { return this._schemaArn; }
set { this._schemaArn = value; }
}
// Check to see if SchemaArn property is set
internal bool IsSetSchemaArn()
{
return this._schemaArn != null;
}
/// <summary>
/// Gets and sets the property TypedLinkName.
/// <para>
/// The unique name of the typed link facet.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string TypedLinkName
{
get { return this._typedLinkName; }
set { this._typedLinkName = value; }
}
// Check to see if TypedLinkName property is set
internal bool IsSetTypedLinkName()
{
return this._typedLinkName != null;
}
}
} | 30.038462 | 112 | 0.622706 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/CloudDirectory/Generated/Model/TypedLinkSchemaAndFacetName.cs | 2,343 | C# |
// Copyright (c) Amer Koleci and contributors.
// Distributed under the MIT license. See the LICENSE file in the project root for more information.
namespace Vortice.DirectX.Direct2D
{
/// <summary>
/// Describes the extend modes and the interpolation mode of an <see cref="ID2D1BitmapBrush"/>.
/// </summary>
public partial struct BitmapBrushProperties1
{
/// <summary>
/// Initializes a new instance of the <see cref="BitmapBrushProperties1"/> struct.
/// </summary>
/// <param name="extendModeX">A value that describes how the brush horizontally tiles those areas that extend past its bitmap.</param>
/// <param name="extendModeY">A value that describes how the brush vertically tiles those areas that extend past its bitmap.</param>
/// <param name="interpolationMode">A value that specifies how the bitmap is interpolated when it is scaled or rotated.</param>
public BitmapBrushProperties1(ExtendMode extendModeX, ExtendMode extendModeY, InterpolationMode interpolationMode)
{
ExtendModeX = extendModeX;
ExtendModeY = extendModeY;
InterpolationMode = interpolationMode;
}
}
}
| 48.6 | 142 | 0.691358 | [
"MIT"
] | Aminator/Vortice.Windows | src/Vortice.DirectX.Direct2D/BitmapBrushProperties1.cs | 1,217 | C# |
//******************************************************************************************************
// VendorUserControl.cs - Gbtc
//
// Copyright © 2010, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 07/13/2010 - Mehulbhai P Thakkar
// Generated original version of source code.
//
//******************************************************************************************************
using System;
using System.Windows;
using openPDCManager.ModalDialogs;
using openPDCManager.Utilities;
using openPDCManager.Data;
using openPDCManager.Data.Entities;
using System.Collections.Generic;
using System.Threading;
namespace openPDCManager.UserControls.CommonControls
{
public partial class VendorUserControl
{
#region [ Methods ]
void Initialize()
{
if (((App)Application.Current).Principal.IsInRole("Administrator, Editor"))
ButtonSave.IsEnabled = true;
else
ButtonSave.IsEnabled = false;
}
void GetVendors()
{
try
{
ListBoxVendorList.ItemsSource = CommonFunctions.GetVendorList(null);
if (ListBoxVendorList.Items.Count > 0)
ListBoxVendorList.SelectedIndex = 0;
}
catch (Exception ex)
{
CommonFunctions.LogException(null, "WPF.GetVendors", ex);
SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Vendor List", SystemMessage = ex.Message, UserMessageType = MessageType.Error },
ButtonType.OkOnly);
sm.Owner = Window.GetWindow(this);
sm.ShowPopup();
}
}
void SaveVendor(Vendor vendor, bool isNew)
{
SystemMessages sm;
try
{
string result = CommonFunctions.SaveVendor(null, vendor, isNew);
sm = new SystemMessages(new Message() { UserMessage = result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
ButtonType.OkOnly);
sm.Owner = Window.GetWindow(this);
sm.ShowPopup();
GetVendors();
//ClearForm();
//make this newly added or updated item as default selected. So user can click initialize right away.
ListBoxVendorList.SelectedItem = ((List<Vendor>)ListBoxVendorList.ItemsSource).Find(c => c.Acronym == vendor.Acronym);
}
catch (Exception ex)
{
CommonFunctions.LogException(null, "WPF.SaveVendor", ex);
sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Vendor Information", SystemMessage = ex.Message, UserMessageType = MessageType.Error },
ButtonType.OkOnly);
sm.Owner = Window.GetWindow(this);
sm.ShowPopup();
}
}
#endregion
}
}
| 42.042105 | 185 | 0.562093 | [
"MIT"
] | GridProtectionAlliance/openPDC | Source/Applications/openPDCManager/WPF/UserControls/CommonControls/VendorUserControl.cs | 3,997 | C# |
using Microsoft.EntityFrameworkCore;
namespace Sales.Domain.ValueObjects
{
[Owned]
public class Address
{
// Street
public string Thoroughfare { get; set; } = null!;
// Street number
public string Premises { get; set; } = null!;
// Suite
public string? SubPremises { get; set; }
public string PostalCode { get; set; } = null!;
// Town or City
public string Locality { get; set; } = null!;
// County
public string SubAdministrativeArea { get; set; } = null!;
// State
public string AdministrativeArea { get; set; } = null!;
public string Country { get; set; } = null!;
}
} | 23.806452 | 67 | 0.54065 | [
"MIT"
] | marinasundstrom/PointOfSale | Sales/Sales/Domain/ValueObjects/Address.cs | 738 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CapaNegocio;
namespace CapaPresentacion
{
public partial class FrmAgregarNuevaCategoria : Form
{
Categorias _owner;
public FrmAgregarNuevaCategoria()
{
InitializeComponent();
}
public FrmAgregarNuevaCategoria(Categorias owner)
{
_owner = owner;
InitializeComponent();
}
private void MensajeError(string mensaje)
{
MessageBox.Show(mensaje, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void buttonCancelar_Click(object sender, EventArgs e)
{
this.Close();
}
private void buttonGuardar_Click(object sender, EventArgs e)
{
String mensaje = NCategorias.Insertar(this.textBoxNombre.Text, this.textBoxDescripcion.Text);
if (mensaje == "Y")
{
this._owner.Mensaje(String.Format("La Categoría {0} ha sido AGREGADA", this.textBoxNombre.Text));
this._owner.Refrescar();
this.Close();
}
else
{
MensajeError(mensaje);
}
}
}
}
| 25.125 | 113 | 0.59204 | [
"MIT"
] | BryanGonzalezDeveloper/sistema-de-gestion-terminado | aplicacion-empresa/CapaPresentacion/FrmAgregarNuevaCategoria.cs | 1,410 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
// This file was automatically generated by the UpdateVendors tool.
//------------------------------------------------------------------------------
#pragma warning disable CS0618, CS0649, CS1574, CS1580, CS1581, CS1584, SYSLIB0011,SYSLIB0032
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using Datadog.Trace.Vendors.dnlib.IO;
namespace Datadog.Trace.Vendors.dnlib.DotNet.Emit {
/// <summary>
/// Method body reader base class
/// </summary>
internal abstract class MethodBodyReaderBase {
/// <summary>The method reader</summary>
protected DataReader reader;
/// <summary>All parameters</summary>
protected IList<Parameter> parameters;
/// <summary>All locals</summary>
protected IList<Local> locals = new List<Local>();
/// <summary>All instructions</summary>
protected IList<Instruction> instructions;
/// <summary>All exception handlers</summary>
protected IList<ExceptionHandler> exceptionHandlers = new List<ExceptionHandler>();
uint currentOffset;
/// <summary>First byte after the end of the code</summary>
protected uint codeEndOffs;
/// <summary>Start offset of method</summary>
protected uint codeStartOffs;
readonly ModuleContext context;
/// <summary>
/// Gets all parameters
/// </summary>
public IList<Parameter> Parameters => parameters;
/// <summary>
/// Gets all locals
/// </summary>
public IList<Local> Locals => locals;
/// <summary>
/// Gets all instructions
/// </summary>
public IList<Instruction> Instructions => instructions;
/// <summary>
/// Gets all exception handlers
/// </summary>
public IList<ExceptionHandler> ExceptionHandlers => exceptionHandlers;
/// <summary>
/// Constructor
/// </summary>
protected MethodBodyReaderBase() {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="context">The module context</param>
protected MethodBodyReaderBase(ModuleContext context) {
this.context = context;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">The reader</param>
protected MethodBodyReaderBase(DataReader reader)
: this(reader, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">The reader</param>
/// <param name="parameters">Method parameters or <c>null</c> if they're not known yet</param>
protected MethodBodyReaderBase(DataReader reader, IList<Parameter> parameters)
: this(reader, parameters, null) {
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="reader">The reader</param>
/// <param name="parameters">Method parameters or <c>null</c> if they're not known yet</param>
/// <param name="context">The module context</param>
protected MethodBodyReaderBase(DataReader reader, IList<Parameter> parameters, ModuleContext context) {
this.reader = reader;
this.parameters = parameters;
this.context = context;
}
/// <summary>
/// Sets new locals
/// </summary>
/// <param name="newLocals">A list of types of all locals or <c>null</c> if none</param>
protected void SetLocals(IList<TypeSig> newLocals) {
var locals = this.locals;
locals.Clear();
if (newLocals is null)
return;
int count = newLocals.Count;
for (int i = 0; i < count; i++)
locals.Add(new Local(newLocals[i]));
}
/// <summary>
/// Sets new locals
/// </summary>
/// <param name="newLocals">A list of types of all locals or <c>null</c> if none</param>
protected void SetLocals(IList<Local> newLocals) {
var locals = this.locals;
locals.Clear();
if (newLocals is null)
return;
int count = newLocals.Count;
for (int i = 0; i < count; i++)
locals.Add(new Local(newLocals[i].Type));
}
/// <summary>
/// Reads all instructions
/// </summary>
/// <param name="numInstrs">Number of instructions to read</param>
protected void ReadInstructions(int numInstrs) {
codeStartOffs = reader.Position;
codeEndOffs = reader.Length; // We don't know the end pos so use the last one
this.instructions = new List<Instruction>(numInstrs);
currentOffset = 0;
var instructions = this.instructions;
for (int i = 0; i < numInstrs && reader.Position < codeEndOffs; i++)
instructions.Add(ReadOneInstruction());
FixBranches();
}
/// <summary>
/// Reads all instructions
/// </summary>
/// <param name="codeSize">Size of code</param>
protected void ReadInstructionsNumBytes(uint codeSize) {
codeStartOffs = reader.Position;
codeEndOffs = reader.Position + codeSize;
if (codeEndOffs < codeStartOffs || codeEndOffs > reader.Length)
throw new InvalidMethodException("Invalid code size");
this.instructions = new List<Instruction>(); //TODO: Estimate number of instructions based on codeSize
currentOffset = 0;
var instructions = this.instructions;
while (reader.Position < codeEndOffs)
instructions.Add(ReadOneInstruction());
reader.Position = codeEndOffs;
FixBranches();
}
/// <summary>
/// Fixes all branch instructions so their operands are set to an <see cref="Instruction"/>
/// instead of an offset.
/// </summary>
void FixBranches() {
var instructions = this.instructions;
int count = instructions.Count;
for (int i = 0; i < count; i++) {
var instr = instructions[i];
switch (instr.OpCode.OperandType) {
case OperandType.InlineBrTarget:
case OperandType.ShortInlineBrTarget:
instr.Operand = GetInstruction((uint)instr.Operand);
break;
case OperandType.InlineSwitch:
var uintTargets = (IList<uint>)instr.Operand;
var targets = new Instruction[uintTargets.Count];
for (int j = 0; j < uintTargets.Count; j++)
targets[j] = GetInstruction(uintTargets[j]);
instr.Operand = targets;
break;
}
}
}
/// <summary>
/// Finds an instruction
/// </summary>
/// <param name="offset">Offset of instruction</param>
/// <returns>The instruction or <c>null</c> if there's no instruction at <paramref name="offset"/>.</returns>
protected Instruction GetInstruction(uint offset) {
// The instructions are sorted and all Offset fields are correct. Do a binary search.
var instructions = this.instructions;
int lo = 0, hi = instructions.Count - 1;
while (lo <= hi && hi != -1) {
int i = (lo + hi) / 2;
var instr = instructions[i];
if (instr.Offset == offset)
return instr;
if (offset < instr.Offset)
hi = i - 1;
else
lo = i + 1;
}
return null;
}
/// <summary>
/// Finds an instruction and throws if it's not present
/// </summary>
/// <param name="offset">Offset of instruction</param>
/// <returns>The instruction</returns>
/// <exception cref="InvalidOperationException">There's no instruction at
/// <paramref name="offset"/></exception>
protected Instruction GetInstructionThrow(uint offset) {
var instr = GetInstruction(offset);
if (instr is not null)
return instr;
throw new InvalidOperationException($"There's no instruction @ {offset:X4}");
}
/// <summary>
/// Reads the next instruction
/// </summary>
Instruction ReadOneInstruction() {
var instr = new Instruction();
instr.Offset = currentOffset;
instr.OpCode = ReadOpCode();
instr.Operand = ReadOperand(instr);
if (instr.OpCode.Code == Code.Switch) {
var targets = (IList<uint>)instr.Operand;
currentOffset += (uint)(instr.OpCode.Size + 4 + 4 * targets.Count);
}
else
currentOffset += (uint)instr.GetSize();
if (currentOffset < instr.Offset)
reader.Position = codeEndOffs;
return instr;
}
/// <summary>
/// Reads the next OpCode from the current position
/// </summary>
OpCode ReadOpCode() {
var op = reader.ReadByte();
if (op == 0xFE)
return OpCodes.TwoByteOpCodes[reader.ReadByte()];
if (op >= 0xF0 && op <= 0xFB && context is not null && reader.BytesLeft >= 1) {
if (context.GetExperimentalOpCode(op, reader.ReadByte()) is OpCode opCode)
return opCode;
else
reader.Position--;
}
return OpCodes.OneByteOpCodes[op];
}
/// <summary>
/// Reads the instruction operand (if any)
/// </summary>
/// <param name="instr">The instruction</param>
object ReadOperand(Instruction instr) =>
instr.OpCode.OperandType switch {
OperandType.InlineBrTarget => ReadInlineBrTarget(instr),
OperandType.InlineField => ReadInlineField(instr),
OperandType.InlineI => ReadInlineI(instr),
OperandType.InlineI8 => ReadInlineI8(instr),
OperandType.InlineMethod => ReadInlineMethod(instr),
OperandType.InlineNone => ReadInlineNone(instr),
OperandType.InlinePhi => ReadInlinePhi(instr),
OperandType.InlineR => ReadInlineR(instr),
OperandType.InlineSig => ReadInlineSig(instr),
OperandType.InlineString => ReadInlineString(instr),
OperandType.InlineSwitch => ReadInlineSwitch(instr),
OperandType.InlineTok => ReadInlineTok(instr),
OperandType.InlineType => ReadInlineType(instr),
OperandType.InlineVar => ReadInlineVar(instr),
OperandType.ShortInlineBrTarget => ReadShortInlineBrTarget(instr),
OperandType.ShortInlineI => ReadShortInlineI(instr),
OperandType.ShortInlineR => ReadShortInlineR(instr),
OperandType.ShortInlineVar => ReadShortInlineVar(instr),
_ => throw new InvalidOperationException("Invalid OpCode.OperandType"),
};
/// <summary>
/// Reads a <see cref="OperandType.InlineBrTarget"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual uint ReadInlineBrTarget(Instruction instr) => instr.Offset + (uint)instr.GetSize() + reader.ReadUInt32();
/// <summary>
/// Reads a <see cref="OperandType.InlineField"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected abstract IField ReadInlineField(Instruction instr);
/// <summary>
/// Reads a <see cref="OperandType.InlineI"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual int ReadInlineI(Instruction instr) => reader.ReadInt32();
/// <summary>
/// Reads a <see cref="OperandType.InlineI8"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual long ReadInlineI8(Instruction instr) => reader.ReadInt64();
/// <summary>
/// Reads a <see cref="OperandType.InlineMethod"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected abstract IMethod ReadInlineMethod(Instruction instr);
/// <summary>
/// Reads a <see cref="OperandType.InlineNone"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual object ReadInlineNone(Instruction instr) => null;
/// <summary>
/// Reads a <see cref="OperandType.InlinePhi"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual object ReadInlinePhi(Instruction instr) => null;
/// <summary>
/// Reads a <see cref="OperandType.InlineR"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual double ReadInlineR(Instruction instr) => reader.ReadDouble();
/// <summary>
/// Reads a <see cref="OperandType.InlineSig"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected abstract MethodSig ReadInlineSig(Instruction instr);
/// <summary>
/// Reads a <see cref="OperandType.InlineString"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected abstract string ReadInlineString(Instruction instr);
/// <summary>
/// Reads a <see cref="OperandType.InlineSwitch"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual IList<uint> ReadInlineSwitch(Instruction instr) {
var num = reader.ReadUInt32();
long offsetAfterInstr = (long)instr.Offset + (long)instr.OpCode.Size + 4L + (long)num * 4;
if (offsetAfterInstr > uint.MaxValue || codeStartOffs + offsetAfterInstr > codeEndOffs) {
reader.Position = codeEndOffs;
return Array2.Empty<uint>();
}
var targets = new uint[num];
uint offset = (uint)offsetAfterInstr;
for (int i = 0; i < targets.Length; i++)
targets[i] = offset + reader.ReadUInt32();
return targets;
}
/// <summary>
/// Reads a <see cref="OperandType.InlineTok"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected abstract ITokenOperand ReadInlineTok(Instruction instr);
/// <summary>
/// Reads a <see cref="OperandType.InlineType"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected abstract ITypeDefOrRef ReadInlineType(Instruction instr);
/// <summary>
/// Reads a <see cref="OperandType.InlineVar"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual IVariable ReadInlineVar(Instruction instr) {
if (IsArgOperandInstruction(instr))
return ReadInlineVarArg(instr);
return ReadInlineVarLocal(instr);
}
/// <summary>
/// Reads a <see cref="OperandType.InlineVar"/> (a parameter) operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual Parameter ReadInlineVarArg(Instruction instr) => GetParameter(reader.ReadUInt16());
/// <summary>
/// Reads a <see cref="OperandType.InlineVar"/> (a local) operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual Local ReadInlineVarLocal(Instruction instr) => GetLocal(reader.ReadUInt16());
/// <summary>
/// Reads a <see cref="OperandType.ShortInlineBrTarget"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual uint ReadShortInlineBrTarget(Instruction instr) => instr.Offset + (uint)instr.GetSize() + (uint)reader.ReadSByte();
/// <summary>
/// Reads a <see cref="OperandType.ShortInlineI"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual object ReadShortInlineI(Instruction instr) {
if (instr.OpCode.Code == Code.Ldc_I4_S)
return reader.ReadSByte();
return reader.ReadByte();
}
/// <summary>
/// Reads a <see cref="OperandType.ShortInlineR"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual float ReadShortInlineR(Instruction instr) => reader.ReadSingle();
/// <summary>
/// Reads a <see cref="OperandType.ShortInlineVar"/> operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual IVariable ReadShortInlineVar(Instruction instr) {
if (IsArgOperandInstruction(instr))
return ReadShortInlineVarArg(instr);
return ReadShortInlineVarLocal(instr);
}
/// <summary>
/// Reads a <see cref="OperandType.ShortInlineVar"/> (a parameter) operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual Parameter ReadShortInlineVarArg(Instruction instr) => GetParameter(reader.ReadByte());
/// <summary>
/// Reads a <see cref="OperandType.ShortInlineVar"/> (a local) operand
/// </summary>
/// <param name="instr">The current instruction</param>
/// <returns>The operand</returns>
protected virtual Local ReadShortInlineVarLocal(Instruction instr) => GetLocal(reader.ReadByte());
/// <summary>
/// Returns <c>true</c> if it's one of the ldarg/starg instructions that have an operand
/// </summary>
/// <param name="instr">The instruction to check</param>
protected static bool IsArgOperandInstruction(Instruction instr) {
switch (instr.OpCode.Code) {
case Code.Ldarg:
case Code.Ldarg_S:
case Code.Ldarga:
case Code.Ldarga_S:
case Code.Starg:
case Code.Starg_S:
return true;
default:
return false;
}
}
/// <summary>
/// Returns a parameter
/// </summary>
/// <param name="index">A parameter index</param>
/// <returns>A <see cref="Parameter"/> or <c>null</c> if <paramref name="index"/> is invalid</returns>
protected Parameter GetParameter(int index) {
var parameters = this.parameters;
if ((uint)index < (uint)parameters.Count)
return parameters[index];
return null;
}
/// <summary>
/// Returns a local
/// </summary>
/// <param name="index">A local index</param>
/// <returns>A <see cref="Local"/> or <c>null</c> if <paramref name="index"/> is invalid</returns>
protected Local GetLocal(int index) {
var locals = this.locals;
if ((uint)index < (uint)locals.Count)
return locals[index];
return null;
}
/// <summary>
/// Add an exception handler if it appears valid
/// </summary>
/// <param name="eh">The exception handler</param>
/// <returns><c>true</c> if it was added, <c>false</c> otherwise</returns>
protected bool Add(ExceptionHandler eh) {
uint tryStart = GetOffset(eh.TryStart);
uint tryEnd = GetOffset(eh.TryEnd);
if (tryEnd <= tryStart)
return false;
uint handlerStart = GetOffset(eh.HandlerStart);
uint handlerEnd = GetOffset(eh.HandlerEnd);
if (handlerEnd <= handlerStart)
return false;
if (eh.IsFilter) {
if (eh.FilterStart is null)
return false;
if (eh.FilterStart.Offset >= handlerStart)
return false;
}
if (handlerStart <= tryStart && tryStart < handlerEnd)
return false;
if (handlerStart < tryEnd && tryEnd <= handlerEnd)
return false;
if (tryStart <= handlerStart && handlerStart < tryEnd)
return false;
if (tryStart < handlerEnd && handlerEnd <= tryEnd)
return false;
// It's probably valid, so let's add it.
exceptionHandlers.Add(eh);
return true;
}
/// <summary>
/// Gets the offset of an instruction
/// </summary>
/// <param name="instr">The instruction or <c>null</c> if the offset is the first offset
/// at the end of the method.</param>
/// <returns>The instruction offset</returns>
uint GetOffset(Instruction instr) {
if (instr is not null)
return instr.Offset;
var instructions = this.instructions;
if (instructions.Count == 0)
return 0;
return instructions[instructions.Count - 1].Offset;
}
/// <summary>
/// Restores a <see cref="MethodDef"/>'s body with the parsed method instructions
/// and exception handlers
/// </summary>
/// <param name="method">The method that gets updated with the instructions, locals, and
/// exception handlers.</param>
public virtual void RestoreMethod(MethodDef method) {
var body = method.Body;
body.Variables.Clear();
var locals = this.locals;
if (locals is not null) {
int count = locals.Count;
for (int i = 0; i < count; i++)
body.Variables.Add(locals[i]);
}
body.Instructions.Clear();
var instructions = this.instructions;
if (instructions is not null) {
int count = instructions.Count;
for (int i = 0; i < count; i++)
body.Instructions.Add(instructions[i]);
}
body.ExceptionHandlers.Clear();
var exceptionHandlers = this.exceptionHandlers;
if (exceptionHandlers is not null) {
int count = exceptionHandlers.Count;
for (int i = 0; i < count; i++)
body.ExceptionHandlers.Add(exceptionHandlers[i]);
}
}
}
}
| 33.946037 | 135 | 0.672529 | [
"Apache-2.0"
] | DataDog/dd-trace-csharp | tracer/src/Datadog.Trace/Vendors/dnlib/DotNet/Emit/MethodBodyReaderBase.cs | 20,130 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Model;
using DAL;
namespace Bll.Impl
{
public class UsualScoreHistoryBll : BaseBll<UsualScoreHistory>, IUsualScoreHistoryBll
{
public UsualScoreHistoryBll(IUsualScoreHistoryDAL dal):base(dal)
{
}
}
}
| 20.666667 | 89 | 0.716129 | [
"Apache-2.0"
] | lqh-xiaoemo/HaolaoshiApi | BLL/Impl/UsualScoreHistoryBll.cs | 312 | C# |
/* MIT License
Copyright (c) 2011-2019 Markus Wendt (http://www.dodoni-project.net)
All rights reserved.
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.
Please see http://www.dodoni-project.net/ for more information concerning the Dodoni.net project.
*/
using System;
using System.Text;
using System.Numerics;
using System.Collections.Generic;
using Dodoni.MathLibrary.Basics;
using Dodoni.MathLibrary.Basics.LowLevel;
namespace Dodoni.MathLibrary.Basics.LowLevel.BuildIn
{
/// <summary>Serves as (primitive) managed code implementation of BLAS level 3 operations (fall-back solution).
/// </summary>
/// <remarks>This implementation is based on the C code of the BLAS implementation, see http://www.netlib.org/clapack/cblas. </remarks>
internal partial class BuildInLevel3BLAS
{
/// <summary>Performs a symmetric rank-2k update, i.e. C := alpha*A*B^t + alpha*B*A^t + beta*C or C := alpha*A^t*B + alpha*B^t*A + beta*C with a symmetric matrix C.
/// </summary>
/// <param name="n">The order of matrix C.</param>
/// <param name="k">The The number of columns of matrices A and B or the number .</param>
/// <param name="alpha">The scalar \alpha.</param>
/// <param name="a">The matrix A supplied column-by-column of dimension (<paramref name="lda"/>, ka), where ka is <paramref name="k"/> if to calculate C := alpha*A*B^t + alpha*B*A^t + beta*C; otherwise <paramref name="n"/>.</param>
/// <param name="b">The matrix B supplied column-by-column of dimension (<paramref name="ldb"/>, kb), where ka is at least max(1,<paramref name="n"/>) if to calculate C := alpha*A*B^t + alpha*B*A^t + beta*C; otherwise at least max(1,<paramref name="k"/>).</param>
/// <param name="beta">The scalar \beta.</param>
/// <param name="c">The symmetric matrix C supplied column-by-column of dimension (<paramref name="ldc"/>, <paramref name="n"/>).</param>
/// <param name="lda">The leading dimension of <paramref name="a"/>, must be at least max(1,<paramref name="n"/>) if to calculate C:= alpha*A*B^t+alpha*B*A^t+beta*C; max(1,<paramref name="k"/>) otherwise.</param>
/// <param name="ldb">The leading dimension of <paramref name="b"/>, must be at least max(1,<paramref name="n"/>) if to calculate C:= alpha*A*B^t+alpha*B*A^t+beta*C; max(1,<paramref name="k"/>) otherwise.</param>
/// <param name="ldc">The leading dimension of <paramref name="c"/>, must be at least max(1,<paramref name="n"/>).</param>
/// <param name="triangularMatrixType">A value whether matrix C is in its upper or lower triangular representation.</param>
/// <param name="operation">A value indicating whether to calculate C := alpha*A*B^t + alpha*B*A^t + beta*C or C := alpha*A^t*B + alpha*B^t*A + beta*C.</param>
public void dsyr2k(int n, int k, double alpha, double[] a, double[] b, double beta, double[] c, int lda, int ldb, int ldc, BLAS.TriangularMatrixType triangularMatrixType = BLAS.TriangularMatrixType.UpperTriangularMatrix, BLAS.Xsyr2kOperation operation = BLAS.Xsyr2kOperation.ATimesBTransPlusBTimesATrans)
{
if (n == 0 || ((alpha == 0.0 || k == 0) && (beta == 1.0)))
{
return; // nothing to do
}
if (operation == BLAS.Xsyr2kOperation.ATimesBTransPlusBTimesATrans) // C = \alpha *A*B' + \alpha *B*A' + C
{
if (triangularMatrixType == BLAS.TriangularMatrixType.UpperTriangularMatrix)
{
for (int j = 0; j < n; j++)
{
for (int i = 0; i <= j; i++)
{
c[i + j * ldc] = beta * c[i + j * ldc];
}
for (int ell = 0; ell < k; ell++)
{
double temp1 = alpha * b[j + ell * ldb];
double temp2 = alpha * a[j + ell * lda];
for (int i = 0; i <= j; i++)
{
c[i + j * ldc] = c[i + j * ldc] + a[i + ell * lda] * temp1 + b[i + ell * ldb] * temp2;
}
}
}
}
else
{
for (int j = 0; j < n; j++)
{
for (int i = j; i < n; i++)
{
c[i + j * ldc] = beta * c[i + j * ldc];
}
for (int ell = 0; ell < k; ell++)
{
double temp1 = alpha * b[j + ell * ldb];
double temp2 = alpha * a[j + ell * lda];
for (int i = j; i < n; i++)
{
c[i + j * ldc] = c[i + j * ldc] + a[i + ell * lda] * temp1 + b[i + ell * ldb] * temp2;
}
}
}
}
}
else // C = \alpha *A' * B + \alpha *B' * A + C
{
if (triangularMatrixType == BLAS.TriangularMatrixType.UpperTriangularMatrix)
{
for (int j = 0; j < n; j++)
{
for (int i = 0; i <= j; i++)
{
double temp1 = 0.0;
double temp2 = 0.0;
for (int ell = 0; ell < k; ell++)
{
temp1 += a[ell + i * lda] * b[ell + j * ldb];
temp2 += b[ell + i * ldb] * a[ell + j * lda];
}
c[i + j * ldc] = beta * c[i + j * ldc] + alpha * temp1 + alpha * temp2;
}
}
}
else
{
for (int j = 0; j < n; j++)
{
for (int i = j; i < n; i++)
{
double temp1 = 0.0;
double temp2 = 0.0;
for (int ell = 0; ell < k; ell++)
{
temp1 += a[ell + i * lda] * b[ell + j * ldb];
temp2 += b[ell + i * ldb] * a[ell + j * lda];
}
c[i + j * ldc] = beta * c[i + j * ldc] + alpha * temp1 + alpha * temp2;
}
}
}
}
}
}
} | 53.555556 | 312 | 0.489367 | [
"MIT"
] | dodoni/dodoni.net | BasicMathLibrary/Basics/LowLevel/BLAS/BuildIn/BuildInLevel3BLAS.dsyr2k.cs | 7,714 | C# |
using System;
using System.Collections.ObjectModel;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using Edi.Advance.BTEC.UiTests.Flows;
using Edi.Advance.BTEC.UiTests.Framework;
using Edi.Advance.Core.Common.Extentions;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Remote;
namespace Edi.Advance.BTEC.UiTests
{
[TestFixture]
public class TestBase
{
[SetUp]
public void SetUp()
{
string pathToDownloadDir = Configuration.DownloadDir;
if (!Directory.Exists(pathToDownloadDir))
Directory.CreateDirectory(pathToDownloadDir);
DesiredCapabilities capability = DesiredCapabilities.Firefox();
switch (Configuration.Browser)
{
case "Firefox":
var profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", pathToDownloadDir);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", "text/csv, application/pdf, application/zip");
//profile.EnableNativeEvents = true;
capability.SetCapability("firefox_profile", profile.ToBase64String());
SeleniumContext.WebDriver = new FirefoxDriver(capability);
break;
case "Chrome":
SeleniumContext.WebDriver =
new ChromeDriver(Path.GetFullPath(
@"..\..\..\..\..\packages\WebDriverChromeDriver.2.10\tools"));
break;
case "InternetExplorer":
SeleniumContext.WebDriver = new InternetExplorerDriver();
break;
}
SeleniumContext.WebDriver.Manage().Window.Maximize();
SeleniumContext.WebDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
[TearDown]
public void TearDown()
{
try
{
if (SeleniumContext.WebDriver != null)
{
if (TestContext.CurrentContext.Result.Status
== TestStatus.Failed)
{
string testName =
TestContext.CurrentContext.Test.Name.Split('(')[0]
+ "_" + Configuration.Browser + "_"
+ DateTime.Now.Ticks;
string pathToFailedTests = Configuration.DownloadDir
+ "\\FailedTests";
string testPath = pathToFailedTests + "\\" + testName;
if (!Directory.Exists(pathToFailedTests))
Directory.CreateDirectory(pathToFailedTests);
Screenshot screenshot =
((ITakesScreenshot) SeleniumContext.WebDriver)
.GetScreenshot();
//TestLog.EmbedImage(testName, new System.Drawing.Bitmap(new MemoryStream(screenshot.AsByteArray)));
var screenshotPath = "file://ci02/FailedTests/"+ testName + ".png";
screenshot.SaveAsFile(testPath + ".png", ImageFormat.Png);
Console.WriteLine(screenshotPath);
}
SeleniumContext.WebDriver.Quit();
}
}
catch
(InvalidOperationException)
{
}
catch
(IOException)
{
}
catch
(WebDriverException)
{
}
}
public StartFlow Start
{
get
{
var navigator = new Navigator();
navigator.Start(Configuration.SiteUrl);
return new StartFlow(navigator);
}
}
//public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
//{
// public ScreenShotRemoteWebDriver(Uri url, ICapabilities capabilities)
// : base(url, capabilities)
// {
// }
// public Screenshot GetScreenshot()
// {
// Response screenshotResponse = Execute(DriverCommand.Screenshot, null);
// string base64 = screenshotResponse.Value.ToString();
// return new Screenshot(base64);
// }
//}
}
} | 36.10687 | 130 | 0.519027 | [
"BSD-3-Clause"
] | ir0n4ikoko/MyBTEC_SeleniumTests | TestBase.cs | 4,732 | C# |
using Android.App;
using Android.Content.PM;
using Android.OS;
using Prism;
using Prism.Ioc;
namespace MyCalendar.Mobile.Droid
{
[Activity(Label = "MyCalendar.Mobile", Icon = "@mipmap/ic_launcher", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App(new AndroidInitializer()));
}
protected override void OnResume()
{
base.OnResume();
Xamarin.Essentials.Platform.OnResume();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IContainerRegistry containerRegistry)
{
// Register any platform specific implementations
}
}
}
| 34.531915 | 199 | 0.687616 | [
"MIT"
] | sunshineV9/MyCalendar | MyCalendar/MyCalendar.Mobile/MyCalendar.Mobile.Android/MainActivity.cs | 1,625 | C# |
namespace ScriptUtils.Events {
using UnityEngine;
//TODO: Rename this to SetRotationFromList and add lerp functionality
public class SetRotationFromEvent : MonoBehaviour {
[SerializeField]
private Quaternion[] m_rotations = null;
public void SetRotation(int index) {
transform.rotation = m_rotations[index];
}
}
} | 31.25 | 73 | 0.672 | [
"Apache-2.0"
] | Funbites-Game-Studio/com.funbites.unity-utils | Runtime/Transform/SetRotationFromEvent.cs | 377 | C# |
using STCM2LEditor.utils;
namespace STCM2LEditor.classes.Action.Parameters
{
internal abstract class BaseParameter : IParameter
{
public virtual uint Value1 { get; set; } = 0xff000000;
public virtual uint Value2 { get; set; } = 0xff000000;
public virtual uint Value3 { get; set; } = 0xff000000;
public virtual int Length => IParameterHelpers.HEADER_LENGTH;
public void Write(byte[] main, ref int seek)
{
ByteUtil.InsertUint32Ref(main, Value1, ref seek);
ByteUtil.InsertUint32Ref(main, Value2, ref seek);
ByteUtil.InsertUint32Ref(main, Value3, ref seek);
}
}
}
| 33.35 | 69 | 0.647676 | [
"MIT"
] | InochiPM/STCM2LEditor | Diabolik Lovers STCM2L Editor/classes/Action/Parameters/BaseParameter.cs | 669 | C# |
using System;
using System.Linq;
using RimWorld.Planet;
using RimWorld.QuestGen;
using UnityEngine;
using Verse;
namespace Cities {
public class QuestNode_GetNearbyCity : QuestNode_GetNearbySettlement {
public SlateRef<bool> visitable = true;
public SlateRef<bool> abandoned = false;
public SlateRef<bool> hasMap = false;
City RandomNearbyCity(Map homeMap, Slate slate) {
return Find.WorldObjects.Settlements
.OfType<City>()
.Where(s => s.Visitable == visitable.GetValue(slate)
&& s.Abandoned == abandoned.GetValue(slate)
&& s.HasMap == hasMap.GetValue(slate))
.RandomByDistance(homeMap?.Parent, Mathf.CeilToInt(maxTileDistance.GetValue(slate)));
}
protected override void RunInt() {
var slate = QuestGen.slate;
var home = QuestGen.slate.Get<Map>("map");
var city = RandomNearbyCity(home, slate);
QuestGen.slate.Set(storeAs.GetValue(slate), city);
if (!string.IsNullOrEmpty(storeFactionAs.GetValue(slate))) {
QuestGen.slate.Set(storeFactionAs.GetValue(slate), city.Faction);
}
if (!storeFactionLeaderAs.GetValue(slate).NullOrEmpty()) {
QuestGen.slate.Set(storeFactionLeaderAs.GetValue(slate), city.Faction.leader);
}
}
protected override bool TestRunInt(Slate slate) {
var home = slate.Get<Map>("map");
var city = RandomNearbyCity(home, slate);
if (city == null) {
return false;
}
slate.Set(storeAs.GetValue(slate), city);
if (!string.IsNullOrEmpty(storeFactionAs.GetValue(slate))) {
slate.Set(storeFactionAs.GetValue(slate), city.Faction);
}
return true;
}
}
} | 34.357143 | 101 | 0.585239 | [
"MIT"
] | Proxyer/rimworld-cities | Source/Quest/Interop/QuestNode_GetNearbyCity.cs | 1,924 | C# |
using System;
using System.Data;
using System.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore.SqlServer.Design.Internal;
using Microsoft.Extensions.DependencyInjection;
namespace Aranasoft.Cobweb.EntityFrameworkCore.Validation.Tests.Support.SqlServer {
public class SqlServerLocalDbFixture : IDisposable {
public ApplicationDbContext GetContext() {
return new ApplicationDbContext(_builder.Options);
}
private LocalDbTestingDatabase _testingDatabase;
private DbContextOptionsBuilder<ApplicationDbContext> _builder;
private SqlConnection _dbConnection;
public SqlServerLocalDbFixture() {
var serviceCollection = new ServiceCollection().AddEntityFrameworkDesignTimeServices();
new SqlServerDesignTimeServices().ConfigureDesignTimeServices(serviceCollection);
var serviceProvider = serviceCollection.BuildServiceProvider();
_testingDatabase = new LocalDbTestingDatabase();
_testingDatabase.EnsureDatabase();
var connectionString = _testingDatabase.ConnectionString;
_dbConnection = new SqlConnection(connectionString);
_dbConnection.Open();
_builder = new DbContextOptionsBuilder<ApplicationDbContext>();
_builder.UseSqlServer(_dbConnection);
_builder.UseApplicationServiceProvider(serviceProvider);
}
public virtual void Dispose() {
if (_dbConnection.State == ConnectionState.Open) _dbConnection.Close();
_dbConnection.Dispose();
_testingDatabase.Dispose();
}
}
}
| 38.977273 | 99 | 0.721283 | [
"BSD-3-Clause"
] | skykingjwc/cobweb | src/entityframeworkcore/test/entityframeworkcore2.validation.tests/Support/SqlServer/SqlServerLocalDbFixture.cs | 1,715 | C# |
namespace MultichatVisual.UI.Auth
{
partial class Auth
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TB_Name = new System.Windows.Forms.TextBox();
this.lName = new System.Windows.Forms.Label();
this.B_OK = new System.Windows.Forms.Button();
this.B_Admin = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// TB_Name
//
this.TB_Name.Location = new System.Drawing.Point(9, 32);
this.TB_Name.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.TB_Name.Name = "TB_Name";
this.TB_Name.Size = new System.Drawing.Size(194, 20);
this.TB_Name.TabIndex = 0;
//
// lName
//
this.lName.AutoSize = true;
this.lName.Location = new System.Drawing.Point(9, 7);
this.lName.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lName.Name = "lName";
this.lName.Size = new System.Drawing.Size(107, 13);
this.lName.TabIndex = 1;
this.lName.Text = "Enter your nickname:";
//
// B_OK
//
this.B_OK.Location = new System.Drawing.Point(145, 64);
this.B_OK.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.B_OK.Name = "B_OK";
this.B_OK.Size = new System.Drawing.Size(56, 23);
this.B_OK.TabIndex = 2;
this.B_OK.Text = "&OK";
this.B_OK.UseVisualStyleBackColor = true;
this.B_OK.Click += new System.EventHandler(this.B_OK_Click);
//
// B_Admin
//
this.B_Admin.Location = new System.Drawing.Point(9, 64);
this.B_Admin.Name = "B_Admin";
this.B_Admin.Size = new System.Drawing.Size(113, 23);
this.B_Admin.TabIndex = 4;
this.B_Admin.Text = "Log In As Admin";
this.B_Admin.UseVisualStyleBackColor = true;
this.B_Admin.Click += new System.EventHandler(this.B_Admin_Click);
//
// Auth
//
this.AcceptButton = this.B_OK;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(212, 92);
this.Controls.Add(this.B_Admin);
this.Controls.Add(this.B_OK);
this.Controls.Add(this.lName);
this.Controls.Add(this.TB_Name);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Auth";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Authorization";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox TB_Name;
private System.Windows.Forms.Label lName;
private System.Windows.Forms.Button B_OK;
private System.Windows.Forms.Button B_Admin;
}
} | 39.35514 | 107 | 0.554025 | [
"BSD-3-Clause"
] | OlehMarchenko95/ort_csharp_js | Other solutions/MultichatVisual/MultichatVisual/UI/Auth/Auth.Designer.cs | 4,213 | C# |
#Mon Jan 31 19:49:42 CST 2022
lib/com.ibm.ws.org.apache.cxf.cxf.rt.rs.client.3.2_1.0.60.jar=115ad4b8fca14185e85d36e73b59e227
lib/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2_1.0.60.jar=4fe9b1220343490d55e4f2c2973def12
lib/com.ibm.ws.org.apache.cxf.cxf.rt.rs.service.description.3.2_1.0.60.jar=ebe0da8df48257cc56b15d9bdd0b724b
lib/com.ibm.ws.jaxrs.2.x.config_1.0.60.jar=0ba67b6c61a7f9cb62c8de3b291f8563
lib/com.ibm.ws.jaxrs.2.0.web_1.0.60.jar=861bc9d786aec63762870804d028be15
bin/jaxrs/wadl2java=35a2ae6f7cd324be11da198b63b6478d
lib/com.ibm.ws.org.apache.cxf.cxf.tools.wadlto.jaxrs.3.2_1.0.60.jar=1e0608735ee10a0380d60ce24c464f4b
bin/jaxrs/wadl2java.bat=6876bbb49c8a6e92bed8182973f380b6
lib/com.ibm.ws.security.authorization.util_1.0.60.jar=95347e95607a25f7ff37e2da72a1ac86
lib/com.ibm.ws.jaxrs.2.0.server_1.0.60.jar=f61d994f3cc62a87c869762ced0cad2d
bin/jaxrs/tools/wadl2java.jar=7c25a99fd11513e72d7253ab113e534b
lib/com.ibm.ws.org.apache.cxf.cxf.tools.common.3.2_1.0.60.jar=6c8b6c4464a9ff2c7f51f4ccf5802e1a
lib/features/com.ibm.websphere.appserver.internal.jaxrs-2.1.mf=207c039b7159f725b112003e52c0934e
lib/com.ibm.ws.jaxrs.2.1.common_1.0.60.jar=6ae18b87f89f466b59f2e9bdc6e19b19
lib/com.ibm.ws.org.apache.cxf.cxf.rt.rs.sse.3.2_1.0.60.jar=2cfffc7d87967bf13217dfb867baab29
dev/api/ibm/com.ibm.websphere.appserver.api.jaxrs20_1.1.60.jar=ca64c83d87dffcf936e640ca4cb42f4a
lib/com.ibm.ws.jaxrs.2.0.client_1.0.60.jar=5a5e66c75c4b584948e1761ca59b705b
lib/com.ibm.ws.jaxrs.2.0.tools_1.0.60.jar=240a40105141b4f064c5dddb778dbdb8
| 76.25 | 107 | 0.846557 | [
"EPL-1.0"
] | kathrynkodama/OpenLiberty-System-Microservice-DEBUG | target/liberty/wlp/lib/features/checksums/com.ibm.websphere.appserver.internal.jaxrs-2.1.cs | 1,525 | C# |
public class GenericPoser : Poser // TypeDefIndex: 9526
{
// Fields
public GenericPoser.Map[] maps; // 0x50
// Methods
[ContextMenu] // RVA: 0x1ABCD0 Offset: 0x1ABDD1 VA: 0x1ABCD0
// RVA: 0x2B2F690 Offset: 0x2B2F791 VA: 0x2B2F690 Slot: 7
public override void AutoMapping() { }
// RVA: 0x2B2FAE0 Offset: 0x2B2FBE1 VA: 0x2B2FAE0 Slot: 8
protected override void InitiatePoser() { }
// RVA: 0x2B2FAF0 Offset: 0x2B2FBF1 VA: 0x2B2FAF0 Slot: 9
protected override void UpdatePoser() { }
// RVA: 0x2B2FDA0 Offset: 0x2B2FEA1 VA: 0x2B2FDA0 Slot: 10
protected override void FixPoserTransforms() { }
// RVA: 0x2B2FA30 Offset: 0x2B2FB31 VA: 0x2B2FA30
private void StoreDefaultState() { }
// RVA: 0x2B2F8E0 Offset: 0x2B2F9E1 VA: 0x2B2F8E0
private Transform GetTargetNamed(string tName, Transform[] array) { }
// RVA: 0x2B2FEF0 Offset: 0x2B2FFF1 VA: 0x2B2FEF0
public void .ctor() { }
}
| 28.935484 | 70 | 0.724638 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | RootMotion/FinalIK/GenericPoser.cs | 897 | C# |
#region Utf8Json License https://github.com/neuecc/Utf8Json/blob/master/LICENSE
// MIT License
//
// Copyright (c) 2017 Yoshifumi Kawai
//
// 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
using System;
using System.Runtime.CompilerServices;
using System.Text;
namespace Elasticsearch.Net
{
// JSON RFC: https://www.ietf.org/rfc/rfc4627.txt
internal struct JsonWriter
{
static readonly byte[] emptyBytes = new byte[0];
// write direct from UnsafeMemory
#if NETSTANDARD
internal
#endif
byte[] buffer;
#if NETSTANDARD
internal
#endif
int offset;
public int CurrentOffset
{
get
{
return offset;
}
}
public void AdvanceOffset(int offset)
{
this.offset += offset;
}
public static byte[] GetEncodedPropertyName(string propertyName)
{
var writer = new JsonWriter();
writer.WritePropertyName(propertyName);
return writer.ToUtf8ByteArray();
}
public static byte[] GetEncodedPropertyNameWithPrefixValueSeparator(string propertyName)
{
var writer = new JsonWriter();
writer.WriteValueSeparator();
writer.WritePropertyName(propertyName);
return writer.ToUtf8ByteArray();
}
public static byte[] GetEncodedPropertyNameWithBeginObject(string propertyName)
{
var writer = new JsonWriter();
writer.WriteBeginObject();
writer.WritePropertyName(propertyName);
return writer.ToUtf8ByteArray();
}
public static byte[] GetEncodedPropertyNameWithoutQuotation(string propertyName)
{
var writer = new JsonWriter();
writer.WriteString(propertyName); // "propname"
var buf = writer.GetBuffer();
var result = new byte[buf.Count - 2];
Buffer.BlockCopy(buf.Array, buf.Offset + 1, result, 0, result.Length); // without quotation
return result;
}
public JsonWriter(byte[] initialBuffer)
{
this.buffer = initialBuffer;
this.offset = 0;
}
public ArraySegment<byte> GetBuffer()
{
if (buffer == null) return new ArraySegment<byte>(emptyBytes, 0, 0);
return new ArraySegment<byte>(buffer, 0, offset);
}
public byte[] ToUtf8ByteArray()
{
if (buffer == null) return emptyBytes;
return BinaryUtil.FastCloneWithResize(buffer, offset);
}
public override string ToString()
{
if (buffer == null) return null;
return Encoding.UTF8.GetString(buffer, 0, offset);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void EnsureCapacity(int appendLength)
{
BinaryUtil.EnsureCapacity(ref buffer, offset, appendLength);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteRaw(byte rawValue)
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = rawValue;
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteRaw(byte[] rawValue)
{
#if NETSTANDARD
UnsafeMemory.WriteRaw(ref this, rawValue);
#else
BinaryUtil.EnsureCapacity(ref buffer, offset, rawValue.Length);
Buffer.BlockCopy(rawValue, 0, buffer, offset, rawValue.Length);
offset += rawValue.Length;
#endif
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteRawUnsafe(byte rawValue)
{
buffer[offset++] = rawValue;
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBeginArray()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)'[';
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteEndArray()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)']';
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBeginObject()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)'{';
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteEndObject()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)'}';
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteValueSeparator()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)',';
}
/// <summary>:</summary>
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteNameSeparator()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)':';
}
/// <summary>WriteString + WriteNameSeparator</summary>
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WritePropertyName(string propertyName)
{
WriteString(propertyName);
WriteNameSeparator();
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteQuotation()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 1);
buffer[offset++] = (byte)'\"';
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteNull()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 4);
buffer[offset + 0] = (byte)'n';
buffer[offset + 1] = (byte)'u';
buffer[offset + 2] = (byte)'l';
buffer[offset + 3] = (byte)'l';
offset += 4;
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteBoolean(bool value)
{
if (value)
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 4);
buffer[offset + 0] = (byte)'t';
buffer[offset + 1] = (byte)'r';
buffer[offset + 2] = (byte)'u';
buffer[offset + 3] = (byte)'e';
offset += 4;
}
else
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 5);
buffer[offset + 0] = (byte)'f';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'l';
buffer[offset + 3] = (byte)'s';
buffer[offset + 4] = (byte)'e';
offset += 5;
}
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteTrue()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 4);
buffer[offset + 0] = (byte)'t';
buffer[offset + 1] = (byte)'r';
buffer[offset + 2] = (byte)'u';
buffer[offset + 3] = (byte)'e';
offset += 4;
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteFalse()
{
BinaryUtil.EnsureCapacity(ref buffer, offset, 5);
buffer[offset + 0] = (byte)'f';
buffer[offset + 1] = (byte)'a';
buffer[offset + 2] = (byte)'l';
buffer[offset + 3] = (byte)'s';
buffer[offset + 4] = (byte)'e';
offset += 5;
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteSingle(float value)
{
offset += DoubleToStringConverter.GetBytes(ref buffer, offset, value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteDouble(double value)
{
offset += DoubleToStringConverter.GetBytes(ref buffer, offset, value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteByte(byte value)
{
WriteUInt64((ulong)value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt16(ushort value)
{
WriteUInt64((ulong)value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteUInt32(uint value)
{
WriteUInt64((ulong)value);
}
public void WriteUInt64(ulong value)
{
offset += NumberConverter.WriteUInt64(ref buffer, offset, value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteSByte(sbyte value)
{
WriteInt64((long)value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt16(short value)
{
WriteInt64((long)value);
}
#if NETSTANDARD
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
public void WriteInt32(int value)
{
WriteInt64((long)value);
}
public void WriteInt64(long value)
{
offset += NumberConverter.WriteInt64(ref buffer, offset, value);
}
public void WriteString(string value)
{
if (value == null)
{
WriteNull();
return;
}
// single-path escape
// nonescaped-ensure
var startoffset = offset;
var max = StringEncoding.UTF8.GetMaxByteCount(value.Length) + 2;
BinaryUtil.EnsureCapacity(ref buffer, startoffset, max);
var from = 0;
var to = value.Length;
buffer[offset++] = (byte)'\"';
// for JIT Optimization, for-loop i < str.Length
for (int i = 0; i < value.Length; i++)
{
byte escapeChar = default(byte);
switch (value[i])
{
case '"':
escapeChar = (byte)'"';
break;
case '\\':
escapeChar = (byte)'\\';
break;
case '\b':
escapeChar = (byte)'b';
break;
case '\f':
escapeChar = (byte)'f';
break;
case '\n':
escapeChar = (byte)'n';
break;
case '\r':
escapeChar = (byte)'r';
break;
case '\t':
escapeChar = (byte)'t';
break;
// use switch jumptable
case (char)0:
case (char)1:
case (char)2:
case (char)3:
case (char)4:
case (char)5:
case (char)6:
case (char)7:
case (char)11:
case (char)14:
case (char)15:
case (char)16:
case (char)17:
case (char)18:
case (char)19:
case (char)20:
case (char)21:
case (char)22:
case (char)23:
case (char)24:
case (char)25:
case (char)26:
case (char)27:
case (char)28:
case (char)29:
case (char)30:
case (char)31:
case (char)32:
case (char)33:
case (char)35:
case (char)36:
case (char)37:
case (char)38:
case (char)39:
case (char)40:
case (char)41:
case (char)42:
case (char)43:
case (char)44:
case (char)45:
case (char)46:
case (char)47:
case (char)48:
case (char)49:
case (char)50:
case (char)51:
case (char)52:
case (char)53:
case (char)54:
case (char)55:
case (char)56:
case (char)57:
case (char)58:
case (char)59:
case (char)60:
case (char)61:
case (char)62:
case (char)63:
case (char)64:
case (char)65:
case (char)66:
case (char)67:
case (char)68:
case (char)69:
case (char)70:
case (char)71:
case (char)72:
case (char)73:
case (char)74:
case (char)75:
case (char)76:
case (char)77:
case (char)78:
case (char)79:
case (char)80:
case (char)81:
case (char)82:
case (char)83:
case (char)84:
case (char)85:
case (char)86:
case (char)87:
case (char)88:
case (char)89:
case (char)90:
case (char)91:
default:
continue;
}
max += 2;
BinaryUtil.EnsureCapacity(ref buffer, startoffset, max); // check +escape capacity
offset += StringEncoding.UTF8.GetBytes(value, from, i - from, buffer, offset);
from = i + 1;
buffer[offset++] = (byte)'\\';
buffer[offset++] = escapeChar;
}
if (from != value.Length)
{
offset += StringEncoding.UTF8.GetBytes(value, from, value.Length - from, buffer, offset);
}
buffer[offset++] = (byte)'\"';
}
}
}
| 30.773764 | 105 | 0.503552 | [
"Apache-2.0"
] | 591094733/elasticsearch-net | src/Elasticsearch.Net/Utf8Json/JsonWriter.cs | 16,187 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Windows.Forms;
using OpenORPG.Database.DAL;
using OpenORPG.Database.Models.Quests.Rewards;
using Server.Game.Database;
using Server.Game.Database.Models.ContentTemplates;
using Server.Game.Database.Models.Quests;
namespace OpenORPG.Toolkit.Views.Content
{
public partial class QuestEditorForm : OpenORPG.Toolkit.Views.Content.BaseContentForm
{
public QuestEditorForm(QuestTemplate questTemplate)
{
InitializeComponent();
SetContentTemplate(questTemplate);
questRewardEditor1.Template = questTemplate;
questStepEditor1.Template = questTemplate;
// Do some data binding where possible
textName.DataBindings.Add("Text", ContentTemplate, "Name");
textDescription.DataBindings.Add("Text", ContentTemplate, "Description");
checkRepeat.DataBindings.Add("Checked", ContentTemplate, "CanRepeat");
}
protected override void Save()
{
var ContentTemplate = this.ContentTemplate as QuestTemplate;
// Persist rewards
ContentTemplate.Rewards = questRewardEditor1.Rewards;
ContentTemplate.QuestSteps = questStepEditor1.Steps;
using (var db = new GameDatabaseContext())
{
var repository = new QuestRepository(db);
repository.Update(ContentTemplate, ContentTemplate.Id);
}
base.Save();
}
}
}
| 30.509091 | 89 | 0.675805 | [
"MIT"
] | hilts-vaughan/OpenORPG | OpenORPG.Toolkit/Views/Content/QuestEditorForm.cs | 1,680 | C# |
using System.IO;
using I2.Loc;
namespace SolastaScoutSentinelSubclass
{
internal static class Translations
{
internal static void Load(string fromFolder)
{
var languageSourceData = LocalizationManager.Sources[0];
foreach (var path in Directory.EnumerateFiles(fromFolder, $"Translations-??.txt"))
{
var filename = Path.GetFileName(path);
var code = filename.Substring(13, 2);
var languageIndex = languageSourceData.GetLanguageIndexFromCode(code);
if (languageIndex < 0)
{
Main.Error($"language {code} not currently loaded.");
continue;
}
foreach (var line in File.ReadLines(path))
{
try
{
var splitted = line.Split(new[] { '\t', ' ' }, 2);
var term = splitted[0];
var text = splitted[1];
if (languageSourceData.ContainsTerm(term))
{
languageSourceData.RemoveTerm(term);
Main.Warning($"official game term {term} was overwritten with \"{text}\"");
}
languageSourceData.AddTerm(term).Languages[languageIndex] = text;
}
catch
{
Main.Error($"invalid translation line \"{line}\".");
}
}
}
}
}
}
| 33.265306 | 103 | 0.44908 | [
"MIT"
] | DubhHerder/SolastaScoutSentinelSubclass | SolastaScoutSentinelSubclass/Translations.cs | 1,630 | C# |
using System;
using MediaManager.Media;
namespace MediaManager.Library
{
public delegate void MetadataUpdatedEventHandler(object sender, MetadataChangedEventArgs e);
public interface IMediaItem : IContentItem
{
/// <summary>
/// Gets or sets a value indicating whether [metadata extracted].
/// </summary>
/// <value>
/// <c>true</c> if [metadata extracted]; otherwise, <c>false</c>.
/// </value>
bool IsMetadataExtracted { get; set; }
/// <summary>
/// Raised when MediaItem is updated
/// </summary>
event MetadataUpdatedEventHandler MetadataUpdated;
/// <summary>
/// The metadata for a int typed value to retrieve the information about whether the media is an advertisement.
/// </summary>
string Advertisement { get; set; }
/// <summary>
/// The metadata for the Album title.
/// </summary>
string Album { get; set; }
/// <summary>
/// The metadata for the artist for the Album of the media's original source.
/// </summary>
string AlbumArtist { get; set; }
/// <summary>
/// The metadata for a Bitmap typed value to retrieve the information about the artwork for the Album of the media's original source.
/// </summary>
object AlbumImage { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the Uri of the artwork for the Album of the media's original source.
/// </summary>
string AlbumImageUri { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the artist of the media.
/// </summary>
string Artist { get; set; }
/// <summary>
/// The metadata for a Bitmap typed value to retrieve the information about the artwork for the media.
/// </summary>
object Image { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about Uri of the artwork for the media.
/// </summary>
string ImageUri { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the author of the media.
/// </summary>
string Author { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the compilation status of the media.
/// </summary>
string Compilation { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the composer of the media.
/// </summary>
string Composer { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the date the media was created or published.
/// </summary>
DateTime Date { get; set; }
/// <summary>
/// The metadata for a int typed value to retrieve the information about the disc number for the media's original source.
/// </summary>
int DiscNumber { get; set; }
object DisplayImage { get; set; }
string DisplayImageUri { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the description that is suitable for display to the user.
/// </summary>
string DisplayDescription { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the subtitle that is suitable for display to the user.
/// </summary>
string DisplaySubtitle { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the title that is suitable for display to the user.
/// </summary>
string DisplayTitle { get; set; }
/// <summary>
/// The metadata for a int typed value to retrieve the information about the download status of the media which will be used for later offline playback.
/// </summary>
DownloadStatus DownloadStatus { get; set; }
/// <summary>
/// The metadata for a int typed value to retrieve the information about the duration of the media.
/// </summary>
TimeSpan Duration { get; set; }
/// <summary>
/// A Bundle extra.
/// </summary>
object Extras { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the genre of the media.
/// </summary>
string Genre { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the Uri of the content.
/// </summary>
string MediaUri { get; set; }
/// <summary>
/// The metadata for a int typed value to retrieve the information about the number of tracks in the media's original source.
/// </summary>
int NumTracks { get; set; }
/// <summary>
/// The metadata for a Rating2 typed value to retrieve the information about the overall rating for the media.
/// </summary>
object Rating { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the title of the media.
/// </summary>
string Title { get; set; }
/// <summary>
/// The metadata for a int typed value to retrieve the information about the track number for the media.
/// </summary>
int TrackNumber { get; set; }
/// <summary>
/// The metadata for a Rating2 typed value to retrieve the information about the user's rating for the media.
/// </summary>
object UserRating { get; set; }
/// <summary>
/// The metadata for a CharSequence or string typed value to retrieve the information about the writer of the media.
/// </summary>
string Writer { get; set; }
/// <summary>
/// The metadata for a int typed value to retrieve the information about the year the media was created or published.
/// </summary>
int Year { get; set; }
/// <summary>
/// The file extension of the media item
/// This may not be available for every item
/// </summary>
string FileExtension { get; set; }
/// <summary>
/// The name of the media file
/// </summary>
string FileName { get; set; }
/// <summary>
/// The type of the media item
/// Standard Type is Default which will try to play in the standard way.
/// </summary>
MediaType MediaType { get; set; }
/// <summary>
/// The location of the media item
/// Standard location is Default which will make a guess based on the URI.
/// </summary>
MediaLocation MediaLocation { get; set; }
/// <summary>
/// Indicates if the MediaItem is being live streamed
/// </summary>
bool IsLive { get; set; }
}
}
| 38.178571 | 168 | 0.597889 | [
"MIT"
] | AswinPG/XamarinMediaManager | MediaManager/Library/IMediaItem.cs | 7,485 | C# |
#if NETSTANDARD
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Fabric;
using ServiceStack.Configuration;
namespace ServiceStack.Webhooks.Azure.Settings
{
public class FabricAppSettings : IAppSettings
{
private readonly FabricConfigurationSettings settings;
public FabricAppSettings(StatelessServiceContext context)
: this(new FabricConfigurationSettings(context))
{
}
public FabricAppSettings(FabricConfigurationSettings settings)
{
Guard.AgainstNull(() => settings, settings);
this.settings = settings;
}
public Dictionary<string, string> GetAll()
{
return new Dictionary<string, string>();
}
public List<string> GetAllKeys()
{
return new List<string>();
}
public bool Exists(string key)
{
return GetString(key) != null;
}
public void Set<T>(string key, T value)
{
throw new NotImplementedException("FabricAppSettings.Set<T> is not implemented");
}
public string GetString(string name)
{
return settings.GetSetting(name);
}
public IList<string> GetList(string key)
{
return new List<string>();
}
public IDictionary<string, string> GetDictionary(string key)
{
return new Dictionary<string, string>();
}
public List<KeyValuePair<string, string>> GetKeyValuePairs(string key)
{
return new List<KeyValuePair<string, string>>();
}
public T Get<T>(string name)
{
return Get(name, default(T));
}
public T Get<T>(string name, T defaultValue)
{
var setting = GetString(name);
if (setting == null)
{
return defaultValue;
}
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter.IsValid(setting))
{
return (T) converter.ConvertFromString(setting);
}
return defaultValue;
}
}
}
#endif | 25.168539 | 93 | 0.565625 | [
"Apache-2.0"
] | jezzsantos/ServiceStack.Webhooks.Azure | src/Webhooks.Azure/Settings/FabricAppSettings.cs | 2,242 | C# |
using System;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[GenerationAPI]
internal struct DropdownEntry
{
public int id; // Used to determine what MaterialSlot an entry belongs to
public string displayName;
// In this case, we will handle the actual IDs later
public DropdownEntry(string displayName)
{
this.id = -1;
this.displayName = displayName;
}
internal DropdownEntry(int id, string displayName)
{
this.id = id;
this.displayName = displayName;
}
}
}
| 23.148148 | 81 | 0.6016 | [
"MIT"
] | PULSAR2105/Boids-Bug | Library/PackageCache/com.unity.shadergraph@12.1.1/Editor/Generation/Data/DropdownEntry.cs | 625 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
using Azure.Core.Http.Pipeline;
using System;
using System.Buffers;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Azure.Core.Http
{
public class PipelineOptions
{
static readonly PipelinePolicy s_default = new Default();
PipelineTransport _transport;
public ArrayPool<byte> Pool { get; set; } = ArrayPool<byte>.Shared;
public PipelineTransport Transport {
get => _transport;
set {
if (value == null) throw new ArgumentNullException(nameof(value));
_transport = value;
}
}
public PipelinePolicy TelemetryPolicy { get; set; } = s_default;
public PipelinePolicy LoggingPolicy { get; set; } = s_default;
public PipelinePolicy RetryPolicy { get; set; } = s_default;
public PipelinePolicy[] PerCallPolicies = Array.Empty<PipelinePolicy>();
public PipelinePolicy[] PerRetryPolicies = Array.Empty<PipelinePolicy>();
public string ApplicationId { get; set; }
public int PolicyCount {
get {
int numberOfPolicies = 3 + PerCallPolicies.Length + PerRetryPolicies.Length;
if (LoggingPolicy == null) numberOfPolicies--;
if (TelemetryPolicy == null) numberOfPolicies--;
if (RetryPolicy == null) numberOfPolicies--;
return numberOfPolicies;
}
}
internal static bool IsDefault(PipelinePolicy policy)
=> policy == s_default;
// TODO (pri 3): I am not happy with the design that needs a semtinel policy.
sealed class Default : PipelinePolicy
{
public override async Task ProcessAsync(HttpMessage message, ReadOnlyMemory<PipelinePolicy> pipeline)
{
Debug.Fail("default policy should be removed");
await ProcessNextAsync(pipeline, message).ConfigureAwait(false);
}
}
#region nobody wants to see these
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj) => base.Equals(obj);
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode() => base.GetHashCode();
[EditorBrowsable(EditorBrowsableState.Never)]
public override string ToString() => base.ToString();
#endregion
}
}
| 34.448718 | 114 | 0.616673 | [
"MIT"
] | maririos/azure-sdk-for-net-lab | Core/Azure.Core/Net/PipelineOptions.cs | 2,689 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DotNetScaffolder.Presentation.Forms.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 40.37037 | 151 | 0.588991 | [
"MIT"
] | tariqhamid/.NetScaffolder | Projects/Presentation/Forms/Properties/Settings.Designer.cs | 1,092 | C# |
namespace ASF.UI.WbSite.Constants.ErrorController
{
public static class ErrorControllerAction
{
public const string BadRequest = "BadRequest";
public const string Forbidden = "Forbidden";
public const string InternalServerError = "InternalServerError";
public const string MethodNotAllowed = "MethodNotAllowed";
public const string NotFound = "NotFound";
public const string Unauthorized = "Unauthorized";
}
} | 39.166667 | 72 | 0.706383 | [
"MIT"
] | MagninM/MCGA2017 | Presentation/ASF.UI.WbSite/Constants/ErrorController/ErrorControllerAction.cs | 472 | C# |
using System;
namespace Telegram.Net.Core.MTProto.Crypto
{
public class FactorizedPair
{
private readonly BigInteger p;
private readonly BigInteger q;
public FactorizedPair(BigInteger p, BigInteger q)
{
this.p = p;
this.q = q;
}
public FactorizedPair(long p, long q)
{
this.p = BigInteger.ValueOf(p);
this.q = BigInteger.ValueOf(q);
}
public BigInteger Min
{
get
{
return p.Min(q);
}
}
public BigInteger Max
{
get
{
return p.Max(q);
}
}
public override string ToString()
{
return string.Format("P: {0}, Q: {1}", p, q);
}
}
public class Factorizator
{
public static Random random = new Random();
public static long findSmallMultiplierLopatin(long what)
{
long g = 0;
for (int i = 0; i < 3; i++)
{
int q = (random.Next(128) & 15) + 17;
long x = random.Next(1000000000) + 1, y = x;
int lim = 1 << (i + 18);
for (int j = 1; j < lim; j++)
{
long a = x, b = x, c = q;
while (b != 0)
{
if ((b & 1) != 0)
{
c += a;
if (c >= what)
{
c -= what;
}
}
a += a;
if (a >= what)
{
a -= what;
}
b >>= 1;
}
x = c;
long z = x < y ? y - x : x - y;
g = GCD(z, what);
if (g != 1)
{
break;
}
if ((j & (j - 1)) == 0)
{
y = x;
}
}
if (g > 1)
{
break;
}
}
long p = what / g;
return Math.Min(p, g);
}
public static long GCD(long a, long b)
{
while (a != 0 && b != 0)
{
while ((b & 1) == 0)
{
b >>= 1;
}
while ((a & 1) == 0)
{
a >>= 1;
}
if (a > b)
{
a -= b;
}
else {
b -= a;
}
}
return b == 0 ? a : b;
}
public static FactorizedPair Factorize(BigInteger pq)
{
if (pq.BitLength < 64)
{
long pqlong = pq.LongValue;
long divisor = findSmallMultiplierLopatin(pqlong);
return new FactorizedPair(BigInteger.ValueOf(divisor), BigInteger.ValueOf(pqlong / divisor));
}
else {
// TODO: port pollard factorization
throw new InvalidOperationException("pq too long; TODO: port the pollard algo");
// logger.error("pq too long; TODO: port the pollard algo");
// return null;
}
}
}
}
| 26.201439 | 109 | 0.308622 | [
"Unlicense"
] | ctphu/Telegram.Net | Telegram.Net.Core/MTProto/Crypto/Factorizator.cs | 3,644 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VisualControl.AeroBasic;
namespace VisualControl.Test
{
public partial class formMain : AeroBasicForm
{
public formMain()
{
InitializeComponent();
}
private void formMain_Load(object sender, EventArgs e)
{
}
}
}
| 20.222222 | 63 | 0.635531 | [
"MIT"
] | ManuelSoftwareDev/AeroVisualStyle | VisualControl.Test/formMain.cs | 548 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Build;
namespace Microsoft.VisualStudio.ProjectSystem.Configuration
{
/// <summary>
/// Provides 'Configuration' project configuration dimension and values.
/// </summary>
/// <remarks>
/// The Order attribute will determine the order of the dimensions inside the configuration
/// service. We want Configuration|Platform|TargetFramework as the defaults so the values
/// start at MaxValue and get decremented for each in order for future extenders to fall
/// below these 3 providers.
/// </remarks>
[Export(typeof(IProjectConfigurationDimensionsProvider))]
[AppliesTo(ProjectCapabilities.ProjectConfigurationsDeclaredDimensions)]
[Order(DimensionProviderOrder.Configuration)]
[ConfigurationDimensionDescription(ConfigurationGeneral.ConfigurationProperty)]
internal class ConfigurationProjectConfigurationDimensionProvider : BaseProjectConfigurationDimensionProvider
{
[ImportingConstructor]
public ConfigurationProjectConfigurationDimensionProvider(IProjectAccessor projectAccessor)
: base(projectAccessor, ConfigurationGeneral.ConfigurationProperty, "Configurations", "Debug")
{
}
/// <summary>
/// Modifies the project when there's a configuration change.
/// </summary>
/// <param name="args">Information about the configuration dimension value change.</param>
/// <returns>A task for the async operation.</returns>
public override Task OnDimensionValueChangedAsync(ProjectConfigurationDimensionValueChangedEventArgs args)
{
if (StringComparers.ConfigurationDimensionNames.Equals(args.DimensionName, DimensionName))
{
if (args.Stage == ChangeEventStage.Before)
{
switch (args.Change)
{
case ConfigurationDimensionChange.Add:
return OnConfigurationAddedAsync(args.Project, args.DimensionValue);
case ConfigurationDimensionChange.Delete:
return OnConfigurationRemovedAsync(args.Project, args.DimensionValue);
case ConfigurationDimensionChange.Rename:
// Need to wait until the core rename changes happen before renaming the property.
break;
}
}
else if (args.Stage == ChangeEventStage.After)
{
// Only change that needs to be handled here is renaming configurations which needs to happen after all
// of the core changes to rename existing conditions have executed.
if (args.Change == ConfigurationDimensionChange.Rename)
{
return OnConfigurationRenamedAsync(args.Project, args.OldDimensionValue, args.DimensionValue);
}
}
}
return Task.CompletedTask;
}
/// <summary>
/// Adds a configuration to the project.
/// </summary>
/// <param name="project">Unconfigured project for which the configuration change.</param>
/// <param name="configurationName">Name of the new configuration.</param>
/// <returns>A task for the async operation.</returns>
private async Task OnConfigurationAddedAsync(UnconfiguredProject project, string configurationName)
{
string evaluatedPropertyValue = await GetPropertyValue(project).ConfigureAwait(false);
await ProjectAccessor.OpenProjectXmlForWriteAsync(project, msbuildProject =>
{
BuildUtilities.AppendPropertyValue(msbuildProject, evaluatedPropertyValue, PropertyName, configurationName);
}).ConfigureAwait(false);
}
/// <summary>
/// Removes a configuration from the project.
/// </summary>
/// <param name="project">Unconfigured project for which the configuration change.</param>
/// <param name="configurationName">Name of the deleted configuration.</param>
/// <returns>A task for the async operation.</returns>
private async Task OnConfigurationRemovedAsync(UnconfiguredProject project, string configurationName)
{
string evaluatedPropertyValue = await GetPropertyValue(project).ConfigureAwait(false);
await ProjectAccessor.OpenProjectXmlForWriteAsync(project, msbuildProject =>
{
BuildUtilities.RemovePropertyValue(msbuildProject, evaluatedPropertyValue, PropertyName, configurationName);
}).ConfigureAwait(false);
}
/// <summary>
/// Renames an existing configuration in the project.
/// </summary>
/// <param name="project">Unconfigured project for which the configuration change.</param>
/// <param name="oldName">Original name of the configuration.</param>
/// <param name="newName">New name of the configuration.</param>
/// <returns>A task for the async operation.</returns>
private async Task OnConfigurationRenamedAsync(UnconfiguredProject project, string oldName, string newName)
{
string evaluatedPropertyValue = await GetPropertyValue(project).ConfigureAwait(false);
await ProjectAccessor.OpenProjectXmlForWriteAsync(project, msbuildProject =>
{
BuildUtilities.RenamePropertyValue(msbuildProject, evaluatedPropertyValue, PropertyName, oldName, newName);
}).ConfigureAwait(false);
}
}
}
| 50.965517 | 161 | 0.658322 | [
"Apache-2.0"
] | bording/project-system | src/Microsoft.VisualStudio.ProjectSystem.Managed/ProjectSystem/Configuration/ConfigurationProjectConfigurationDimensionProvider.cs | 5,914 | C# |
using MediaPlayer.Server;
using Microsoft.AspNetCore.Mvc;
using MusicPlayer.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MusicPlayer.MediaWorker
{
public class MusicWorkerService : IMediaWorker
{
private static MusicWorkerService _instance;
public static MusicWorkerService Instance
{
get
{
if (_instance == null)
_instance = new MusicWorkerService();
return _instance;
}
}
public async Task<List<MusicAlbum>> GetAlbumsAsync()
{
HttpClient client = new HttpClient
{
BaseAddress = new Uri(AppHttpContext.AppBaseUrl)
};
// Albums
HttpResponseMessage response = await client.GetAsync("api/albums/");
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<MusicAlbum>>(jsonString);
}
// Artists
response = await client.GetAsync("api/artists/");
if (response.IsSuccessStatusCode)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<MusicAlbum>>(jsonString);
}
return null;
}
public async Task ScanMusicMedia()
{
//int year = string.IsNullOrEmpty(tfile.Tag.Album) ? DefaultValues.DEFAULT_YEAR : int.Parse(tfile.Tag.Album);
//if (!string.IsNullOrEmpty(trackAlbumTitle) && !albums.Exists(x => x.Title == trackAlbumTitle))
//{
// AddAlbum(new MusicAlbum()
// {
// Artists = string.Join(",", tfile.Tag.AlbumArtistsSort),
// Title = trackAlbumTitle,
// Year = year,
// CoverSource = "https://via.placeholder.com/111"
// });
//}
}
/// <summary>
/// ImportFromFolderAsync
/// </summary>
/// <param name="files">files</param>
/// <returns></returns>
public IEnumerable<MusicTrack> GetTracksFromFiles(IEnumerable<string> files)
{
List<MusicTrack> result = new List<MusicTrack>();
if (!files.Any())
return null;
foreach (string file in files)
{
TagLib.File tfile = TagLib.File.Create(file);
string trackAlbumTitle = tfile.Tag.Album;
if(tfile.PossiblyCorrupt)
{
Console.WriteLine("Can't import file " + file + " possible file corruption.");
continue;
}
string albumName = string.IsNullOrEmpty(trackAlbumTitle) ? (Path.GetDirectoryName(file) != "Music" ? Path.GetDirectoryName(file) : "Unknown") : trackAlbumTitle;
MusicTrack mt = new MusicTrack()
{
Id = Guid.NewGuid().ToString(),
Title = string.IsNullOrEmpty(tfile.Tag.Title) ? file : tfile.Tag.Title,
Artist = string.IsNullOrEmpty(tfile.Tag.FirstAlbumArtist) ? "Unknown" : tfile.Tag.FirstAlbumArtist,
Album = albumName,
Duration = (int)tfile.Properties.Duration.TotalSeconds,
SampleRate = tfile.Properties.AudioSampleRate,
Bitrate = tfile.Properties.AudioBitrate,
Channels = tfile.Properties.AudioChannels,
TrackNumber = tfile.Tag.Track,
DiscNumber = tfile.Tag.Disc,
FilePath = file,
CreatedDate = DateTime.Now,
ModifiedDate = DateTime.Now,
};
result.Add(mt);
}
return result.AsEnumerable();
}
private void AddAlbum(MusicAlbum musicAlbum)
{
return;
}
}
}
| 35.141667 | 176 | 0.535215 | [
"Apache-2.0"
] | adesfontaines/ReactMediaPlayer | MediaPlayer.Server/MediaWorker/MusicWorkerService.cs | 4,219 | C# |
namespace HMPPS.HealthCheck
{
public class HealthCheckConfig
{
public string MongoDbConnectionString { get; set; }
public string RedisDbConnectionString { get; set; }
public string IdamHealthCheckUrl { get; set; }
}
}
| 25.4 | 59 | 0.673228 | [
"MIT"
] | glenjamin/hmpps-hub | src/HMPPS.Monitoring/HMPPS.HealthCheck/HealthCheckConfig.cs | 254 | C# |
#pragma checksum "..\..\Case.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "8BC856CCDA1D40D5E8BC0627F4A2E33E"
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré par un outil.
// Version du runtime :4.0.30319.42000
//
// Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
// le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
using Puissance4;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Puissance4 {
/// <summary>
/// Case
/// </summary>
public partial class Case : System.Windows.Controls.Border, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/Puissance4;component/case.xaml", System.UriKind.Relative);
#line 1 "..\..\Case.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
| 38.881579 | 141 | 0.666667 | [
"MIT"
] | OwenGombas/Puissance4 | Puissance4/obj/Debug/Case.g.cs | 2,968 | C# |
using Aiursoft.DocGenerator.Attributes;
using Aiursoft.DocGenerator.Services;
using Aiursoft.DocGenerator.Tools;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Aiursoft.DocGenerator.Middlewares
{
public class APIDocGeneratorMiddleware
{
private readonly RequestDelegate _next;
private static Func<MethodInfo, Type, bool> _isAPIAction;
private static Func<MethodInfo, Type, bool> _judgeAuthorized;
private static List<object> _globalPossibleResponse;
private static DocFormat _format;
private static string _docAddress;
public APIDocGeneratorMiddleware(RequestDelegate next)
{
_next = next;
}
public static void ApplySettings(APIDocGeneratorSettings settings)
{
_isAPIAction = settings.IsAPIAction;
_judgeAuthorized = settings.JudgeAuthorized;
_globalPossibleResponse = settings.GlobalPossibleResponse;
_format = settings.Format;
_docAddress = settings.DocAddress.TrimStart('/').ToLower();
}
public async Task Invoke(HttpContext context)
{
if (_isAPIAction == null || _judgeAuthorized == null)
{
throw new ArgumentNullException();
}
if (context.Request.Path.ToString().Trim().Trim('/').ToLower() != _docAddress)
{
await _next.Invoke(context);
return;
}
switch (_format)
{
case DocFormat.Json:
context.Response.ContentType = "application/json";
break;
case DocFormat.Markdown:
context.Response.ContentType = "text/markdown";
break;
default:
throw new InvalidDataException($"Invalid format: '{_format}'!");
}
context.Response.StatusCode = 200;
var actionsMatches = new List<API>();
var possibleControllers = Assembly
.GetEntryAssembly()
?.GetTypes()
.Where(type => typeof(ControllerBase).IsAssignableFrom(type))
.ToList();
foreach (var controller in possibleControllers ?? new List<Type>())
{
if (!IsController(controller))
{
continue;
}
var controllerRoute = controller.GetCustomAttributes(typeof(RouteAttribute), true)
.Select(t => t as RouteAttribute)
.Select(t => t?.Template)
.FirstOrDefault();
foreach (var method in controller.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public))
{
if (!IsAction(method) || !_isAPIAction(method, controller))
{
continue;
}
var args = GenerateArguments(method);
var possibleResponses = GetPossibleResponses(method);
var api = new API
{
ControllerName = controller.Name,
ActionName = method.Name,
IsPost = method.CustomAttributes.Any(t => t.AttributeType == typeof(HttpPostAttribute)),
Routes = method.GetCustomAttributes(typeof(RouteAttribute), true)
.Select(t => t as RouteAttribute)
.Select(t => t?.Template)
.Select(t => $"{controllerRoute}/{t}")
.ToList(),
Arguments = args,
AuthRequired = _judgeAuthorized(method, controller),
PossibleResponses = possibleResponses
};
if (!api.Routes.Any())
{
api.Routes.Add($"{api.ControllerName.TrimController()}/{api.ActionName}");
}
actionsMatches.Add(api);
}
}
var generatedJsonDoc = JsonConvert.SerializeObject(actionsMatches);
if (_format == DocFormat.Json)
{
await context.Response.WriteAsync(generatedJsonDoc);
}
else if (_format == DocFormat.Markdown)
{
var generator = new MarkDownDocGenerator();
var groupedControllers = actionsMatches.GroupBy(t => t.ControllerName);
string finalMarkDown = string.Empty;
foreach (var controllerDoc in groupedControllers)
{
finalMarkDown += generator.GenerateMarkDownForAPI(controllerDoc, $"{context.Request.Scheme}://{context.Request.Host}") + "\r\n--------\r\n";
}
await context.Response.WriteAsync(finalMarkDown);
}
}
private string[] GetPossibleResponses(MethodInfo action)
{
var possibleList = action.GetCustomAttributes(typeof(APIProduces))
.Select(t => (t as APIProduces)?.PossibleType)
.Select(t => t.Make())
.Select(JsonConvert.SerializeObject).ToList();
possibleList.AddRange(
_globalPossibleResponse.Select(JsonConvert.SerializeObject));
return possibleList.ToArray();
}
private List<Argument> GenerateArguments(MethodInfo method)
{
var args = new List<Argument>();
foreach (var param in method.GetParameters())
{
if (param.ParameterType.IsClass && param.ParameterType != typeof(string))
{
foreach (var prop in param.ParameterType.GetProperties())
{
args.Add(new Argument
{
Name = GetArgumentName(prop, prop.Name),
Required = JudgeRequired(prop.PropertyType, prop.CustomAttributes),
Type = ConvertTypeToArgumentType(prop.PropertyType)
});
}
}
else
{
args.Add(new Argument
{
Name = GetArgumentName(param, param.Name),
Required = !param.HasDefaultValue && JudgeRequired(param.ParameterType, param.CustomAttributes),
Type = ConvertTypeToArgumentType(param.ParameterType)
});
}
}
return args;
}
private string GetArgumentName(ICustomAttributeProvider property, string defaultName)
{
var propName = defaultName;
var fromQuery = property.GetCustomAttributes(typeof(IModelNameProvider), true).FirstOrDefault();
if (fromQuery != null)
{
var queriedName = (fromQuery as IModelNameProvider)?.Name;
if (!string.IsNullOrWhiteSpace(queriedName))
{
propName = queriedName;
}
}
return propName;
}
private bool IsController(Type type)
{
return
type.Name.EndsWith("Controller") &&
type.Name != "Controller" &&
type.IsSubclassOf(typeof(ControllerBase)) &&
type.IsPublic;
}
private bool IsAction(MethodInfo method)
{
return
!method.IsAbstract &&
!method.IsVirtual &&
!method.IsStatic &&
!method.IsConstructor &&
!method.IsDefined(typeof(NonActionAttribute)) &&
!method.IsDefined(typeof(ObsoleteAttribute));
}
private ArgumentType ConvertTypeToArgumentType(Type t)
{
return
t == typeof(int) ? ArgumentType.Number :
t == typeof(int?) ? ArgumentType.Number :
t == typeof(long) ? ArgumentType.Number :
t == typeof(long?) ? ArgumentType.Number :
t == typeof(string) ? ArgumentType.Text :
t == typeof(DateTime) ? ArgumentType.Datetime :
t == typeof(DateTime?) ? ArgumentType.Datetime :
t == typeof(bool) ? ArgumentType.Boolean :
t == typeof(bool?) ? ArgumentType.Boolean :
t == typeof(string[]) ? ArgumentType.Collection :
t == typeof(List<string>) ? ArgumentType.Collection :
ArgumentType.Unknown;
}
private bool JudgeRequired(Type source, IEnumerable<CustomAttributeData> attributes)
{
if (attributes.Any(t => t.AttributeType == typeof(RequiredAttribute)))
{
return true;
}
return
source == typeof(int) || source == typeof(DateTime) || source == typeof(bool);
}
}
public class API
{
public string ControllerName { get; set; }
public string ActionName { get; set; }
public bool AuthRequired { get; set; }
public bool IsPost { get; set; }
public List<Argument> Arguments { get; set; }
public string[] PossibleResponses { get; set; }
public List<string> Routes { get; set; }
}
public class Argument
{
public string Name { get; set; }
public bool Required { get; set; }
public ArgumentType Type { get; set; }
}
public enum ArgumentType
{
Text = 0,
Number = 1,
Boolean = 2,
Datetime = 3,
Collection = 4,
Unknown = 5
}
}
| 39.262548 | 160 | 0.524929 | [
"MIT"
] | AiursoftWeb/Infrastructures | src/WebExtends/DocGenerator/Middlewares/APIDocGeneratorMiddleware.cs | 10,171 | C# |
using System;
using UnityEngine;
using UnityEngine.Events;
using Valve.VR.InteractionSystem;
namespace codepa
{
[RequireComponent(typeof(Interactable))]
public class VRJoystick : MonoBehaviour
{
[Serializable] class ValueEvent : UnityEvent<Vector2> { }
[SerializeField] Transform pivotPoint;
[Space]
[SerializeField, Range(0, 90)] float maxXAngles;
[SerializeField, Range(0, 90)] float maxYAngles;
[Space]
[SerializeField] ValueEvent OnValueChage;
private Interactable interactable;
private Vector3 originalPosition;
private Vector2 joystickValue;
public Vector2 Value
{
get
{
return joystickValue;
}
private set
{
joystickValue = value;
OnValueChage?.Invoke(joystickValue);
}
}
void Awake()
{
interactable = this.GetComponent<Interactable>();
// Save our position/rotation so that we can restore it when we detach
originalPosition = pivotPoint.transform.localPosition;
}
protected virtual void HandHoverUpdate(Hand hand)
{
GrabTypes startingGrabType = hand.GetGrabStarting();
if (interactable.attachedToHand == null && startingGrabType != GrabTypes.None)
{
hand.AttachObject(gameObject, startingGrabType, Hand.AttachmentFlags.DetachOthers);
}
}
protected virtual void HandAttachedUpdate(Hand hand)
{
// Ensure hand stay in place.
pivotPoint.transform.localPosition = originalPosition;
pivotPoint.transform.rotation = hand.transform.rotation;
// Correct hand rotation
pivotPoint.transform.Rotate(Vector3.right, 90);
// Errase vertical rotation and set it to the correct orientation.
pivotPoint.transform.localEulerAngles = new Vector3(
ClampDegrees(pivotPoint.transform.localEulerAngles.x, maxXAngles),
0,
ClampDegrees(pivotPoint.transform.localEulerAngles.z, maxYAngles));
// Update Joystick value
Value = new Vector2(DegreePrecentage(pivotPoint.transform.localEulerAngles.z, -maxYAngles), DegreePrecentage(pivotPoint.transform.localEulerAngles.x, maxXAngles));
// Apply local offset to the pivot point
pivotPoint.transform.localEulerAngles += -transform.localEulerAngles;
// Check if trigger is released
if (hand.IsGrabEnding(this.gameObject))
{
hand.DetachObject(gameObject);
}
}
/// <summary>
/// Utilite method to clamp the rotation of the stick.
/// </summary>
/// <param name="value"></param>
/// <param name="degree"></param>
/// <returns></returns>
private float ClampDegrees(float value, float degree)
{
if (value > 180) return Mathf.Clamp(value, 360 - degree, 360);
else return Mathf.Clamp(value, 0, degree);
}
/// <summary>
/// Utilitie method to check the joystick movement percentage.
/// </summary>
/// <param name="value"></param>
/// <param name="degree"></param>
/// <returns></returns>
private float DegreePrecentage(float value, float degree)
{
if (value > 180)
value = value - 360;
return value / degree;
}
/// <summary>
/// Helpful Gizmos
/// </summary>
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(pivotPoint.position, 0.01f);
DrawGizmosArrow(transform.position, transform.forward * 0.1f, 0.025f, 30);
void DrawGizmosArrow(in Vector3 pos, in Vector3 direction, float arrowHeadLength = 0.25f, float arrowHeadAngle = 20.0f)
{
Gizmos.DrawRay(pos, direction);
Gizmos.DrawRay(pos + direction, Quaternion.LookRotation(direction) * Quaternion.Euler(0, arrowHeadAngle, 0) * Vector3.back * arrowHeadLength);
Gizmos.DrawRay(pos + direction, Quaternion.LookRotation(direction) * Quaternion.Euler(0, -arrowHeadAngle, 0) * Vector3.back * arrowHeadLength);
}
}
}
} | 29.246032 | 166 | 0.715332 | [
"MIT"
] | UnTalPaco/simple-steam-vr-joystick | Assets/[VR Joystick]/VRJoystick.cs | 3,687 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
//
// MailMessageTest.cs - Unit Test Cases for System.Net.MailAddress.MailMessage
//
// Authors:
// John Luke (john.luke@gmail.com)
//
// (C) 2005, 2006 John Luke
//
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;
namespace System.Net.Mail.Tests
{
public class MailMessageTest
{
MailMessage messageWithSubjectAndBody;
MailMessage emptyMessage;
public MailMessageTest()
{
messageWithSubjectAndBody = new MailMessage("from@example.com", "to@example.com");
messageWithSubjectAndBody.Subject = "the subject";
messageWithSubjectAndBody.Body = "hello";
messageWithSubjectAndBody.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(
"<html><body>hello</body></html>",
null,
"text/html"
)
);
Attachment a = Attachment.CreateAttachmentFromString("blah blah", "AttachmentName");
messageWithSubjectAndBody.Attachments.Add(a);
emptyMessage = new MailMessage("from@example.com", "r1@t1.com, r2@t1.com");
}
[Fact]
public void TestRecipients()
{
Assert.Equal(2, emptyMessage.To.Count);
Assert.Equal("r1@t1.com", emptyMessage.To[0].Address);
Assert.Equal("r2@t1.com", emptyMessage.To[1].Address);
}
[Fact]
public void TestForNullException()
{
Assert.Throws<ArgumentNullException>(() => new MailMessage("from@example.com", null));
Assert.Throws<ArgumentNullException>(
() => new MailMessage(null, new MailAddress("to@example.com"))
);
Assert.Throws<ArgumentNullException>(
() => new MailMessage(new MailAddress("from@example.com"), null)
);
Assert.Throws<ArgumentNullException>(() => new MailMessage(null, "to@example.com"));
}
[Fact]
public void AlternateViewTest()
{
Assert.Equal(1, messageWithSubjectAndBody.AlternateViews.Count);
AlternateView av = messageWithSubjectAndBody.AlternateViews[0];
Assert.Equal(0, av.LinkedResources.Count);
Assert.Equal("text/html; charset=us-ascii", av.ContentType.ToString());
}
[Fact]
public void AttachmentTest()
{
Assert.Equal(1, messageWithSubjectAndBody.Attachments.Count);
Attachment at = messageWithSubjectAndBody.Attachments[0];
Assert.Equal("text/plain", at.ContentType.MediaType);
Assert.Equal("AttachmentName", at.ContentType.Name);
Assert.Equal("AttachmentName", at.Name);
}
[Fact]
public void BodyTest()
{
Assert.Equal("hello", messageWithSubjectAndBody.Body);
}
[Fact]
public void BodyEncodingTest()
{
Assert.Equal(messageWithSubjectAndBody.BodyEncoding, Encoding.ASCII);
}
[Fact]
public void FromTest()
{
Assert.Equal("from@example.com", messageWithSubjectAndBody.From.Address);
}
[Fact]
public void IsBodyHtmlTest()
{
Assert.False(messageWithSubjectAndBody.IsBodyHtml);
}
[Fact]
public void PriorityTest()
{
Assert.Equal(MailPriority.Normal, messageWithSubjectAndBody.Priority);
}
[Fact]
public void SubjectTest()
{
Assert.Equal("the subject", messageWithSubjectAndBody.Subject);
}
[Fact]
public void ToTest()
{
Assert.Equal(1, messageWithSubjectAndBody.To.Count);
Assert.Equal("to@example.com", messageWithSubjectAndBody.To[0].Address);
messageWithSubjectAndBody = new MailMessage();
messageWithSubjectAndBody.To.Add("to@example.com");
messageWithSubjectAndBody.To.Add("you@nowhere.com");
Assert.Equal(2, messageWithSubjectAndBody.To.Count);
Assert.Equal("to@example.com", messageWithSubjectAndBody.To[0].Address);
Assert.Equal("you@nowhere.com", messageWithSubjectAndBody.To[1].Address);
}
[Fact]
public void BodyAndEncodingTest()
{
MailMessage msg = new MailMessage("from@example.com", "to@example.com");
Assert.Null(msg.BodyEncoding);
msg.Body = "test";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.ASCII, msg.BodyEncoding);
msg.BodyEncoding = null;
msg.Body = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.BodyEncoding.CodePage);
}
[Fact]
public void SubjectAndEncodingTest()
{
MailMessage msg = new MailMessage("from@example.com", "to@example.com");
Assert.Null(msg.SubjectEncoding);
msg.Subject = "test";
Assert.Null(msg.SubjectEncoding);
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
msg.SubjectEncoding = null;
msg.Subject = "test\u3067\u3059";
Assert.Equal(Encoding.UTF8.CodePage, msg.SubjectEncoding.CodePage);
}
[Fact]
[SkipOnPlatform(
TestPlatforms.Browser,
"Not passing as internal System.Net.Mail.MailWriter stripped from build"
)]
public void SendMailMessageTest()
{
string expected =
@"X-Sender: from@example.com
X-Receiver: to@example.com
MIME-Version: 1.0
From: from@example.com
To: to@example.com
Date: DATE
Subject: the subject
Content-Type: multipart/mixed;
boundary=--boundary_1_GUID
----boundary_1_GUID
Content-Type: multipart/alternative;
boundary=--boundary_0_GUID
----boundary_0_GUID
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
hello
----boundary_0_GUID
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
<html><body>hello</body></html>
----boundary_0_GUID--
----boundary_1_GUID
Content-Type: text/plain; charset=us-ascii
Content-Disposition: attachment
Content-Transfer-Encoding: quoted-printable
blah blah
----boundary_1_GUID--
";
expected = expected.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n");
string sent = DecodeSentMailMessage(messageWithSubjectAndBody).Raw;
sent = Regex.Replace(sent, "Date:.*?\r\n", "Date: DATE\r\n");
sent = Regex.Replace(sent, @"_.{8}-.{4}-.{4}-.{4}-.{12}", "_GUID");
// name and charset can appear in different order
Assert.Contains("; name=AttachmentName", sent);
sent = sent.Replace("; name=AttachmentName", string.Empty);
Assert.Equal(expected, sent);
}
[Fact]
[SkipOnPlatform(
TestPlatforms.Browser,
"Not passing as internal System.Net.Mail.MailWriter stripped from build"
)]
public void SentSpecialLengthMailAttachment_Base64Decode_Success()
{
// The special length follows pattern: (3N - 1) * 0x4400 + 1
// This length will trigger WriteState.Padding = 2 & count = 1 (byte to write)
// The smallest number to match the pattern is 34817.
int specialLength = 34817;
string stringLength34817 = new string('A', specialLength - 1) + 'Z';
byte[] toBytes = Encoding.ASCII.GetBytes(stringLength34817);
using (var tempFile = TempFile.Create(toBytes))
{
var message = new MailMessage(
"sender@test.com",
"user1@pop.local",
"testSubject",
"testBody"
);
message.Attachments.Add(new Attachment(tempFile.Path));
string attachment = DecodeSentMailMessage(message).Attachment;
string decodedAttachment = Encoding.UTF8.GetString(
Convert.FromBase64String(attachment)
);
// Make sure last byte is not encoded twice.
Assert.Equal(specialLength, decodedAttachment.Length);
Assert.Equal("AAAAAAAAAAAAAAAAZ", decodedAttachment.Substring(34800));
}
}
private static (string Raw, string Attachment) DecodeSentMailMessage(MailMessage mail)
{
// Create a MIME message that would be sent using System.Net.Mail.
var stream = new MemoryStream();
var mailWriterType = mail.GetType().Assembly.GetType("System.Net.Mail.MailWriter");
var mailWriter = Activator.CreateInstance(
type: mailWriterType,
bindingAttr: BindingFlags.Instance | BindingFlags.NonPublic,
binder: null,
args: new object[] { stream, true }, // true to encode message for transport
culture: null,
activationAttributes: null
);
// Send the message.
mail.GetType()
.InvokeMember(
name: "Send",
invokeAttr: BindingFlags.Instance
| BindingFlags.NonPublic
| BindingFlags.InvokeMethod,
binder: null,
target: mail,
args: new object[] { mailWriter, true, true }
);
// Decode contents.
string result = Encoding.UTF8.GetString(stream.ToArray());
string attachment = result.Split(new[] { "attachment" }, StringSplitOptions.None)[1]
.Trim()
.Split('-')[0].Trim();
return (result, attachment);
}
}
}
| 35.07931 | 98 | 0.586454 | [
"MIT"
] | belav/runtime | src/libraries/System.Net.Mail/tests/Functional/MailMessageTest.cs | 10,173 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlowDesign.Model;
using FlowDesign.Model.Flow;
using System.Xml.Serialization;
using System.Xml;
namespace FlowDesign.DataAccess.Converter
{
/// <summary>
/// Konvertiert ein <see cref="FlowDesign.Model.Project"/> in einen string
/// </summary>
public class XmlConverter : IProjectConverter
{
public string ConvertObject<T>(T objectData)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (StringWriter textWriter = new Utf8StringWriter())
{
xmlSerializer.Serialize(textWriter, objectData);
return textWriter.ToString();
}
}
public T ConvertObjectBack<T>(string objectDataString)
{
byte[] byteArray = Encoding.UTF8.GetBytes(objectDataString);
MemoryStream stream = new MemoryStream(byteArray);
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stream);
}
public string[] SimpleConvertBackToString(string dataString)
{
dataString.Replace("</", "<");
char[] delimiters = new char[] { '<', '>'};
string[] splittedData = dataString.Split(delimiters);
return splittedData;
}
/// <summary>
/// Ändert das Encoding von dem Serializer von UTF-16 auf UTF-8
/// </summary>
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
}
}
| 30.428571 | 78 | 0.617958 | [
"MIT"
] | FlowDesign-HS-Esslingen/FlowDesignModelingTool | Source/FlowDesign.DataAccess/Converter/XmlConverter.cs | 1,707 | C# |
using System;
namespace NScan.Lib.Union4
{
public abstract class Union<T1, T2, T3, T4>
{
private readonly object? _value = null;
protected Union(T1 o)
{
AssertNotNull(o!);
_value = o;
}
protected Union(T2 o)
{
AssertNotNull(o!);
_value = o;
}
protected Union(T3 o)
{
AssertNotNull(o!);
_value = o;
}
protected Union(T4 o)
{
AssertNotNull(o!);
_value = o;
}
private static void AssertNotNull(object o)
{
if (o == null)
{
throw new ArgumentNullException(nameof(o));
}
}
public void Accept(IUnionVisitor<T1, T2, T3, T4> visitor)
{
switch (_value)
{
case T1 o:
visitor.Visit(o);
break;
case T2 o:
visitor.Visit(o);
break;
case T3 o:
visitor.Visit(o);
break;
case T4 o:
visitor.Visit(o);
break;
default:
throw new InvalidOperationException($"Unknown rule name {_value}");
}
}
public TReturn Accept<TReturn>(IUnionTransformingVisitor<T1, T2, T3, T4, TReturn> transformingVisitor)
{
return _value switch
{
T1 o => transformingVisitor.Visit(o),
T2 o => transformingVisitor.Visit(o),
T3 o => transformingVisitor.Visit(o),
T4 o => transformingVisitor.Visit(o),
_ => throw new InvalidOperationException($"Unknown rule name {_value}")
};
}
}
} | 21 | 106 | 0.539683 | [
"MIT"
] | pascalberger/nscan | src/NScan.Lib/Union4/Union.cs | 1,514 | C# |
// -----------------------------------------------------------------
// <copyright file="ConnectedClient.cs" company="2Dudes">
// Copyright (c) | Jose L. Nunez de Caceres et al.
// https://linkedin.com/in/nunezdecaceres
//
// All Rights Reserved.
//
// Licensed under the MIT License. See LICENSE in the project root for license information.
// </copyright>
// -----------------------------------------------------------------
namespace Fibula.Communications
{
using System;
using System.Collections.Generic;
using System.Linq;
using Fibula.Communications.Contracts;
using Fibula.Communications.Contracts.Abstractions;
using Fibula.Communications.Packets.Contracts.Abstractions;
using Fibula.Definitions.Enumerations;
using Fibula.Utilities.Validation;
using Microsoft.Extensions.Logging;
/// <summary>
/// Class that implements an <see cref="IClient"/> for any sort of connection.
/// </summary>
public class ConnectedClient : IClient
{
/// <summary>
/// Stores the set of creatures that are known to this client.
/// </summary>
private readonly IDictionary<uint, long> knownCreatures;
/// <summary>
/// A lock object to semaphore access to the <see cref="knownCreatures"/> collection.
/// </summary>
private readonly object knownCreaturesLock;
/// <summary>
/// Stores the logger in use.
/// </summary>
private readonly ILogger logger;
/// <summary>
/// Stores the id of the player tied to this client.
/// </summary>
private uint playerId;
/// <summary>
/// Initializes a new instance of the <see cref="ConnectedClient"/> class.
/// </summary>
/// <param name="logger">A reference to the logger to use.</param>
/// <param name="connection">The connection that this client uses.</param>
public ConnectedClient(ILogger<ConnectedClient> logger, IConnection connection)
{
logger.ThrowIfNull(nameof(logger));
connection.ThrowIfNull(nameof(connection));
this.logger = logger;
this.knownCreatures = new Dictionary<uint, long>();
this.knownCreaturesLock = new object();
this.Connection = connection;
this.Type = AgentType.Undefined;
this.Version = "Unknown";
}
/// <summary>
/// Gets a value indicating whether this client is idle.
/// </summary>
public bool IsIdle => this.Connection.IsOrphaned;
/// <summary>
/// Gets the connection enstablished by this client.
/// </summary>
public IConnection Connection { get; }
/// <summary>
/// Gets or sets the operating system.
/// </summary>
public AgentType Type { get; set; }
/// <summary>
/// Gets or sets the version.
/// </summary>
public string Version { get; set; }
/// <summary>
/// Gets or sets the id of the player that this client is tied to.
/// </summary>
public uint PlayerId
{
get => this.playerId;
set
{
if (this.playerId != default && this.playerId != value)
{
throw new InvalidOperationException($"{nameof(this.PlayerId)} may only be set once.");
}
this.playerId = value;
}
}
/// <summary>
/// Sends the packets supplied over the <see cref="Connection"/>.
/// </summary>
/// <param name="packetsToSend">The packets to send.</param>
public void Send(IEnumerable<IOutboundPacket> packetsToSend)
{
if (packetsToSend == null || !packetsToSend.Any())
{
return;
}
this.Connection.Send(packetsToSend, this.playerId);
}
/// <summary>
/// Checks if this player knows the given creature.
/// </summary>
/// <param name="creatureId">The id of the creature to check.</param>
/// <returns>True if the player knows the creature, false otherwise.</returns>
public bool KnowsCreatureWithId(uint creatureId)
{
lock (this.knownCreaturesLock)
{
return this.knownCreatures.ContainsKey(creatureId);
}
}
/// <summary>
/// Adds the given creature to this player's known collection.
/// </summary>
/// <param name="creatureId">The id of the creature to add to the known creatures collection.</param>
public void AddKnownCreature(uint creatureId)
{
lock (this.knownCreaturesLock)
{
this.knownCreatures[creatureId] = DateTimeOffset.UtcNow.Ticks;
this.logger.LogTrace($"Added creatureId {creatureId} to player {this.playerId} known set.");
}
}
/// <summary>
/// Chooses a creature to remove from this player's known creatures collection, if it has reached the collection size limit.
/// </summary>
/// <param name="skip">Optional. A number of creatures to skip during selection. Used for multiple creature picking.</param>
/// <returns>The id of the chosen creature, if any, or <see cref="uint.MinValue"/> if no creature was chosen.</returns>
public uint ChooseCreatureToRemoveFromKnownSet(int skip = 0)
{
lock (this.knownCreaturesLock)
{
// If the buffer is full we need to choose a victim.
if (this.knownCreatures.Count == IClient.KnownCreatureLimit)
{
return this.knownCreatures.OrderBy(kvp => kvp.Value).Skip(skip).FirstOrDefault().Key;
}
}
return uint.MinValue;
}
/// <summary>
/// Removes the given creature from this player's known collection.
/// </summary>
/// <param name="creatureId">The id of the creature to remove from the known creatures collection.</param>
public void RemoveKnownCreature(uint creatureId)
{
lock (this.knownCreaturesLock)
{
if (this.knownCreatures.ContainsKey(creatureId))
{
this.knownCreatures.Remove(creatureId);
this.logger.LogTrace($"Removed creatureId {creatureId} from player {this.playerId} known set.");
}
}
}
}
}
| 35.691892 | 132 | 0.564138 | [
"MIT"
] | Codinablack/fibula-server | src/Fibula.Communications/ConnectedClient.cs | 6,605 | C# |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _samples_aspx_sample03 : System.Web.UI.Page
{
protected void Page_Load( object sender, EventArgs e )
{
// Set the base path. This is the URL path for the FCKeditor
// installations. By default "/fckeditor/".
FCKeditor1.BasePath = this.GetBasePath();
LblPostedData.Text = "";
PostedAlertBlock.Visible = false;
PostedDataBlock.Visible = false;
if ( Page.IsPostBack )
return;
// Set the startup editor value.
FCKeditor1.Value = "<p>This is some <strong>sample text</strong>. You are using <a href=\"http://www.fckeditor.net/\">FCKeditor</a>.</p>";
}
/// <summary>
/// Automatically calculates the editor base path based on the _samples
/// directory. This is usefull only for these samples. A real application
/// should use something like this instead:
/// <code>
/// FCKeditor1.BasePath = "/fckeditor/" ; // "/fckeditor/" is the default value.
/// </code>
/// </summary>
private string GetBasePath()
{
string path = Request.Url.AbsolutePath;
int index = path.LastIndexOf( "_samples" );
return path.Remove( index, path.Length - index );
}
protected void BtnSubmit_Click( object sender, EventArgs e )
{
// For sample purposes, print the editor value at the bottom of the
// page. Note that we are encoding the value, so it will be printed as
// is, intead of rendering it.
LblPostedData.Text = HttpUtility.HtmlEncode( FCKeditor1.Value );
// Make the posted data block visible.
PostedDataBlock.Visible = true;
PostedAlertBlock.Visible = true;
}
protected void cmbToolbars_SelectedIndexChanged( object sender, EventArgs e )
{
FCKeditor1.ToolbarSet = cmbToolbars.SelectedValue;
}
}
| 30.634921 | 140 | 0.725907 | [
"MIT"
] | dsalunga/mPortal | Portal/WebSystem/FCKeditor.Net_2.6.3/_samples/aspx/2.0/sample03.aspx.cs | 1,930 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// As informações gerais sobre um assembly são controladas por
// conjunto de atributos. Altere estes valores de atributo para modificar as informações
// associadas a um assembly.
[assembly: AssemblyTitle("ListarCores")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ListarCores")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Definir ComVisible como false torna os tipos neste assembly invisíveis
// para componentes COM. Caso precise acessar um tipo neste assembly de
// COM, defina o atributo ComVisible como true nesse tipo.
[assembly: ComVisible(false)]
// O GUID a seguir será destinado à ID de typelib se este projeto for exposto para COM
[assembly: Guid("567bec24-7dd1-4805-a1e7-bff81873afc9")]
// As informações da versão de um assembly consistem nos quatro valores a seguir:
//
// Versão Principal
// Versão Secundária
// Número da Versão
// Revisão
//
// É possível especificar todos os valores ou usar como padrão os Números de Build e da Revisão
// usando o "*" como mostrado abaixo:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 95 | 0.752658 | [
"MIT"
] | Brunobagesteiro/Aula70483 | ListarCores/ListarCores/Properties/AssemblyInfo.cs | 1,436 | C# |
using System;
namespace EventDrivenThinking.EventInference.Schema
{
public static class ServiceConventions
{
static ServiceConventions()
{
GetCategoryFromNamespaceFunc = ns =>
{
var ix = ns.LastIndexOf('.');
if (ix > 0)
return ns.Substring(ix + 1);
return ns;
};
GetActionNameFromCommandFunc = commandType => commandType.Name;
}
public static Func<string,string> GetCategoryFromNamespaceFunc { get; set; }
public static Func<Type, string> GetActionNameFromCommandFunc { get; set; }
public static string GetProjectionStreamFromType(Type t)
{
return $"{GetCategoryFromNamespace(t.Namespace)}Projection";
}
public static string GetCategoryFromNamespace(string ns)
{
return GetCategoryFromNamespaceFunc(ns);
}
public static string GetActionNameFromCommand(Type commandType)
{
return GetActionNameFromCommandFunc(commandType);
}
}
} | 31.628571 | 84 | 0.598916 | [
"MIT"
] | eventmodeling/eventdriventhinking | EventDrivenThinking/EventInference/Schema/ServiceConventions.cs | 1,109 | C# |
using Abp.Authorization;
using iMasterEnglishNG.Authorization.Roles;
using iMasterEnglishNG.Authorization.Users;
namespace iMasterEnglishNG.Authorization
{
public class PermissionChecker : PermissionChecker<Role, User>
{
public PermissionChecker(UserManager userManager)
: base(userManager)
{
}
}
}
| 23.266667 | 66 | 0.716332 | [
"MIT"
] | RenJieJiang/iMasterEnglishNG | aspnet-core/src/iMasterEnglishNG.Core/Authorization/PermissionChecker.cs | 351 | C# |
namespace PiRhoSoft.CompositionEngine
{
public static class Composition
{
public const string DocumentationUrl = "http://localhost:3000/#/v10/manual/";
}
}
| 20.25 | 79 | 0.753086 | [
"MIT"
] | larsolm/Archives | Monster RPG Game Kit/MonsterRPGGameKit/Assets/PiRhoSoft Composition/Scripts/Engine/Composition.cs | 164 | C# |
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fsmb.Apis.Ua.Clients.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
/// <summary>
/// 5th Pathway information
/// </summary>
public partial class FifthPathway
{
/// <summary>
/// Initializes a new instance of the FifthPathway class.
/// </summary>
public FifthPathway() { }
/// <summary>
/// Initializes a new instance of the FifthPathway class.
/// </summary>
public FifthPathway(FifthPathwaySchool school, DateTime? startDate = default(DateTime?), DateTime? endDate = default(DateTime?), DateTime? certificateDate = default(DateTime?))
{
School = school;
StartDate = startDate;
EndDate = endDate;
CertificateDate = certificateDate;
}
/// <summary>
/// School
/// </summary>
[JsonProperty(PropertyName = "school")]
public FifthPathwaySchool School { get; set; }
/// <summary>
/// Start date
/// </summary>
[JsonProperty(PropertyName = "startDate")]
public DateTime? StartDate { get; set; }
/// <summary>
/// End date
/// </summary>
[JsonProperty(PropertyName = "endDate")]
public DateTime? EndDate { get; set; }
/// <summary>
/// Certification date
/// </summary>
[JsonProperty(PropertyName = "certificateDate")]
public DateTime? CertificateDate { get; set; }
/// <summary>
/// Validate the object. Throws ValidationException if validation fails.
/// </summary>
public virtual void Validate()
{
if (School == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "School");
}
if (this.School != null)
{
this.School.Validate();
}
}
}
}
| 30.626667 | 185 | 0.543753 | [
"MIT"
] | fsmb/ua-api | samples/csharp/UaApiSample/Generated/Models/FifthPathway.cs | 2,299 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ArduLogReader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArduLogReader")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cad7b17b-307e-4bb3-b7ff-5b94d374e5ad")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.675676 | 84 | 0.748207 | [
"MIT"
] | AliFlux/ArduLogReader | ArduLogReader/Properties/AssemblyInfo.cs | 1,397 | C# |
// <copyright file="DependenciesAdapter.cs" company="OpenTelemetry Authors">
// Copyright 2018, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using OpenTelemetry.Trace;
namespace OpenTelemetry.Adapter.Dependencies
{
/// <summary>
/// Instrumentation adaptor that automatically collect calls to Http, SQL, and Azure SDK.
/// </summary>
public class DependenciesAdapter : IDisposable
{
private readonly List<IDisposable> adapters = new List<IDisposable>();
/// <summary>
/// Initializes a new instance of the <see cref="DependenciesAdapter"/> class.
/// </summary>
/// <param name="tracerFactory">Tracer factory to get a tracer from.</param>
/// <param name="httpOptions">Http configuration options.</param>
/// <param name="sqlOptions">Sql configuration options.</param>
public DependenciesAdapter(TracerFactoryBase tracerFactory, HttpClientAdapterOptions httpOptions = null, SqlClientAdapterOptions sqlOptions = null)
{
if (tracerFactory == null)
{
throw new ArgumentNullException(nameof(tracerFactory));
}
var assemblyVersion = typeof(DependenciesAdapter).Assembly.GetName().Version;
var httpClientListener = new HttpClientAdapter(tracerFactory.GetTracer(nameof(HttpClientAdapter), "semver:" + assemblyVersion), httpOptions ?? new HttpClientAdapterOptions());
var httpWebRequestAdapter = new HttpWebRequestAdapter(tracerFactory.GetTracer(nameof(HttpWebRequestAdapter), "semver:" + assemblyVersion), httpOptions ?? new HttpClientAdapterOptions());
var azureClientsListener = new AzureClientsAdapter(tracerFactory.GetTracer(nameof(AzureClientsAdapter), "semver:" + assemblyVersion));
var azurePipelineListener = new AzurePipelineAdapter(tracerFactory.GetTracer(nameof(AzurePipelineAdapter), "semver:" + assemblyVersion));
var sqlClientListener = new SqlClientAdapter(tracerFactory.GetTracer(nameof(AzurePipelineAdapter), "semver:" + assemblyVersion), sqlOptions ?? new SqlClientAdapterOptions());
this.adapters.Add(httpClientListener);
this.adapters.Add(httpWebRequestAdapter);
this.adapters.Add(azureClientsListener);
this.adapters.Add(azurePipelineListener);
this.adapters.Add(sqlClientListener);
}
/// <inheritdoc />
public void Dispose()
{
foreach (var adapter in this.adapters)
{
adapter.Dispose();
}
}
}
}
| 47.58209 | 198 | 0.693538 | [
"Apache-2.0"
] | AndyPook/opentelemetry-dotnet | src/OpenTelemetry.Adapter.Dependencies/DependenciesAdapter.cs | 3,190 | C# |
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
namespace NConfig
{
/// <summary>
/// ConfigurationCollection having typed indexer and enumerator.
/// </summary>
/// <typeparam name="T">Type of the configuration element having a key.</typeparam>
public abstract class MergeableConfigurationCollection<T> : ConfigurationElementCollection,
IMergeableConfigurationCollection, IEnumerable<T>
where T : ConfigurationElement, new()
{
/// <summary>
/// As we know the type of the element, we can create it.
/// </summary>
protected override ConfigurationElement CreateNewElement()
{
return new T();
}
/// <summary>
/// Access to the i-th element type-safe.
/// </summary>
public T this[int index]
{
get { return BaseGet(index) as T; }
}
/// <summary>
/// Type-safe getter for the element with the key.
/// </summary>
public T GetElement(string key)
{
return BaseGet(key) as T;
}
/// <summary>
/// Enumerates all elements of the collection.
/// Please note that the sort order is not defined.
/// </summary>
public new IEnumerator<T> GetEnumerator()
{
return (
from i in Enumerable.Range(0, Count)
select this[i]).GetEnumerator();
}
/// <summary>
/// if T simply returns the value, no duplicates will be added to collection
/// </summary>
protected override object GetElementKey(ConfigurationElement element)
{
var keyElements = element.ElementInformation.Properties
.Cast<PropertyInformation>()
.Where(x => x.IsKey)
.ToList();
if (!keyElements.Any())
{
// no property is set as IsKey
throw new ConfigurationErrorsException(
string.Format("Element type {0} in collection {1} does not have IsKey property specified: {2}",
element.GetType(), GetType(), element));
}
if (keyElements.Count == 1)
{
return keyElements.First().Value;
}
// For several IsKey = true properties: use an aggregated key so that they are compared together
return string.Join(":--:", keyElements.Select(x => x.Value.ToString()).ToArray() );
}
void IMergeableConfigurationCollection.Add(ConfigurationElement element)
{
BaseAdd(element, false);
}
bool IMergeableConfigurationCollection.IsRemoved(ConfigurationElement item)
{
return BaseIsRemoved(GetElementKey(item));
}
object IMergeableConfigurationCollection.GetElementKeyForMerge(ConfigurationElement item)
{
return GetElementKey(item);
}
}
}
| 33.351064 | 116 | 0.54992 | [
"MIT"
] | Yegoroff/NConfig | NConfig/MergeableConfigurationCollection.cs | 3,135 | C# |
using LBH.AdultSocialCare.Transactions.Api.V1.AppConstants.Enums;
using LBH.AdultSocialCare.Transactions.Api.V1.Exceptions.CustomExceptions;
using LBH.AdultSocialCare.Transactions.Api.V1.Gateways.PayRunGateways;
using LBH.AdultSocialCare.Transactions.Api.V1.UseCase.PayRunUseCases.Interfaces;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace LBH.AdultSocialCare.Transactions.Api.V1.UseCase.PayRunUseCases.Concrete
{
public class ChangePayRunStatusUseCase : IChangePayRunStatusUseCase
{
private readonly IPayRunGateway _payRunGateway;
public ChangePayRunStatusUseCase(IPayRunGateway payRunGateway)
{
_payRunGateway = payRunGateway;
}
public async Task<bool> SubmitPayRunForApproval(Guid payRunId)
{
// Pay run must be in draft to be submitted for approval
var payRun = await _payRunGateway.CheckPayRunExists(payRunId).ConfigureAwait(false);
if (payRun.PayRunStatusId != (int) PayRunStatusesEnum.Draft)
{
throw new ApiException(
$"Pay run with id {payRunId} is not in draft", StatusCodes.Status422UnprocessableEntity);
}
var validInvoiceIds = new List<int>() { (int) InvoiceStatusEnum.Held, (int) InvoiceStatusEnum.Accepted };
var validInvoiceStatuses = await _payRunGateway.CheckAllInvoicesInPayRunInStatusList(payRunId, validInvoiceIds).ConfigureAwait(false);
if (!validInvoiceStatuses)
{
throw new ApiException(
$"All invoices in pay run must be held or accepted before submitting for approval. Please check and try again");
}
return await _payRunGateway.ChangePayRunStatus(payRunId, (int) PayRunStatusesEnum.SubmittedForApproval)
.ConfigureAwait(false);
}
public async Task<bool> KickBackPayRunToDraft(Guid payRunId)
{
// Check if pay run is in submitted for approval stage. That is when it can be kicked back to draft
var payRun = await _payRunGateway.CheckPayRunExists(payRunId).ConfigureAwait(false);
return payRun.PayRunStatusId switch
{
(int) PayRunStatusesEnum.Draft => throw new ApiException(
$"Pay run with id {payRunId} is already in draft", StatusCodes.Status422UnprocessableEntity),
(int) PayRunStatusesEnum.Approved => throw new ApiException(
$"Pay run with id {payRunId} is already approved and cannot be send back to draft",
StatusCodes.Status422UnprocessableEntity),
_ => await _payRunGateway.ChangePayRunStatus(payRunId, (int) PayRunStatusesEnum.Draft)
.ConfigureAwait(false)
};
}
}
}
| 45.265625 | 146 | 0.675181 | [
"MIT"
] | LBHackney-IT/lbh-adult-social-care-transactions-api | LBH.AdultSocialCare.Transactions.Api/V1/UseCase/PayRunUseCases/Concrete/ChangePayRunStatusUseCase.cs | 2,897 | C# |
using System.Collections.Generic;
using mesoBoard.Data;
namespace mesoBoard.Web.Areas.Admin.Models
{
public class PluginConfigsViewModel
{
public IEnumerable<PluginConfig> Configs { get; set; }
public string[] ConfigGroups { get; set; }
}
} | 24.545455 | 62 | 0.7 | [
"BSD-3-Clause"
] | craigmoliver/mesoBoard | mesoBoard.Web/Areas/Admin/Models/Configs/PluginConfigsViewModel.cs | 272 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.Mwaa.Inputs
{
public sealed class EnvironmentLoggingConfigurationWebserverLogsArgs : Pulumi.ResourceArgs
{
[Input("cloudWatchLogGroupArn")]
public Input<string>? CloudWatchLogGroupArn { get; set; }
/// <summary>
/// Enabling or disabling the collection of logs
/// </summary>
[Input("enabled")]
public Input<bool>? Enabled { get; set; }
/// <summary>
/// Logging level. Valid values: `CRITICAL`, `ERROR`, `WARNING`, `INFO`, `DEBUG`. Will be `INFO` by default.
/// </summary>
[Input("logLevel")]
public Input<string>? LogLevel { get; set; }
public EnvironmentLoggingConfigurationWebserverLogsArgs()
{
}
}
}
| 30.8 | 116 | 0.642857 | [
"ECL-2.0",
"Apache-2.0"
] | RafalSumislawski/pulumi-aws | sdk/dotnet/Mwaa/Inputs/EnvironmentLoggingConfigurationWebserverLogsArgs.cs | 1,078 | C# |
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using static Microsoft.Azure.PowerShell.Cmdlets.Datadog.Runtime.PowerShell.MarkdownTypesExtensions;
using static Microsoft.Azure.PowerShell.Cmdlets.Datadog.Runtime.PowerShell.PsProxyOutputExtensions;
namespace Microsoft.Azure.PowerShell.Cmdlets.Datadog.Runtime.PowerShell
{
internal static class MarkdownRenderer
{
public static void WriteMarkdowns(IEnumerable<VariantGroup> variantGroups, PsModuleHelpInfo moduleHelpInfo, string docsFolder, string examplesFolder)
{
Directory.CreateDirectory(docsFolder);
var markdownInfos = variantGroups.Where(vg => !vg.IsInternal).Select(vg => new MarkdownHelpInfo(vg, examplesFolder)).OrderBy(mhi => mhi.CmdletName).ToArray();
foreach (var markdownInfo in markdownInfos)
{
var sb = new StringBuilder();
sb.Append(markdownInfo.ToHelpMetadataOutput());
sb.Append($"# {markdownInfo.CmdletName}{Environment.NewLine}{Environment.NewLine}");
sb.Append($"## SYNOPSIS{Environment.NewLine}{markdownInfo.Synopsis.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}");
sb.Append($"## SYNTAX{Environment.NewLine}{Environment.NewLine}");
var hasMultipleParameterSets = markdownInfo.SyntaxInfos.Length > 1;
foreach (var syntaxInfo in markdownInfo.SyntaxInfos)
{
sb.Append(syntaxInfo.ToHelpSyntaxOutput(hasMultipleParameterSets));
}
sb.Append($"## DESCRIPTION{Environment.NewLine}{markdownInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}");
sb.Append($"## EXAMPLES{Environment.NewLine}{Environment.NewLine}");
foreach (var exampleInfo in markdownInfo.Examples)
{
sb.Append(exampleInfo.ToHelpExampleOutput());
}
sb.Append($"## PARAMETERS{Environment.NewLine}{Environment.NewLine}");
foreach (var parameter in markdownInfo.Parameters)
{
sb.Append(parameter.ToHelpParameterOutput());
}
if (markdownInfo.SupportsShouldProcess)
{
foreach (var parameter in SupportsShouldProcessParameters)
{
sb.Append(parameter.ToHelpParameterOutput());
}
}
if (markdownInfo.SupportsPaging)
{
foreach (var parameter in SupportsPagingParameters)
{
sb.Append(parameter.ToHelpParameterOutput());
}
}
sb.Append($"### CommonParameters{Environment.NewLine}This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).{Environment.NewLine}{Environment.NewLine}");
sb.Append($"## INPUTS{Environment.NewLine}{Environment.NewLine}");
foreach (var input in markdownInfo.Inputs)
{
sb.Append($"### {input}{Environment.NewLine}{Environment.NewLine}");
}
sb.Append($"## OUTPUTS{Environment.NewLine}{Environment.NewLine}");
foreach (var output in markdownInfo.Outputs)
{
sb.Append($"### {output}{Environment.NewLine}{Environment.NewLine}");
}
sb.Append($"## NOTES{Environment.NewLine}{Environment.NewLine}");
sb.Append($"ALIASES{Environment.NewLine}{Environment.NewLine}");
foreach (var alias in markdownInfo.Aliases)
{
sb.Append($"{alias}{Environment.NewLine}{Environment.NewLine}");
}
if (markdownInfo.ComplexInterfaceInfos.Any())
{
sb.Append($"{ComplexParameterHeader}{Environment.NewLine}");
}
foreach (var complexInterfaceInfo in markdownInfo.ComplexInterfaceInfos)
{
sb.Append($"{complexInterfaceInfo.ToNoteOutput(includeDashes: true, includeBackticks: true)}{Environment.NewLine}{Environment.NewLine}");
}
sb.Append($"## RELATED LINKS{Environment.NewLine}{Environment.NewLine}");
foreach (var relatedLink in markdownInfo.RelatedLinks)
{
sb.Append($"{relatedLink}{Environment.NewLine}{Environment.NewLine}");
}
File.WriteAllText(Path.Combine(docsFolder, $"{markdownInfo.CmdletName}.md"), sb.ToString());
}
WriteModulePage(moduleHelpInfo, markdownInfos, docsFolder);
}
private static void WriteModulePage(PsModuleHelpInfo moduleInfo, MarkdownHelpInfo[] markdownInfos, string docsFolder)
{
var sb = new StringBuilder();
sb.Append(moduleInfo.ToModulePageMetadataOutput());
sb.Append($"# {moduleInfo.Name} Module{Environment.NewLine}");
sb.Append($"## Description{Environment.NewLine}{moduleInfo.Description.ToDescriptionFormat()}{Environment.NewLine}{Environment.NewLine}");
sb.Append($"## {moduleInfo.Name} Cmdlets{Environment.NewLine}");
foreach (var markdownInfo in markdownInfos)
{
sb.Append(markdownInfo.ToModulePageCmdletOutput());
}
File.WriteAllText(Path.Combine(docsFolder, $"{moduleInfo.Name}.md"), sb.ToString());
}
}
}
| 52.45082 | 430 | 0.582435 | [
"MIT"
] | Agazoth/azure-powershell | src/Datadog/generated/runtime/BuildTime/MarkdownRenderer.cs | 6,278 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class PersonnelSystemController : DeviceSystemBaseController
{
public PersonnelSystemController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 22.866667 | 112 | 0.749271 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/PersonnelSystemController.cs | 329 | C# |
//Copyright 2017 Spin Services Limited
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using log4net;
using SportingSolutions.Udapi.Sdk.Interfaces;
using SS.Integration.Adapter.Actors.Messages;
using SS.Integration.Adapter.Helpers;
using SS.Integration.Adapter.Interface;
namespace SS.Integration.Adapter.Actors
{
/// <summary>
/// This class has the responibility to process all the sports in parallel using different instances/threads managed by AKKA Router
/// A single sport is processed on a separate thread by a single instance acting like a child actor.
/// The child actor is responsible for triggering the creation/processing of that sport's resources stream listeners to the StreamListenerManagerActor
/// </summary>
public class SportProcessorRouterActor : ReceiveActor
{
#region Constants
public const string ActorName = nameof(SportProcessorRouterActor);
public const string Path = "/user/" + ActorName;
#endregion
#region Fields
private readonly ILog _logger = LogManager.GetLogger(typeof(SportProcessorRouterActor));
private readonly IServiceFacade _serviceFacade;
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="serviceFacade"></param>
public SportProcessorRouterActor(IServiceFacade serviceFacade)
{
_serviceFacade = serviceFacade ?? throw new ArgumentNullException(nameof(serviceFacade));
Receive<ProcessSportMsg>(o => ProcessSportsMsgHandler(o));
}
#endregion
#region Protected methods
protected override void PreRestart(Exception reason, object message)
{
_logger.Error(
$"Actor restart reason exception={reason?.ToString() ?? "null"}." +
(message != null
? $" last processing messageType={message.GetType().Name}"
: ""));
base.PreRestart(reason, message);
}
#endregion
#region Private methods
private void ProcessSportsMsgHandler(ProcessSportMsg msg)
{
var sports = _serviceFacade.GetSports();
if (sports == null)
{
var errorMsg = "ServiceFacade GetSports responce=NULL probably credentials problem";
_logger.Error(errorMsg);
throw new Exception(errorMsg);
}
_logger.Debug($"ServiceFacade GetSports returned SportsCount={sports?.Count()} listOfSports={$"\"{string.Join(", ", sports.Select(_=> _.Name))}\"" }");
List <IResourceFacade> resources = new List<IResourceFacade>();
foreach (var sport in sports)
{
var _res = _serviceFacade.GetResources(sport.Name);
if(_res != null && _res.Any())
_logger.Info($"ProcessSportMsgHandler {GetListOfFixtures(_res, sport)}");
if (ValidateResources(_res, sport.Name))
{
resources.AddRange(_res);
}
}
if (resources.Count > 1)
{
try
{
resources.SortByMatchStatus();
}
catch (System.ArgumentException argEx)
{
_logger.Warn($"Can't sort resources. Fixtures list: {GetListOfFixtures(resources)}. {argEx}");
}
}
_logger.Info($"ProcessSportsMsgHandler resourcesCount={resources.Count}");
var streamListenerManagerActor = Context.System.ActorSelection(StreamListenerManagerActor.Path);
foreach (var resource in resources)
{
streamListenerManagerActor.Tell(new ProcessResourceMsg { Resource = resource }, Self);
}
}
private string GetListOfFixtures(List<IResourceFacade> _res, IFeature sport = null)
{
string result = string.Empty;
var sportName = sport != null ? sport.Name : "Any";
try
{
var list = _res.Select(_ => $"fixtureId={_?.Id} sport={_?.Sport} name=\"{_?.Name}\" matchStatus={_?.MatchStatus} startTime={_?.Content?.StartTime}");
result = $"sport ={sportName} count ={ list.Count()} resources =\"{string.Join(" , ", list)} \"";
}
catch(Exception)
{
_logger.Warn("ProcessSportsMsgHandler can't read fixtures info");
}
return result;
}
private bool ValidateResources(IList<IResourceFacade> resources, string sport)
{
var valid = true;
if (resources == null)
{
_logger.Warn($"Cannot find sport={sport} in UDAPI....");
valid = false;
}
else if (resources.Count == 0)
{
valid = false;
}
return valid;
}
#endregion
}
}
| 34.814815 | 165 | 0.594326 | [
"Apache-2.0"
] | sportingsolutions/SS.Integration.Adapter | SS.Integration.Adapter/Actors/SportProcessorRouterActor.cs | 5,642 | C# |
/*
* Developer: Ramtin Jokar [ Ramtinak@live.com ] [ My Telegram Account: https://t.me/ramtinak ]
*
* Github source: https://github.com/ramtinak/InstagramApiSharp
* Nuget package: https://www.nuget.org/packages/InstagramApiSharp
*
* IRANIAN DEVELOPERS
*/
using System;
using System.Collections.Generic;
using InstagramApiSharp.Classes.ResponseWrappers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace InstagramApiSharp.Converters.Json
{
internal class InstaUserPresenceContainerDataConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(InstaUserPresenceContainerResponse);
}
public override object ReadJson(JsonReader reader,
Type objectType,
object existingValue,
JsonSerializer serializer)
{
var token = JToken.Load(reader);
var presence = token.ToObject<InstaUserPresenceContainerResponse>();
var userPresenceRoot = token?.SelectToken("user_presence");
var extras = userPresenceRoot.ToObject<InstaExtraResponse>();
try
{
foreach (var item in extras.Extras)
{
try
{
var p = item.Value.ToObject<InstaUserPresenceResponse>();
p.Pk = long.Parse(item.Key);
presence.Items.Add(p);
}
catch { }
}
}
catch { }
return presence;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
}
| 30.896552 | 98 | 0.585379 | [
"MIT"
] | AMP-VTV/InstagramApiSharp | src/InstagramApiSharp/Converters/Json/InstaUserPresenceContainerDataConverter.cs | 1,794 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.