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 System;
using Bonobo.Git.Server.Data.Update;
using Bonobo.Git.Server.Security;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Bonobo.Git.Server.Test
{
[TestClass]
public class PasswordServiceTest
{
private const String DefaultAdminUserName = "admin";
private const String DefaultAdminPassword = "admin";
private const String DefaultAdminHash =
"0CC52C6751CC92916C138D8D714F003486BF8516933815DFC11D6C3E36894BFA" +
"044F97651E1F3EEBA26CDA928FB32DE0869F6ACFB787D5A33DACBA76D34473A3";
private const String Md5DefaultAdminHash = "21232F297A57A5A743894A0E4A801FC3";
[TestMethod]
public void AdminDefaultPasswordIsSaltedSha512Hash()
{
Action<string, string> updateHook = (username, password) =>
{
Assert.Fail("Generating password hash should not update the related db entry.");
};
var passwordService = new PasswordService(updateHook);
var saltedHash = passwordService.GetSaltedHash(DefaultAdminPassword, DefaultAdminUserName);
Assert.AreEqual(DefaultAdminHash, saltedHash);
}
[TestMethod]
public void InsertDefaultDataCommandUsesSaltedSha512Hash()
{
var script = new Bonobo.Git.Server.Data.Update.InsertDefaultData();
AssertSaltedSha512HashIsUsed(script);
}
[TestMethod]
public void SqlServerInsertDefaultDataCommandUsesSaltedSha512Hash()
{
var script = new Bonobo.Git.Server.Data.Update.SqlServer.InsertDefaultData();
AssertSaltedSha512HashIsUsed(script);
}
// ReSharper disable UnusedParameter.Global
public void AssertSaltedSha512HashIsUsed(IUpdateScript updateScript)
// ReSharper restore UnusedParameter.Global
{
Assert.IsTrue(updateScript.Command.Contains(DefaultAdminHash));
}
[TestMethod]
public void CorrectSha512PasswordsWontBeUpgraded()
{
Action<string, string> updateHook = (username, password) =>
{
Assert.Fail("Sha512 password does not need to be upgraded.");
};
var passwordService = new PasswordService(updateHook);
bool isCorrect = passwordService
.ComparePassword(DefaultAdminPassword, DefaultAdminUserName, DefaultAdminHash);
Assert.IsTrue(isCorrect);
}
[TestMethod]
public void WrongSha512PasswordsWontBeUpgraded()
{
Action<string, string> updateHook = (username, password) =>
{
Assert.Fail("Wrong sha512 password must not be upgraded.");
};
var passwordService = new PasswordService(updateHook);
bool isCorrect = passwordService
.ComparePassword("1" + DefaultAdminPassword, DefaultAdminUserName, DefaultAdminHash);
Assert.IsFalse(isCorrect);
}
[TestMethod]
public void CorrectMd5PasswordsWillBeUpgraded()
{
int correctUpgradeHookCalls = 0;
var username = DefaultAdminUserName;
var password = DefaultAdminPassword;
Action<string, string> updateHook = (updateUsername, updatePassword) =>
{
Assert.AreEqual(username, updateUsername);
Assert.AreEqual(password, updatePassword);
++correctUpgradeHookCalls;
};
var passwordService = new PasswordService(updateHook);
bool isCorrect = passwordService
.ComparePassword(password, username, Md5DefaultAdminHash);
Assert.IsTrue(isCorrect);
Assert.AreEqual(1, correctUpgradeHookCalls, "Correct md5 password should be upgraded exactly once.");
}
[TestMethod]
public void WrongMd5PasswordsWontBeUpgraded()
{
Action<string, string> updateHook = (s, s1) =>
{
Assert.Fail("Wrong md5 password must not be upgraded.");
};
var passwordService = new PasswordService(updateHook);
bool isCorrect = passwordService
.ComparePassword("1" + DefaultAdminPassword, DefaultAdminUserName, Md5DefaultAdminHash);
Assert.IsFalse(isCorrect);
}
}
}
| 39.531532 | 113 | 0.635369 | [
"MIT"
] | AAndharia/Bonobo-Git-Server | Bonobo.Git.Server.Test/PasswordServiceTest.cs | 4,390 | C# |
using System;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
using Bogus;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Resources;
using JsonApiDotNetCore.Serialization.Client.Internal;
using JsonApiDotNetCore.Serialization.Objects;
using JsonApiDotNetCoreExample;
using JsonApiDotNetCoreExample.Data;
using JsonApiDotNetCoreExample.Models;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Xunit;
namespace JsonApiDotNetCoreExampleTests.Acceptance
{
public sealed class KebabCaseFormatterTests : IClassFixture<IntegrationTestContext<KebabCaseStartup, AppDbContext>>
{
private readonly IntegrationTestContext<KebabCaseStartup, AppDbContext> _testContext;
private readonly Faker<KebabCasedModel> _faker;
public KebabCaseFormatterTests(IntegrationTestContext<KebabCaseStartup, AppDbContext> testContext)
{
_testContext = testContext;
_faker = new Faker<KebabCasedModel>()
.RuleFor(m => m.CompoundAttr, f => f.Lorem.Sentence());
testContext.ConfigureServicesAfterStartup(services =>
{
var part = new AssemblyPart(typeof(EmptyStartup).Assembly);
services.AddMvcCore().ConfigureApplicationPartManager(apm => apm.ApplicationParts.Add(part));
});
}
[Fact]
public async Task KebabCaseFormatter_GetAll_IsReturned()
{
// Arrange
var model = _faker.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<KebabCasedModel>();
dbContext.KebabCasedModels.Add(model);
await dbContext.SaveChangesAsync();
});
var route = "api/v1/kebab-cased-models";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.ManyData.Should().HaveCount(1);
responseDocument.ManyData[0].Id.Should().Be(model.StringId);
responseDocument.ManyData[0].Attributes["compound-attr"].Should().Be(model.CompoundAttr);
}
[Fact]
public async Task KebabCaseFormatter_GetSingle_IsReturned()
{
// Arrange
var model = _faker.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.KebabCasedModels.Add(model);
await dbContext.SaveChangesAsync();
});
var route = "api/v1/kebab-cased-models/" + model.StringId;
// Act
var (httpResponse, responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Id.Should().Be(model.StringId);
responseDocument.SingleData.Attributes["compound-attr"].Should().Be(model.CompoundAttr);
}
[Fact]
public async Task KebabCaseFormatter_Create_IsCreated()
{
// Arrange
var model = _faker.Generate();
var serializer = GetSerializer<KebabCasedModel>(kcm => new { kcm.CompoundAttr });
var route = "api/v1/kebab-cased-models";
var requestBody = serializer.Serialize(model);
// Act
var (httpResponse, responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.Created);
responseDocument.SingleData.Should().NotBeNull();
responseDocument.SingleData.Attributes["compound-attr"].Should().Be(model.CompoundAttr);
}
[Fact]
public async Task KebabCaseFormatter_Update_IsUpdated()
{
// Arrange
var model = _faker.Generate();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.KebabCasedModels.Add(model);
await dbContext.SaveChangesAsync();
});
model.CompoundAttr = _faker.Generate().CompoundAttr;
var serializer = GetSerializer<KebabCasedModel>(kcm => new { kcm.CompoundAttr });
var route = "api/v1/kebab-cased-models/" + model.StringId;
var requestBody = serializer.Serialize(model);
// Act
var (httpResponse, responseDocument) = await _testContext.ExecutePatchAsync<Document>(route, requestBody);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.Should().BeNull();
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
var stored = await dbContext.KebabCasedModels.SingleAsync(x => x.Id == model.Id);
Assert.Equal(model.CompoundAttr, stored.CompoundAttr);
});
}
[Fact]
public async Task KebabCaseFormatter_ErrorWithStackTrace_CasingConventionIsApplied()
{
// Arrange
var route = "api/v1/kebab-cased-models/1";
const string requestBody = "{ \"data\": {";
// Act
var (httpResponse, responseDocument) = await _testContext.ExecutePatchAsync<JObject>(route, requestBody);
httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity);
var meta = responseDocument["errors"][0]["meta"];
Assert.NotNull(meta["stack-trace"]);
}
private IRequestSerializer GetSerializer<TResource>(Expression<Func<TResource, dynamic>> attributes = null, Expression<Func<TResource, dynamic>> relationships = null) where TResource : class, IIdentifiable
{
using var scope = _testContext.Factory.Services.CreateScope();
var serializer = scope.ServiceProvider.GetRequiredService<IRequestSerializer>();
var graph = scope.ServiceProvider.GetRequiredService<IResourceGraph>();
serializer.AttributesToSerialize = attributes != null ? graph.GetAttributes(attributes) : null;
serializer.RelationshipsToSerialize = relationships != null ? graph.GetRelationships(relationships) : null;
return serializer;
}
}
public sealed class KebabCaseStartup : TestStartup
{
public KebabCaseStartup(IConfiguration configuration) : base(configuration)
{
}
protected override void ConfigureJsonApiOptions(JsonApiOptions options)
{
base.ConfigureJsonApiOptions(options);
((DefaultContractResolver)options.SerializerSettings.ContractResolver).NamingStrategy = new KebabCaseNamingStrategy();
}
}
}
| 37.071429 | 213 | 0.646848 | [
"MIT"
] | ybuasen/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/Acceptance/KebabCaseFormatterTests.cs | 7,266 | C# |
using LiveSplit.ComponentUtil;
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace alyx_multiplayer
{
class Core
{
private static Process game;
private static IntPtr _entListPtr;
private static IntPtr _gamePathPtr;
private static IntPtr _mapNamePtr => _gamePathPtr + 0x100;
private static StringWatcher _mapName;
private static MemoryWatcherList _watchers = new MemoryWatcherList();
public static NetworkHandler networkHandler = new NetworkHandler();
private const int ENT_INFO_SIZE = 120;
private const int TICK_MS = 20;
private static UI ui;
private static RichTextBox textBoxLog;
private static ToolStripStatusLabel labelIP;
public static bool isInfoOpen = false;
private static bool isConsoleEnabled = false;
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
private static extern void ShowWindow(IntPtr one, int two);
const int CONSOLE_HIDE = 0;
const int CONSOLE_SHOW = 5;
private static bool hasFoundPtr = false;
private const string defaultScriptPath = @"C:\Program Files (x86)\Steam\steamapps\common\Half-Life Alyx\game\hlvr_addons\alyx_multiplayer\scripts\vscripts";
public static string scriptPath;
private static string entPrefix = "ex1d_";
public static int entPrefixIndex = 1;
private static string cachedMapName = "";
/// <summary>
/// Main method. Establish the events thread, then run the UI.
/// </summary>
/// <param name="args">Command-line arguments.</param>
[STAThread]
public static void Main(string[] args)
{
ConfigureConsole(isConsoleEnabled);
Application.SetCompatibleTextRenderingDefault(false);
Application.EnableVisualStyles();
ui = new UI();
scriptPath = defaultScriptPath;
Thread eventsThread = new Thread(EventsThread.Begin);
eventsThread.Start();
Application.Run(ui);
}
/// <summary>
/// Show or hide the console window.
/// </summary>
/// <param name="showWindow">If true, show the window. Else, hide the window.</param>
private static void ConfigureConsole(bool showConsole)
{
var handle = GetConsoleWindow();
if (showConsole) ShowWindow(handle, CONSOLE_SHOW);
else ShowWindow(handle, CONSOLE_HIDE);
}
public static void ToggleConsole()
{
isConsoleEnabled = !isConsoleEnabled;
ConfigureConsole(isConsoleEnabled);
}
/// <summary>
/// We can run our events while the UI is also running.
/// </summary>
private class EventsThread {
/// <summary>
/// Run init, then update continuously.
/// </summary>
public static void Begin()
{
FindUIControls();
DisplayIP();
bool isGameRunning = false;
while (!isGameRunning)
{
try
{
game = Process.GetProcessesByName("hlvr")[0];
isGameRunning = true;
}
catch (IndexOutOfRangeException)
{
Log("[MAIN] Game not running! Checking again in five seconds.");
Thread.Sleep(5000);
}
}
Console.Clear();
Init();
Console.SetCursorPosition(0, 10);
while (true)
{
Update();
Thread.Sleep(TICK_MS);
Console.SetCursorPosition(0, 10);
}
}
}
/// <summary>
///
/// </summary>
public class InfoThread
{
/// <summary>
///
/// </summary>
public static void ShowInfo()
{
Application.Run(new Info());
}
}
/// <summary>
/// Find and define all the controls from the UI.
/// </summary>
private static void FindUIControls()
{
textBoxLog = ui.Controls.Find("textBoxLog", true).FirstOrDefault() as RichTextBox;
StatusStrip statusStrip = ui.Controls.Find("statusStrip", true).FirstOrDefault() as StatusStrip;
labelIP = statusStrip.Items.Find("labelIP", true).FirstOrDefault() as ToolStripStatusLabel;
}
/// <summary>
/// Output text to the UI log.
/// </summary>
/// <param name="text">The text to output.</param>
delegate void CallbackLog(string text, bool writeToConsole = true);
public static void Log(String text, bool writeToConsole = true)
{
if (textBoxLog.InvokeRequired)
{
CallbackLog callbackLog = new CallbackLog(Log);
textBoxLog.Invoke(callbackLog, new object[] { text, writeToConsole });
}
else
{
if (writeToConsole) Console.WriteLine(text);
if (textBoxLog.Text.Equals("")) textBoxLog.Text = text;
else textBoxLog.Text = textBoxLog.Text + "\n" + text;
}
}
/// <summary>
/// Figure out and display the local public IP.
/// </summary>
delegate void CallbackDisplayIP();
private static void DisplayIP()
{
String ip = "Not found!";
try
{
ip = new WebClient().DownloadString("https://api.ipify.org");
} catch
{
Console.WriteLine("Error in IP fetch!");
ip = "Error in IP fetch! Are you connected to the internet?";
}
Console.WriteLine("[DISPLAYIP] Client public IP is " + ip);
labelIP.Text = ip;
}
/// <summary>
/// Get a static pointer from the local pointer of an instruction.
/// </summary>
/// <param name="ptr">Location of the instruction.</param>
/// <param name="trgOperandOffset">Where the pointer sits inside this instruction.</param>
/// <param name="totalSize">Size of the instruction.</param>
/// <returns></returns>
private static IntPtr GetPointer(IntPtr ptr, int trgOperandOffset, int totalSize)
{
byte[] bytes = game.ReadBytes(ptr + trgOperandOffset, 4);
if (bytes == null)
{
return IntPtr.Zero;
}
Array.Reverse(bytes);
int offset = Convert.ToInt32(BitConverter.ToString(bytes).Replace("-", ""), 16);
IntPtr actualPtr = IntPtr.Add(ptr + totalSize, offset);
return actualPtr;
}
/// <summary>
/// Initialize signature scanners and sigscan.
/// </summary>
private static void Init()
{
Log("Starting with default values", false);
Action<string, IntPtr> SigReport = (name, ptr) =>
{
Console.WriteLine("[INIT] " + name + (ptr == IntPtr.Zero ? " WAS NOT FOUND" : " is 0x" + ptr.ToString("X")));
};
SigScanTarget _entListSig = new SigScanTarget(6,
"40 ?? 48 ?? ?? ??",
"48 ?? ?? ?? ?? ?? ??", // MOV RAX,qword ptr [DAT_1814e3bc0]
"8b ?? 48 ?? ?? ?? ?? ?? ?? 48 ?? ?? ff ?? ?? ?? ?? ?? 4c ?? ??");
_entListSig.OnFound = (proc, scanner, ptr) => GetPointer(ptr, 3, 7);
SigScanTarget _gamePathSig = new SigScanTarget(7,
"48 8B 97 ?? ?? ?? ??",
"48 8D 0D ?? ?? ?? ??", // LEA RCX,[mapname]
"48 8B 5C 24 ??");
_gamePathSig.OnFound = (proc, scanner, ptr) => GetPointer(ptr, 3, 7);
ProcessModuleWow64Safe[] modules = game.ModulesWow64Safe();
ProcessModuleWow64Safe server = modules.FirstOrDefault(x => x.ModuleName.ToLower() == "server.dll");
ProcessModuleWow64Safe engine = modules.FirstOrDefault(x => x.ModuleName.ToLower() == "engine2.dll");
while (server == null || engine == null)
{
Console.WriteLine("[INIT] Modules aren't yet loaded! Waiting 1 second until next try");
Thread.Sleep(1000);
}
var serverScanner = new SignatureScanner(game, server.BaseAddress, server.ModuleMemorySize);
var engineScanner = new SignatureScanner(game, engine.BaseAddress, engine.ModuleMemorySize);
_entListPtr = serverScanner.Scan(_entListSig); SigReport("entity list", _entListPtr);
_gamePathPtr = engineScanner.Scan(_gamePathSig); SigReport("game path / map name", _gamePathPtr);
Console.WriteLine("gamepath " + game.ReadString(_gamePathPtr, 255) + " ");
_mapName = new StringWatcher(_mapNamePtr, 255);
_watchers.Add(_mapName);
}
/// <summary>
/// Get the pointer of an entity using its index.
/// </summary>
private static IntPtr GetEntPtrFromIndex(int index)
{
// The game splits the entity pointer list into blocks with seemingly a certain size.
// This function is taken from the game's decompiled code!
int block = 24 + (index >> 9) * 8;
int pos = (index & 511) * ENT_INFO_SIZE;
new DeepPointer(_entListPtr, block, 0x0).DerefOffsets(game, out IntPtr blockPtr);
IntPtr entPtr = blockPtr + pos;
return entPtr;
}
/// <summary>
/// Get the name of an entity using a pointer.
/// </summary>
/// <param name="ptr">The pointer.</param>
/// <param name="isTargetName">Whether the supplied name is the entity's name or its class name.</param>
/// <returns></returns>
private static string GetNameFromPtr(IntPtr ptr, bool isTargetName = false)
{
DeepPointer nameptr = new DeepPointer(ptr, 0x10, (isTargetName) ? 0x18 : 0x20, 0x0);
string name = "";
nameptr.DerefString(game, 128, out name);
return name;
}
/// <summary>
/// Get the pointer of an entity using its name.
/// </summary>
/// <param name="name">The entity name.</param>
/// <param name="isTargetName">If true, the name parameter is the entity's class name. Otherwise, it's the entity's actual name.</param>
/// <returns></returns>
private static IntPtr GetPtrByName(string entNameNoPrefix, bool isTargetName = false)
{
// Refresh entPrefix, if need be
if (!_mapName.Current.Equals(cachedMapName))
{
entPrefix = FindEntPrefix(entNameNoPrefix, isTargetName);
cachedMapName = _mapName.Current;
}
string name = entPrefix + entNameNoPrefix;
var prof = Stopwatch.StartNew();
// 2838: theorectically the index can go all the way up to 32768 but it never does even on the biggest of maps
for (int i = 0; i <= 20000; i++)
{
IntPtr entPtr = GetEntPtrFromIndex(i);
if (entPtr != IntPtr.Zero)
{
if (GetNameFromPtr(entPtr, isTargetName) == name)
{
prof.Stop();
if (!hasFoundPtr)
{
hasFoundPtr = true;
Log("Found " + name + " pointer!", false);
}
Console.WriteLine("[ENTFINDING] Successfully found " + name + "'s pointer after " + prof.ElapsedMilliseconds * 0.001f + " seconds, index #" + i);
return entPtr;
}
else continue;
}
}
prof.Stop();
if (hasFoundPtr)
{
hasFoundPtr = false;
Log("Lost track of " + name + " pointer!", false);
} Console.WriteLine("[ENTFINDING] Can't find " + name + "'s pointer! Time spent: " + prof.ElapsedMilliseconds * 0.001f + " seconds");
return IntPtr.Zero;
}
/// <summary>
/// Get the position of an entity using a pointer.
/// </summary>
/// <param name="ptr">The pointer.</param>
/// <returns></returns>
private static Vector3f GetEntPosFromPtr(IntPtr ptr)
{
new DeepPointer(ptr, 0x1a0, 0x108).DerefOffsets(game, out IntPtr posPtr);
return game.ReadValue<Vector3f>(posPtr);
}
/// <summary>
/// Get the angles of an entity using a pointer.
/// </summary>
/// <param name="ptr">The pointer.</param>
/// <returns></returns>
private static Vector3f GetEntAngleFromPtr(IntPtr ptr)
{
new DeepPointer(ptr, 0x1a0, 0x114).DerefOffsets(game, out IntPtr angPtr);
return game.ReadValue<Vector3f>(angPtr);
}
/// <summary>
/// Search for the entity prefix that works for this map.
/// </summary>
/// <param name="entNameNoPrefix">The entity's name without a prefix.</param>
/// <param name="isTargetName">If true, the name parameter is the entity's class name. Otherwise, it's the entity's actual name.</param>
/// <returns></returns>
private static string FindEntPrefix(string entNameNoPrefix, bool isTargetName = false)
{
string testEntPrefix = entPrefix;
entPrefixIndex = 1;
int indexCap = 100; // Will the player ever load more than 100 maps?
Log("Finding new ent prefix...", false);
bool stillSearching = true;
while (stillSearching)
{
Log("Testing " + testEntPrefix, false);
string name = testEntPrefix + entNameNoPrefix;
for (int i = 0; i <= 20000; i++)
{
IntPtr entPtr = GetEntPtrFromIndex(i);
if (entPtr != IntPtr.Zero)
{
if (GetNameFromPtr(entPtr, isTargetName) == name)
{
if (!hasFoundPtr)
{
hasFoundPtr = true;
Log("Found " + name + " pointer!", false);
}
stillSearching = false;
}
else continue;
}
}
if (stillSearching)
{
entPrefixIndex++;
if (entPrefixIndex >= indexCap) entPrefixIndex = 1;
testEntPrefix = "ex" + entPrefixIndex + "d_";
}
}
return testEntPrefix;
}
/// <summary>
/// Update the console with current position, angles, and mapname.
/// </summary>
private static void Update()
{
_watchers.UpdateAll(game);
// Original code for local coords fetch
// IntPtr localPtr = GetEntPtrFromIndex(1);
// Now we're using an empty at the local's head!
IntPtr localPtr = GetPtrByName("localHead", true);
Vector3f localPos = GetEntPosFromPtr(localPtr);
Vector3f localAng = GetEntAngleFromPtr(localPtr);
networkHandler.SendCoords(localPos.ToString() + "," + localAng.ToString() + " ");
string[] unparsedCoords;
try
{
unparsedCoords = networkHandler.GetCoords().Split(',');
} catch (NullReferenceException)
{
unparsedCoords = new string[] { "0 0 0", "0 0 0" };
}
string[] unparsedPos = unparsedCoords[0].Split(' ');
string[] unparsedAng = unparsedCoords[1].Split(' ');
System.Globalization.CultureInfo invariantCulture = System.Globalization.CultureInfo.InvariantCulture;
Vector3f networkPos = new Vector3f(float.Parse(unparsedPos[0], invariantCulture), float.Parse(unparsedPos[1], invariantCulture), float.Parse(unparsedPos[2], invariantCulture));
Vector3f networkAng = new Vector3f(float.Parse(unparsedAng[0], invariantCulture), float.Parse(unparsedAng[1], invariantCulture), float.Parse(unparsedAng[2], invariantCulture));
// Write networkPos and networkAng to the script we use to move the avatar
LuaUtils.WriteCoordsToScript(scriptPath, entPrefix, networkPos, networkAng);
Console.WriteLine("localPos " + localPos + " ");
Console.WriteLine("localAng " + localAng + " ");
Console.WriteLine("networkPos " + networkPos + " ");
Console.WriteLine("networkAng " + networkAng + " ");
Console.WriteLine("map " + _mapName.Current + " ");
}
}
}
| 40.176339 | 189 | 0.51864 | [
"MIT"
] | ZacharyTalis/alyx-multiplayer | Core.cs | 18,001 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using MaterialDesignThemes.Wpf;
namespace MaterialDesignExtensions.Controls
{
/// <summary>
/// The base class with common logic for <see cref="OpenDirectoryDialog" />, <see cref="OpenFileDialog" /> and <see cref="SaveFileDialog" />.
/// </summary>
public abstract class FileSystemDialog : Control
{
/// <summary>
/// Enables the feature to create new directories.
/// </summary>
public static readonly DependencyProperty CreateNewDirectoryEnabledProperty = DependencyProperty.Register(
nameof(CreateNewDirectoryEnabled),
typeof(bool),
typeof(FileSystemDialog),
new PropertyMetadata(false));
/// <summary>
/// Enables the feature to create new directories. Notice: It does not have any effects for <see cref="OpenFileDialog" />.
/// </summary>
public bool CreateNewDirectoryEnabled
{
get
{
return (bool)GetValue(CreateNewDirectoryEnabledProperty);
}
set
{
SetValue(CreateNewDirectoryEnabledProperty, value);
}
}
/// <summary>
/// The current directory of the dialog.
/// </summary>
public static readonly DependencyProperty CurrentDirectoryProperty = DependencyProperty.Register(
nameof(CurrentDirectory),
typeof(string),
typeof(FileSystemDialog),
new PropertyMetadata(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)));
/// <summary>
/// The current directory of the dialog.
/// </summary>
public string CurrentDirectory
{
get
{
return (string)GetValue(CurrentDirectoryProperty);
}
set
{
SetValue(CurrentDirectoryProperty, value);
}
}
/// <summary>
/// Shows or hides hidden directories and files.
/// </summary>
public static readonly DependencyProperty ShowHiddenFilesAndDirectoriesProperty = DependencyProperty.Register(
nameof(ShowHiddenFilesAndDirectories),
typeof(bool),
typeof(FileSystemDialog),
new PropertyMetadata(false));
/// <summary>
/// Shows or hides hidden directories and files.
/// </summary>
public bool ShowHiddenFilesAndDirectories
{
get
{
return (bool)GetValue(ShowHiddenFilesAndDirectoriesProperty);
}
set
{
SetValue(ShowHiddenFilesAndDirectoriesProperty, value);
}
}
/// <summary>
/// Shows or hides protected directories and files of the system.
/// </summary>
public static readonly DependencyProperty ShowSystemFilesAndDirectoriesProperty = DependencyProperty.Register(
nameof(ShowSystemFilesAndDirectories),
typeof(bool),
typeof(FileSystemDialog),
new PropertyMetadata(false));
/// <summary>
/// Shows or hides protected directories and files of the system.
/// </summary>
public bool ShowSystemFilesAndDirectories
{
get
{
return (bool)GetValue(ShowSystemFilesAndDirectoriesProperty);
}
set
{
SetValue(ShowSystemFilesAndDirectoriesProperty, value);
}
}
static FileSystemDialog()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FileSystemDialog), new FrameworkPropertyMetadata(typeof(FileSystemDialog)));
}
/// <summary>
/// Creates a new <see cref="FileSystemDialog" />.
/// </summary>
public FileSystemDialog() : base() { }
protected DialogHost GetDialogHost()
{
DependencyObject element = VisualTreeHelper.GetParent(this);
while (element != null && !(element is DialogHost))
{
element = VisualTreeHelper.GetParent(element);
}
return element as DialogHost;
}
protected static void InitDialog(FileSystemDialog dialog, double? width, double? height,
string currentDirectory,
bool showHiddenFilesAndDirectories, bool showSystemFilesAndDirectories,
bool createNewDirectoryEnabled = false)
{
if (width != null)
{
dialog.Width = (double)width;
}
if (height != null)
{
dialog.Height = (double)height;
}
if (!string.IsNullOrWhiteSpace(currentDirectory))
{
dialog.CurrentDirectory = currentDirectory;
}
dialog.CreateNewDirectoryEnabled = createNewDirectoryEnabled;
dialog.ShowHiddenFilesAndDirectories = showHiddenFilesAndDirectories;
dialog.ShowSystemFilesAndDirectories = showSystemFilesAndDirectories;
}
}
/// <summary>
/// Arguments to initialize a dialog.
/// </summary>
public abstract class FileSystemDialogArguments
{
/// <summary>
/// The fixed width of the dialog (nullable).
/// </summary>
public double? Width { get; set; }
/// <summary>
/// The fixed height of the dialog (nullable).
/// </summary>
public double? Height { get; set; }
/// <summary>
/// The current directory of the dialog.
/// </summary>
public string CurrentDirectory { get; set; }
/// <summary>
/// Enables the feature to create new directories. Notice: It does not have any effects for <see cref="OpenFileDialog" />.
/// </summary>
public bool CreateNewDirectoryEnabled { get; set; }
/// <summary>
/// Shows or hides hidden directories and files.
/// </summary>
public bool ShowHiddenFilesAndDirectories { get; set; }
/// <summary>
/// Shows or hides protected directories and files of the system.
/// </summary>
public bool ShowSystemFilesAndDirectories { get; set; }
/// <summary>
/// Callback after openening the dialog.
/// </summary>
public DialogOpenedEventHandler OpenedHandler { get; set; }
/// <summary>
/// Callback after closing the dialog.
/// </summary>
public DialogClosingEventHandler ClosingHandler { get; set; }
/// <summary>
/// Creates a new <see cref="FileSystemDialogArguments" />.
/// </summary>
public FileSystemDialogArguments()
{
Width = null;
Height = null;
CurrentDirectory = null;
CreateNewDirectoryEnabled = false;
ShowHiddenFilesAndDirectories = false;
ShowSystemFilesAndDirectories = false;
OpenedHandler = null;
ClosingHandler = null;
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="args"></param>
public FileSystemDialogArguments(FileSystemDialogArguments args)
{
Width = args.Width;
Height = args.Height;
CurrentDirectory = args.CurrentDirectory;
CreateNewDirectoryEnabled = args.CreateNewDirectoryEnabled;
ShowHiddenFilesAndDirectories = args.ShowHiddenFilesAndDirectories;
ShowSystemFilesAndDirectories = args.ShowSystemFilesAndDirectories;
OpenedHandler = args.OpenedHandler;
ClosingHandler = args.ClosingHandler;
}
}
/// <summary>
/// Base class for the result of a dialog.
/// </summary>
public abstract class FileSystemDialogResult
{
/// <summary>
/// true, if the dialog was canceled
/// </summary>
public bool Canceled { get; protected set; }
/// <summary>
/// true, if the dialog was confirmed
/// </summary>
public bool Confirmed
{
get
{
return !Canceled;
}
}
/// <summary>
/// Creates a new <see cref="FileSystemDialogResult" />.
/// </summary>
/// <param name="canceled"></param>
public FileSystemDialogResult(bool canceled)
{
Canceled = canceled;
}
}
}
| 31.985455 | 145 | 0.570032 | [
"MIT"
] | KHALED-LAKEHAL/MaterialDesignExtensions | MaterialDesignExtensions/Controls/FileSystemDialog.cs | 8,798 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Internal.Runtime.CompilerServices;
namespace System
{
public static partial class MemoryExtensions
{
/// <summary>
/// Indicates whether the specified span contains only white-space characters.
/// </summary>
public static bool IsWhiteSpace(this ReadOnlySpan<char> span)
{
for (int i = 0; i < span.Length; i++)
{
if (!char.IsWhiteSpace(span[i]))
return false;
}
return true;
}
/// <summary>
/// Returns a value indicating whether the specified <paramref name="value"/> occurs within the <paramref name="span"/>.
/// <param name="span">The source span.</param>
/// <param name="value">The value to seek within the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
/// </summary>
public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
return IndexOf(span, value, comparisonType) >= 0;
}
/// <summary>
/// Determines whether this <paramref name="span"/> and the specified <paramref name="other"/> span have the same characters
/// when compared using the specified <paramref name="comparisonType"/> option.
/// <param name="span">The source span.</param>
/// <param name="other">The value to compare with the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param>
/// </summary>
public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType)) == 0;
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType)) == 0;
case StringComparison.Ordinal:
return EqualsOrdinal(span, other);
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return EqualsOrdinalIgnoreCase(span, other);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool EqualsOrdinal(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
{
if (span.Length != value.Length)
return false;
if (value.Length == 0) // span.Length == value.Length == 0
return true;
return span.SequenceEqual(value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
{
if (span.Length != value.Length)
return false;
if (value.Length == 0) // span.Length == value.Length == 0
return true;
return CompareInfo.EqualsOrdinalIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), span.Length);
}
/// <summary>
/// Compares the specified <paramref name="span"/> and <paramref name="other"/> using the specified <paramref name="comparisonType"/>,
/// and returns an integer that indicates their relative position in the sort order.
/// <param name="span">The source span.</param>
/// <param name="other">The value to compare with the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param>
/// </summary>
public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
if (span.Length == 0 || other.Length == 0)
return span.Length - other.Length;
return string.CompareOrdinal(span, other);
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return CompareInfo.CompareOrdinalIgnoreCase(span, other);
}
}
/// <summary>
/// Reports the zero-based index of the first occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>.
/// <param name="span">The source span.</param>
/// <param name="value">The value to seek within the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
/// </summary>
public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
if (comparisonType == StringComparison.Ordinal)
{
return SpanHelpers.IndexOf(
ref MemoryMarshal.GetReference(span),
span.Length,
ref MemoryMarshal.GetReference(value),
value.Length);
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return CompareInfo.IndexOfOrdinalIgnoreCase(span, value, fromBeginning: true);
}
}
/// <summary>
/// Reports the zero-based index of the last occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>.
/// <param name="span">The source span.</param>
/// <param name="value">The value to seek within the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
/// </summary>
public static int LastIndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
if (comparisonType == StringComparison.Ordinal)
{
return SpanHelpers.LastIndexOf(
ref MemoryMarshal.GetReference(span),
span.Length,
ref MemoryMarshal.GetReference(value),
value.Length);
}
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return CompareInfo.IndexOfOrdinalIgnoreCase(span, value, fromBeginning: false);
}
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to lowercase,
/// using the casing rules of the specified culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <param name="culture">An object that supplies culture-specific casing rules.</param>
/// <remarks>If <paramref name="culture"/> is null, <see cref="System.Globalization.CultureInfo.CurrentCulture"/> will be used.</remarks>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
/// <exception cref="InvalidOperationException">The source and destination buffers overlap.</exception>
public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo? culture)
{
if (source.Overlaps(destination))
throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation);
culture ??= CultureInfo.CurrentCulture;
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToLowerAsciiInvariant(source, destination);
else
culture.TextInfo.ChangeCaseToLower(source, destination);
return source.Length;
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to lowercase,
/// using the casing rules of the invariant culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
/// <exception cref="InvalidOperationException">The source and destination buffers overlap.</exception>
public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination)
{
if (source.Overlaps(destination))
throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation);
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToLowerAsciiInvariant(source, destination);
else
TextInfo.Invariant.ChangeCaseToLower(source, destination);
return source.Length;
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to uppercase,
/// using the casing rules of the specified culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <param name="culture">An object that supplies culture-specific casing rules.</param>
/// <remarks>If <paramref name="culture"/> is null, <see cref="System.Globalization.CultureInfo.CurrentCulture"/> will be used.</remarks>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
/// <exception cref="InvalidOperationException">The source and destination buffers overlap.</exception>
public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo? culture)
{
if (source.Overlaps(destination))
throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation);
culture ??= CultureInfo.CurrentCulture;
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToUpperAsciiInvariant(source, destination);
else
culture.TextInfo.ChangeCaseToUpper(source, destination);
return source.Length;
}
/// <summary>
/// Copies the characters from the source span into the destination, converting each character to uppercase
/// using the casing rules of the invariant culture.
/// </summary>
/// <param name="source">The source span.</param>
/// <param name="destination">The destination span which contains the transformed characters.</param>
/// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns>
/// <exception cref="InvalidOperationException">The source and destination buffers overlap.</exception>
public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination)
{
if (source.Overlaps(destination))
throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation);
// Assuming that changing case does not affect length
if (destination.Length < source.Length)
return -1;
if (GlobalizationMode.Invariant)
TextInfo.ToUpperAsciiInvariant(source, destination);
else
TextInfo.Invariant.ChangeCaseToUpper(source, destination);
return source.Length;
}
/// <summary>
/// Determines whether the end of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option.
/// </summary>
/// <param name="span">The source span.</param>
/// <param name="value">The sequence to compare to the end of the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
return span.EndsWith(value);
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return span.EndsWithOrdinalIgnoreCase(value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool EndsWithOrdinalIgnoreCase(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
=> value.Length <= span.Length
&& CompareInfo.EqualsOrdinalIgnoreCase(
ref Unsafe.Add(ref MemoryMarshal.GetReference(span), span.Length - value.Length),
ref MemoryMarshal.GetReference(value),
value.Length);
/// <summary>
/// Determines whether the beginning of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option.
/// </summary>
/// <param name="span">The source span.</param>
/// <param name="value">The sequence to compare to the beginning of the source span.</param>
/// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param>
public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType)
{
string.CheckStringComparison(comparisonType);
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return CompareInfo.Invariant.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
return span.StartsWith(value);
default:
Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase);
return span.StartsWithOrdinalIgnoreCase(value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool StartsWithOrdinalIgnoreCase(this ReadOnlySpan<char> span, ReadOnlySpan<char> value)
=> value.Length <= span.Length
&& CompareInfo.EqualsOrdinalIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), value.Length);
/// <summary>
/// Returns an enumeration of <see cref="Rune"/> from the provided span.
/// </summary>
/// <remarks>
/// Invalid sequences will be represented in the enumeration by <see cref="Rune.ReplacementChar"/>.
/// </remarks>
public static SpanRuneEnumerator EnumerateRunes(this ReadOnlySpan<char> span)
{
return new SpanRuneEnumerator(span);
}
/// <summary>
/// Returns an enumeration of <see cref="Rune"/> from the provided span.
/// </summary>
/// <remarks>
/// Invalid sequences will be represented in the enumeration by <see cref="Rune.ReplacementChar"/>.
/// </remarks>
public static SpanRuneEnumerator EnumerateRunes(this Span<char> span)
{
return new SpanRuneEnumerator(span);
}
}
}
| 52.028205 | 198 | 0.640875 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Private.CoreLib/src/System/MemoryExtensions.Globalization.cs | 20,293 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Umbraco.Web.Models.TemplateQuery
{
public class ContentTypeModel
{
public string Alias { get; set; }
public string Name { get; set; }
}
}
| 18.4375 | 42 | 0.694915 | [
"MIT"
] | 0Neji/Umbraco-CMS | src/Umbraco.Web/Models/TemplateQuery/ContentTypeModel.cs | 297 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Linq;
namespace Microsoft.MixedReality.Toolkit.SDK.DiagnosticsSystem
{
internal class MemoryUseTracker
{
private readonly MemoryReading[] memoryReadings;
private int index = 0;
private MemoryReading sumReading = new MemoryReading();
public MemoryUseTracker()
{
memoryReadings = new MemoryReading[10];
for (int i = 0; i < memoryReadings.Length; i++)
{
memoryReadings[i] = new MemoryReading();
}
}
public MemoryReading GetReading()
{
var reading = memoryReadings[index];
reading.GCMemoryInBytes = GC.GetTotalMemory(false);
index = (index + 1) % memoryReadings.Length;
return memoryReadings.Aggregate(sumReading.Reset(), (a, b) => a + b) / memoryReadings.Length;
}
public struct MemoryReading
{
public long GCMemoryInBytes { get; set; }
public MemoryReading Reset()
{
GCMemoryInBytes = 0;
return this;
}
public static MemoryReading operator +(MemoryReading a, MemoryReading b)
{
a.GCMemoryInBytes += b.GCMemoryInBytes;
return a;
}
public static MemoryReading operator /(MemoryReading a, int b)
{
a.GCMemoryInBytes /= b;
return a;
}
}
}
}
| 26.0625 | 105 | 0.558753 | [
"MIT"
] | Alexees/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit-SDK/Features/Diagnostics/MemoryUseTracker.cs | 1,670 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows.Forms;
using Nemiro.OAuth;
namespace TestProject1
{
[TestClass]
public class UniValueBindingTest
{
[TestMethod]
public void UniValue_Binding()
{
var list = new ListBox();
var v = UniValue.ParseJson("[{text: 'test', value: 1, any: 'aaaa'},{text: '123', value: 2, any: 'bbbb'},{text: 'xyz', value: 3, any: 'cccc'}]");
list.DisplayMember = "text";
list.ValueMember = "value";
list.DataSource = v;
var form = new Form();
form.Controls.Add(list);
var list2 = new ListBox() { Left = list.Left + list.Width };
list2.DisplayMember = "text";
list2.ValueMember = "value";
foreach (UniValue item in v)
{
list2.Items.Add(item);
}
form.Controls.Add(list2);
var list3 = new ListBox() { Left = list2.Left + list2.Width };
list3.DisplayMember = "text";
list3.ValueMember = "value";
v = UniValue.ParseJson("{items: [{text: 'test', value: 1, any: 'aaaa'},{text: '123', value: 2, any: 'bbbb'},{text: 'xyz', value: 3, any: 'cccc'}]}");
foreach (UniValue item in v["items"])
{
list3.Items.Add(item);
}
form.Controls.Add(list3);
form.Show();
list.SelectedIndex = 0;
Assert.IsTrue(list.Text == "test");
form.Close();
list.SelectedIndex = 1;
if (list.Text != "123")
{
Assert.Fail();
}
if (list.SelectedValue.ToString() != "2")
{
Assert.Fail();
}
if (((UniValue)list.SelectedItem)["any"] != "bbbb")
{
Assert.Fail();
}
list2.SelectedIndex = 1;
if (list2.Text != "123")
{
Assert.Fail();
}
if (((UniValue)list2.SelectedItem)["value"] != "2")
{
Assert.Fail();
}
list3.SelectedIndex = 2;
if (list3.Text != "xyz")
{
Assert.Fail();
}
if (((UniValue)list3.SelectedItem)["value"] != "3")
{
Assert.Fail();
}
form.Close();
}
}
} | 21.613861 | 155 | 0.537792 | [
"Apache-2.0"
] | ivandrofly/nemiro.oauth.dll | src/TestProject1/UniValueBindingTest.cs | 2,185 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GeradorChefe : MonoBehaviour
{
private float tempoParaProximaGeracao = 0;
private float tempoEntreGeracoes = 20;
public GameObject ChefePrefab;
private ControlaInterface scriptControlaInterface;
public Transform[] PosicoesPossiveisDeGeracao;
private Transform jogador;
void Start()
{
tempoParaProximaGeracao = tempoEntreGeracoes;
scriptControlaInterface = GameObject.FindObjectOfType(typeof(ControlaInterface)) as ControlaInterface;
jogador = GameObject.FindWithTag(Tags.Jogador).transform;
}
void Update()
{
if(Time.timeSinceLevelLoad > tempoParaProximaGeracao)
{
Vector3 posicaoDeCriacao = CacularPosicaoMaisDistanteDoJogador();
Instantiate(ChefePrefab, posicaoDeCriacao, Quaternion.identity);
scriptControlaInterface.AparecerTextoChefeCriado();
tempoParaProximaGeracao = Time.timeSinceLevelLoad + tempoEntreGeracoes;
}
}
Vector3 CacularPosicaoMaisDistanteDoJogador()
{
Vector3 posicaoDeMaiorDistancia = Vector3.zero;
float maiorDistancia = 0;
foreach (Transform posicao in PosicoesPossiveisDeGeracao)
{
float distanciaAteOJogador = Vector3.Distance(posicao.position, jogador.position);
if (distanciaAteOJogador > maiorDistancia)
{
maiorDistancia = distanciaAteOJogador;
posicaoDeMaiorDistancia = posicao.position;
}
}
return posicaoDeMaiorDistancia;
}
}
| 34.270833 | 110 | 0.693009 | [
"MIT"
] | rodolfostark/zombie-game | Assets/Scripts/GeradorChefe.cs | 1,645 | C# |
using Microsoft.OData;
using Microsoft.OData.Edm;
using Microsoft.OData.UriParser;
using System;
using System.Collections.Generic;
namespace OdataToEntity.Parsers.Translators
{
internal enum OeNavigationSelectItemKind
{
Normal,
NotSelected,
NextLink
}
internal sealed class OeNavigationSelectItem
{
private bool _allSelected;
private readonly IEdmNavigationProperty? _edmProperty;
private OeEntryFactory? _entryFactory;
private readonly List<OeNavigationSelectItem> _navigationItems;
private ExpandedReferenceSelectItem? _navigationSelectItem;
private readonly List<OeStructuralSelectItem> _structuralItems;
private readonly List<OeStructuralSelectItem> _structuralItemsNotSelected;
private OeNavigationSelectItem(IEdmEntitySetBase entitySet, ODataPath path)
{
EntitySet = entitySet;
Path = path;
_navigationItems = new List<OeNavigationSelectItem>();
_structuralItems = new List<OeStructuralSelectItem>();
_structuralItemsNotSelected = new List<OeStructuralSelectItem>();
_allSelected = true;
}
public OeNavigationSelectItem(ODataUri odataUri)
: this(GetEntitySet(odataUri.Path), odataUri.Path)
{
Kind = OeNavigationSelectItemKind.Normal;
}
public OeNavigationSelectItem(IEdmEntitySetBase entitySet, OeNavigationSelectItem parent, ExpandedReferenceSelectItem item, OeNavigationSelectItemKind kind)
: this(entitySet, CreatePath(parent.Path, item.PathToNavigationProperty))
{
_edmProperty = ((NavigationPropertySegment)item.PathToNavigationProperty.LastSegment).NavigationProperty;
_navigationSelectItem = item;
EntitySet = entitySet;
Kind = kind;
Parent = parent;
}
internal void AddKeyRecursive(bool notSelected)
{
if (!AllSelected)
foreach (IEdmStructuralProperty keyProperty in EntitySet.EntityType().Key())
AddStructuralItem(keyProperty, notSelected);
if (_navigationSelectItem is ExpandedNavigationSelectItem expanded)
{
OrderByClause orderByClause = OeSkipTokenParser.GetUniqueOrderBy(EntitySet, expanded.OrderByOption, null);
if (expanded.OrderByOption != orderByClause)
_navigationSelectItem = new ExpandedNavigationSelectItem(
expanded.PathToNavigationProperty,
expanded.NavigationSource,
expanded.SelectAndExpand,
expanded.FilterOption,
orderByClause,
expanded.TopOption,
expanded.SkipOption,
expanded.CountOption,
expanded.SearchOption,
expanded.LevelsOption);
}
foreach (OeNavigationSelectItem childNavigationItem in _navigationItems)
{
if (!AllSelected && childNavigationItem.Kind == OeNavigationSelectItemKind.NextLink && !childNavigationItem.EdmProperty!.Type.IsCollection())
foreach (IEdmStructuralProperty fkeyProperty in childNavigationItem.EdmProperty.DependentProperties())
AddStructuralItem(fkeyProperty, notSelected);
childNavigationItem.AddKeyRecursive(notSelected);
}
}
internal OeNavigationSelectItem AddOrGetNavigationItem(OeNavigationSelectItem navigationItem, bool isExpand)
{
_allSelected &= isExpand;
OeNavigationSelectItem? existingNavigationItem = FindChildrenNavigationItem(navigationItem.EdmProperty);
if (existingNavigationItem == null)
{
_navigationItems.Add(navigationItem);
return navigationItem;
}
if (existingNavigationItem.Kind == OeNavigationSelectItemKind.NotSelected && navigationItem.Kind == OeNavigationSelectItemKind.Normal)
existingNavigationItem.Kind = OeNavigationSelectItemKind.Normal;
return existingNavigationItem;
}
public bool AddStructuralItem(IEdmStructuralProperty structuralProperty, bool notSelected)
{
if (notSelected)
{
if (FindStructuralItemIndex(_structuralItemsNotSelected, structuralProperty) != -1)
return false;
if (FindStructuralItemIndex(_structuralItems, structuralProperty) != -1)
return false;
_structuralItemsNotSelected.Add(new OeStructuralSelectItem(structuralProperty, notSelected));
}
else
{
if (FindStructuralItemIndex(_structuralItems, structuralProperty) != -1)
return false;
int i = FindStructuralItemIndex(_structuralItemsNotSelected, structuralProperty);
if (i != -1)
_structuralItemsNotSelected.RemoveAt(i);
_structuralItems.Add(new OeStructuralSelectItem(structuralProperty, notSelected));
}
return true;
}
private static ODataPath CreatePath(ODataPath parentPath, ODataExpandPath pathToNavigationProperty)
{
var segments = new List<ODataPathSegment>(parentPath);
segments.AddRange(pathToNavigationProperty);
return new ODataPath(segments);
}
private OeNavigationSelectItem? FindChildrenNavigationItem(IEdmNavigationProperty navigationProperty)
{
for (int i = 0; i < _navigationItems.Count; i++)
if (_navigationItems[i].EdmProperty == navigationProperty)
return _navigationItems[i];
return null;
}
public OeNavigationSelectItem? FindHierarchyNavigationItem(IEdmNavigationProperty navigationProperty)
{
if (Parent != null)
{
if (EdmProperty == navigationProperty)
return this;
for (int i = 0; i < _navigationItems.Count; i++)
{
OeNavigationSelectItem? matched = _navigationItems[i].FindHierarchyNavigationItem(navigationProperty);
if (matched != null)
return matched;
}
}
return null;
}
private static int FindStructuralItemIndex(List<OeStructuralSelectItem> structuralItems, IEdmProperty structuralProperty)
{
for (int i = 0; i < structuralItems.Count; i++)
if (structuralItems[i].EdmProperty == structuralProperty)
return i;
return -1;
}
private static IEdmEntitySet GetEntitySet(ODataPath path)
{
if (path.LastSegment is EntitySetSegment entitySetSegment)
return entitySetSegment.EntitySet;
if (path.LastSegment is NavigationPropertySegment navigationPropertySegment)
return (IEdmEntitySet)navigationPropertySegment.NavigationSource;
if (path.LastSegment is KeySegment keySegment)
return (IEdmEntitySet)keySegment.NavigationSource;
if (path.LastSegment is OperationSegment)
return ((EntitySetSegment)path.FirstSegment).EntitySet;
if (path.LastSegment is FilterSegment)
return ((EntitySetSegment)path.FirstSegment).EntitySet;
throw new InvalidOperationException("unknown segment type " + path.LastSegment.ToString());
}
public IReadOnlyList<IEdmNavigationProperty> GetJoinPath()
{
var joinPath = new List<IEdmNavigationProperty>();
for (OeNavigationSelectItem navigationItem = this; navigationItem.Parent != null; navigationItem = navigationItem.Parent)
joinPath.Insert(0, navigationItem.EdmProperty!);
return joinPath;
}
public IReadOnlyList<OeStructuralSelectItem> GetStructuralItemsWithNotSelected()
{
if (AllSelected)
throw new InvalidOperationException("StructuralItems.Count > 0");
if (_structuralItemsNotSelected.Count == 0)
return _structuralItems;
var allStructuralItems = new List<OeStructuralSelectItem>(_structuralItems.Count + _structuralItemsNotSelected.Count);
allStructuralItems.AddRange(_structuralItems);
for (int i = 0; i < _structuralItemsNotSelected.Count; i++)
if (FindStructuralItemIndex(allStructuralItems, _structuralItemsNotSelected[i].EdmProperty) == -1)
allStructuralItems.Add(_structuralItemsNotSelected[i]);
return allStructuralItems;
}
public bool HasNavigationItems()
{
for (int i = 0; i < _navigationItems.Count; i++)
if (_navigationItems[i].Kind != OeNavigationSelectItemKind.NextLink)
return true;
return false;
}
public bool AlreadyUsedInBuildExpression { get; set; }
public IEdmNavigationProperty EdmProperty => _edmProperty ?? throw new InvalidOperationException(nameof(EdmProperty) + " missing for when Parent is null");
public IEdmEntitySetBase EntitySet { get; }
public OeEntryFactory EntryFactory
{
get => _entryFactory!;
set => _entryFactory = value ?? throw new ArgumentNullException(nameof(value));
}
public OeNavigationSelectItemKind Kind { get; private set; }
public IReadOnlyList<OeNavigationSelectItem> NavigationItems => _navigationItems;
public ExpandedReferenceSelectItem NavigationSelectItem => _navigationSelectItem ?? throw new InvalidOperationException(nameof(NavigationSelectItem) + " missing for when Parent is null");
public int PageSize { get; set; }
public OeNavigationSelectItem? Parent { get; }
public ODataPath Path { get; }
public bool AllSelected => _allSelected && _structuralItems.Count == 0;
}
internal readonly struct OeStructuralSelectItem
{
public OeStructuralSelectItem(IEdmStructuralProperty edmProperty, bool notSelected)
{
EdmProperty = edmProperty;
NotSelected = notSelected;
}
public IEdmStructuralProperty EdmProperty { get; }
public bool NotSelected { get; }
}
}
| 44.082988 | 195 | 0.638084 | [
"MIT"
] | DawidPotgieter/OdataToEntity | source/OdataToEntity/Parsers/Translators/OeSelectItem.cs | 10,626 | C# |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using gov.va.medora.mdo.conf;
namespace gov.va.medora.mdws.conf
{
public class MdwsConfigConstants : ConfigFileConstants
{
public static string MDWS_CONFIG_SECTION = "MDWS";
/// <summary>
/// MDWS sessions log level
/// </summary>
public static string SESSIONS_LOG_LEVEL = "SessionsLogLevel";
/// <summary>
/// MDWS sessions logging
/// </summary>
public static string SESSIONS_LOGGING = "SessionsLogging";
/// <summary>
/// Production installation
/// </summary>
public static string MDWS_PRODUCTION = "Production";
/// <summary>
/// The facade sites file name
/// </summary>
public static string FACADE_SITES_FILE = "FacadeSitesFile";
/// <summary>
/// True/False
/// </summary>
public static string FACADE_PRODUCTION = "FacadeProduction";
/// <summary>
/// The facade version information
/// </summary>
public static string FACADE_VERSION = "FacadeVersion";
public static string DEFAULT_VISIT_METHOD = "VisitMethod";
public static string DEFAULT_CONTEXT = "DefaultContext";
public static string EXCLUDE_SITE_200 = "ExcludeSite200";
public static string WATCH_SITES_FILE = "WatchSitesFile";
public static string BHIE_PASSWORD = "BhiePassword";
/// <summary>
/// The BSE data encryption key
/// </summary>
public static string BSE_SQL_ENCRYPTION_KEY = "EncryptionKey";
/// <summary>
/// Valid NHIN data types
/// </summary>
public static string NHIN_TYPES = "NhinTypes";
/// <summary>
/// MDWS service account federated ID
/// </summary>
public static string SERVICE_ACCOUNT_FED_UID = "ServiceAccountFederatedUid";
/// <summary>
/// MDWS service account name
/// </summary>
public static string SERVICE_ACCOUNT_NAME = "ServiceAccountSubjectName";
/// <summary>
/// MDWS service account BSE password
/// </summary>
public static string SERVICE_ACCOUNT_PASSWORD = "ServiceAccountPassword";
}
} | 34.313953 | 84 | 0.638767 | [
"Apache-2.0"
] | monkeyglasses/mdws | mdws/src/conf/MdwsConfigConstants.cs | 2,953 | C# |
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.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("ConsoleApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleApplication1")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9aab688a-ce5f-402e-8891-2d7b4ae85ea3")]
// 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")]
| 42.326923 | 84 | 0.755111 | [
"Apache-2.0"
] | NeCTAR-RC/murano-agent | contrib/windows-agent/ExecutionPlanGenerator/Properties/AssemblyInfo.cs | 2,204 | C# |
using System;
using UniInject;
using UniRx;
using UnityEngine.UIElements;
public class TextInputDialogControl : AbstractDialogControl, IInjectionFinishedListener
{
[Inject(UxmlName = "dialogTitle")]
protected Label dialogTitle;
[Inject(UxmlName = "dialogMessage")]
protected Label dialogMessage;
[Inject(UxmlName = "invalidValueIcon")]
protected VisualElement invalidValueIcon;
[Inject(UxmlName = "invalidValueLabel")]
protected Label invalidValueLabel;
[Inject(UxmlName = "valueTextField")]
protected TextField textField;
[Inject(UxmlName = "okButton")]
protected Button okButton;
[Inject(UxmlName = "cancelButton")]
protected Button cancelButton;
protected BackslashReplacingTextFieldControl backslashReplacingTextFieldControl;
private readonly Subject<string> submitValueEventStream = new();
public IObservable<string> SubmitValueEventStream => submitValueEventStream;
public Func<string, ValueInputDialogValidationResult> ValidateValueCallback { get; set; } = DefaultValidateValueCallback;
public string Title
{
get
{
return dialogTitle.text;
}
set
{
dialogTitle.text = value;
}
}
public string Message
{
get
{
return dialogMessage.text;
}
set
{
dialogMessage.text = value;
}
}
public string Value
{
get
{
return textField.value;
}
set
{
textField.value = value;
}
}
private string initialValue = "";
public string InitialValue
{
get
{
return initialValue;
}
set
{
initialValue = value;
Value = value;
// Do not show an error if the user has not done anything yet.
// But do not allow the user to continue if invalid either (okButton would still be disabled).
HideValidationMessage();
}
}
public virtual void OnInjectionFinished()
{
okButton.RegisterCallbackButtonTriggered(() => TrySubmitValue(textField.value));
cancelButton.RegisterCallbackButtonTriggered(() => CloseDialog());
if (backslashReplacingTextFieldControl == null)
{
backslashReplacingTextFieldControl = new BackslashReplacingTextFieldControl(textField);
backslashReplacingTextFieldControl.ValueChangedEventStream
.Subscribe(newValue => ValidateValue(newValue, true));
}
cancelButton.Focus();
InitialValue = "";
ValidateValue(InitialValue, false);
}
public void Reset()
{
Value = initialValue;
}
private void TrySubmitValue(string textValue)
{
if (ValidateValueCallback == null
|| ValidateValueCallback(textValue).Severity != EValueInputDialogValidationResultSeverity.Error)
{
submitValueEventStream.OnNext(textValue);
CloseDialog();
}
}
protected void ValidateValue(string textValue, bool showMessageIfInvalid)
{
if (ValidateValueCallback == null)
{
HideValidationMessageAndEnableOkButton();
return;
}
ValueInputDialogValidationResult validationResult = ValidateValueCallback(textValue);
if (validationResult.Severity == EValueInputDialogValidationResultSeverity.None)
{
HideValidationMessageAndEnableOkButton();
}
else
{
okButton.SetEnabled(false);
if (showMessageIfInvalid)
{
invalidValueIcon.ShowByVisibility();
invalidValueLabel.ShowByVisibility();
}
invalidValueLabel.text = validationResult.Message;
if (validationResult.Severity == EValueInputDialogValidationResultSeverity.Warning)
{
invalidValueIcon.AddToClassList("warning");
}
else if (validationResult.Severity == EValueInputDialogValidationResultSeverity.Error)
{
invalidValueIcon.AddToClassList("error");
}
}
}
private void HideValidationMessageAndEnableOkButton()
{
HideValidationMessage();
okButton.SetEnabled(true);
}
private void HideValidationMessage()
{
invalidValueIcon.HideByVisibility();
invalidValueLabel.HideByVisibility();
invalidValueIcon.RemoveFromClassList("warning");
invalidValueIcon.RemoveFromClassList("error");
}
private static ValueInputDialogValidationResult DefaultValidateValueCallback(string newValue)
{
if (newValue.IsNullOrEmpty())
{
return ValueInputDialogValidationResult.CreateErrorResult("Enter a value please");
}
return ValueInputDialogValidationResult.CreateValidResult();
}
}
| 27.295082 | 125 | 0.628829 | [
"MIT"
] | achimmihca/Play | UltraStar Play/Packages/playshared/Runtime/UI/Dialogs/TextInputDialogControl.cs | 4,997 | C# |
namespace GlutenFree.OddJob.Storage.BaseTests
{
public static class TestConstants
{
public static readonly string SimpleParam = "simple";
public static readonly string OddParam1 = "odd1";
public static readonly string OddParam2 = "odd2";
public static readonly string NestedOddParam1 = "n1";
public static readonly string NestedOddParam2 = "n2";
}
public class MockJobNoParam
{
public void DoThing()
{
//Intentionally empty, storage test.
}
}
public class MockJobInClassWithArity<TString>
{
public void DoThing(TString simpleParam, OddParam oddParam)
{
//Intentionally Empty since this is testing storage.
}
}
public class MockJobWithArity
{
public void DoThing<TString, TOddParam>(TString simpleParam, TOddParam oddParam)
{
//Intentionally empty since this is testing storage.
}
}
public class MockJob
{
public void DoThing(string simpleParam, OddParam oddParam)
{
//Intentionally empty since this is testing storage.
}
}
public class OddParam
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public NestedOddParam Nested { get; set; }
}
public class NestedOddParam
{
public string NestedParam1 { get; set; }
public string NestedParam2 { get; set; }
}
}
| 25.775862 | 88 | 0.613378 | [
"Apache-2.0"
] | to11mtm/OddJob | OddJob.Storage.BaseTests/TestData.cs | 1,497 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace OpenRPA.Interfaces.VT
{
public interface ITerminalConfig
{
string Hostname { get; set; }
int Port { get; set; }
string TermType { get; set; }
bool UseSSL { get; set; }
}
public interface IField
{
bool Allocated { get; set; }
ILocation Location { get; set; }
bool IsInputField { get; set; }
string Text { get; set; }
string ForeColor { get; set; }
string BackColor { get; set; }
bool UpperCase { get; set; }
}
public interface ILocation
{
int Position { get; set; }
int Column { get; set; }
int Row { get; set; }
int Length { get; set; }
}
public interface ITerminalSession : INotifyPropertyChanged
{
ITerminal Terminal { get; set; }
ITerminalConfig Config { get; set; }
void Connect();
void Disconnect();
void Refresh();
void Show();
void Close();
string WorkflowInstanceId { get; set; }
}
public interface ITerminal : INotifyPropertyChanged
{
event EventHandler CursorPositionSet;
void Connect(ITerminalConfig config);
bool IsConnected { get; set; }
bool IsConnecting { get; set; }
int CursorY { get; set; }
int CursorX { get; set; }
int HighlightCursorY { get; set; }
int HighlightCursorX { get; set; }
void SendText(int field, string text);
void SendText(string text);
void Refresh();
void Redraw();
int GetFieldByLocation(int column, int row);
int GetStringByLocation(int column, int row);
IField GetField(int field);
IField GetString(int field);
void SendKey(Key key);
string GetTextAt(int Column, int Row, int length);
void Close();
bool WaitForText(string Text, TimeSpan Timeout);
bool WaitForKeyboardUnlocked(TimeSpan Timeout);
}
}
| 29.694444 | 62 | 0.596819 | [
"MPL-2.0"
] | igaisin/openrpa | OpenRPA.Interfaces/VT/IVTTerminal.cs | 2,140 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using CognitiveMiddlewareService.MiddlewareService;
namespace CognitiveMiddlewareService.Processors
{
public class AggregatedResult
{
public LandmarkResult Landmark { get; set; }
public CelebrityResult Celebrity { get; set; }
}
} | 29.357143 | 101 | 0.746959 | [
"Apache-2.0"
] | microsoft/ai-edu | 实践案例/B06-搭建中间服务层/src/Processors/AggregatedResult.cs | 411 | 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("LagoVista.ISYAutomation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LagoVista.ISYAutomation")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 36.655172 | 84 | 0.745061 | [
"MIT"
] | LagoVista/ISY | src/LagoVista.ISY.UWP.Sample/Properties/AssemblyInfo.cs | 1,066 | C# |
#pragma checksum "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.Notifications\Areas\Notifications\Views\_ViewStart.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7091c65830b0329e613be026ede8a57552863778"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Notifications_Views__ViewStart), @"mvc.1.0.view", @"/Areas/Notifications/Views/_ViewStart.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.Notifications\Areas\Notifications\Views\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.Notifications\Areas\Notifications\Views\_ViewImports.cshtml"
using Microsoft.AspNetCore.Mvc.Localization;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7091c65830b0329e613be026ede8a57552863778", @"/Areas/Notifications/Views/_ViewStart.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"252a5853f5646565b6d19f2f67b215e8a2ab4af3", @"/Areas/Notifications/Views/_ViewImports.cshtml")]
public class Areas_Notifications_Views__ViewStart : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic>
{
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 1 "D:\CodingWork\Projects\NongMinGoProject\SimplCommerce\src\Modules\SimplCommerce.Module.Notifications\Areas\Notifications\Views\_ViewStart.cshtml"
Layout = "_Layout";
#line default
#line hidden
#nullable disable
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public IViewLocalizer Localizer { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; }
}
}
#pragma warning restore 1591
| 54.262295 | 247 | 0.786405 | [
"Apache-2.0"
] | Coopathon2019/03_NongMinGo | src/Modules/SimplCommerce.Module.Notifications/obj/Debug/netcoreapp3.0/Razor/Areas/Notifications/Views/_ViewStart.cshtml.g.cs | 3,310 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Data;
using System.Data.SqlClient;
using CodeHelperLibrary.Object;
namespace CodeHelperLibrary
{
public class SQLHelper
{
public List<SQLObject> Generate(string connection,string query,string name)
{
using (IDbConnection db = new SqlConnection("Data Source=.;Initial Catalog=MessageXpress Dispatch;Integrated Security=True;MultipleActiveResultSets=true"))
{
//return db.Query<SQLObject>
//().ToList();
// db.QueryMultiple
int index = query.IndexOf("FROM ");
if(index<0)
index = query.IndexOf("from ");
if (index < 0)
index = query.IndexOf("From ");
query = query.Insert(index, " INTO #temp ");
var sql = @" IF OBJECT_ID('tempdb..#temp') IS NOT NULL
DROP TABLE #temp; "+ query+@"
EXEC tempdb.dbo.sp_help N'#temp';
drop table #temp; ";
using (var multi = db.QueryMultiple(sql, new { InvoiceID = 1 }))
{
var sqlobject = multi.Read<SQLObject>();
var sqlobject2 = multi.Read<SQLObject>();
return sqlobject2.ToList();
;
// var invoiceItems = multi.Read<InvoiceItem>().ToList();
}
return null;
}
}
}
}
| 33.55102 | 167 | 0.509732 | [
"Apache-2.0"
] | vishaletm/SQL-Generate-POCO | CodeHelper/CodeHelperLibrary/SQLHelper.cs | 1,646 | C# |
using System;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using BroadWorksConnector.Ocip.Validation;
using System.Collections.Generic;
namespace BroadWorksConnector.Ocip.Models
{
/// <summary>
/// Response to the EnterpriseCallCenterAgentThresholdProfileGetListRequest.
/// Contains a table with all the Call Center Agent Threshold Profiles in the Enterprise.
/// The column headings are: "Default", "Name", "Description".
/// <see cref="EnterpriseCallCenterAgentThresholdProfileGetListRequest"/>
/// </summary>
[Serializable]
[XmlRoot(Namespace = "")]
[Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""e2c537e3e39483b96620673a7012ffdd:569""}]")]
public class EnterpriseCallCenterAgentThresholdProfileGetListResponse : BroadWorksConnector.Ocip.Models.C.OCIDataResponse
{
private BroadWorksConnector.Ocip.Models.C.OCITable _profilesTable;
[XmlElement(ElementName = "profilesTable", IsNullable = false, Namespace = "")]
[Group(@"e2c537e3e39483b96620673a7012ffdd:569")]
public BroadWorksConnector.Ocip.Models.C.OCITable ProfilesTable
{
get => _profilesTable;
set
{
ProfilesTableSpecified = true;
_profilesTable = value;
}
}
[XmlIgnore]
protected bool ProfilesTableSpecified { get; set; }
}
}
| 35.439024 | 129 | 0.687543 | [
"MIT"
] | Rogn/broadworks-connector-net | BroadworksConnector/Ocip/Models/EnterpriseCallCenterAgentThresholdProfileGetListResponse.cs | 1,453 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightBulbsStore.Core.Models.Order
{
public class OrderProductViewModel
{
public string ProductId { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public string CategoryName { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public decimal TotalProductPrice { get; set; }
}
}
| 20.185185 | 54 | 0.649541 | [
"MIT"
] | tedoff56/ASP.NET-Core-SoftUni-Project | LightBulbsStore/LightBulbsStore.Core/Models/Order/OrderProductViewModel.cs | 547 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/WbemCli.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
/// <include file='WbemRefresher.xml' path='doc/member[@name="WbemRefresher"]/*' />
[Guid("C71566F2-561E-11D1-AD87-00C04FD8FDFF")]
public partial struct WbemRefresher
{
}
| 35.466667 | 145 | 0.766917 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/WbemCli/WbemRefresher.cs | 534 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _151024D
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("podaj temperature w celsjuszach");
double celsjusz;
celsjusz=(Convert.ToDouble(Console.ReadLine()));
double konwersja=0;
konwersja = (celsjusz * 1.8) + 32;
Console.Write("temperatura przed konwersja:");
Console.WriteLine(celsjusz);
Console.Write("temperatura po konwersji:");
Console.WriteLine(konwersja);
Console.ReadLine();
}
}
}
| 23.21875 | 66 | 0.559892 | [
"MIT"
] | Parabent/OOP2019 | Program.cs | 745 | C# |
using TumblThree.Applications.Services;
using TumblThree.Domain.Models;
namespace TumblThree.Applications.Downloader
{
public interface IDownloaderFactory
{
IDownloader GetDownloader(BlogTypes blogTypes);
IDownloader GetDownloader(BlogTypes blogTypes, IShellService shellService, ICrawlerService crawlerService, IBlog blog);
}
}
| 27.692308 | 127 | 0.786111 | [
"Apache-2.0",
"MIT"
] | vaginessa/TumblThree | src/TumblThree/TumblThree.Applications/Downloader/IDownloaderFactory.cs | 362 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Vote
{
public class Program
{
public static void Main(string[] args)
{
try
{
CreateHostBuilder(args).Build().Run();
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 24.514286 | 70 | 0.576923 | [
"MIT"
] | AlecPapierniak/tye | samples/azure-functions/voting/vote/Program.cs | 860 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V6301 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT140701UK03.PertinentInformation", Namespace="urn:hl7-org:v3")]
public partial class UKCT_MT140701UK03PertinentInformation {
private BL seperatableIndField;
private UKCT_MT140701UK03AdministrationDetails pertinentAdministrationDetailsField;
private string typeField;
private string typeCodeField;
private bool contextConductionIndField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public UKCT_MT140701UK03PertinentInformation() {
this.typeField = "ActRelationship";
this.typeCodeField = "PERT";
this.contextConductionIndField = true;
}
public BL seperatableInd {
get {
return this.seperatableIndField;
}
set {
this.seperatableIndField = value;
}
}
public UKCT_MT140701UK03AdministrationDetails pertinentAdministrationDetails {
get {
return this.pertinentAdministrationDetailsField;
}
set {
this.pertinentAdministrationDetailsField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string typeCode {
get {
return this.typeCodeField;
}
set {
this.typeCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool contextConductionInd {
get {
return this.contextConductionIndField;
}
set {
this.contextConductionIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT140701UK03PertinentInformation));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current UKCT_MT140701UK03PertinentInformation object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an UKCT_MT140701UK03PertinentInformation object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output UKCT_MT140701UK03PertinentInformation object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out UKCT_MT140701UK03PertinentInformation obj, out System.Exception exception) {
exception = null;
obj = default(UKCT_MT140701UK03PertinentInformation);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out UKCT_MT140701UK03PertinentInformation obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static UKCT_MT140701UK03PertinentInformation Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((UKCT_MT140701UK03PertinentInformation)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current UKCT_MT140701UK03PertinentInformation object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an UKCT_MT140701UK03PertinentInformation object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output UKCT_MT140701UK03PertinentInformation object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out UKCT_MT140701UK03PertinentInformation obj, out System.Exception exception) {
exception = null;
obj = default(UKCT_MT140701UK03PertinentInformation);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out UKCT_MT140701UK03PertinentInformation obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static UKCT_MT140701UK03PertinentInformation LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this UKCT_MT140701UK03PertinentInformation object
/// </summary>
public virtual UKCT_MT140701UK03PertinentInformation Clone() {
return ((UKCT_MT140701UK03PertinentInformation)(this.MemberwiseClone()));
}
#endregion
}
}
| 41.200692 | 1,358 | 0.579743 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V6301/Generated/UKCT_MT140701UK03PertinentInformation.cs | 11,907 | C# |
// Decompiled with JetBrains decompiler
// Type: SynapseGaming.LightingSystem.Effects.BaseSkinnedEffect
// Assembly: SynapseGaming-SunBurn-Pro, Version=1.3.2.8, Culture=neutral, PublicKeyToken=c23c60523565dbfd
// MVID: A5F03349-72AC-4BAA-AEEE-9AB9B77E0A39
// Assembly location: C:\Projects\BlackBox\StarDrive\SynapseGaming-SunBurn-Pro.dll
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace SynapseGaming.LightingSystem.Effects
{
/// <summary>Provides basic skinned animation rendering support.</summary>
public abstract class BaseSkinnedEffect : BaseRenderableEffect, ISkinnedEffect
{
private Matrix[] SkinBonesCache = new Matrix[1];
private bool IsSkinned;
private Matrix[] SkinBonesArray;
private EffectParameter SkinBonesParam;
/// <summary>
/// Array of bone transforms for the skeleton's current pose. The matrix index is the
/// same as the bone order used in the model or vertex buffer.
/// </summary>
public Matrix[] SkinBones
{
get => SkinBonesArray;
set
{
if (value != null)
{
_UpdatedByBatch = true;
EffectHelper.Update(value, ref SkinBonesArray, ref SkinBonesParam);
}
else
{
if (!IsSkinned || SkinBonesParam == null)
return;
if (SkinBonesCache.Length < SkinBonesParam.Elements.Count)
{
SkinBonesCache = new Matrix[SkinBonesParam.Elements.Count];
for (int index = 0; index < SkinBonesCache.Length; ++index)
SkinBonesCache[index] = Matrix.Identity;
}
if (SkinBonesArray != SkinBonesCache)
{
_UpdatedByBatch = true;
SkinBonesArray = SkinBonesCache;
SkinBonesParam.SetArrayRange(0, SkinBonesArray.Length);
SkinBonesParam.SetValue(SkinBonesArray);
}
}
}
}
/// <summary>
/// Determines if the effect is currently rendering skinned objects.
/// </summary>
public bool Skinned
{
get => IsSkinned;
set
{
if (value == IsSkinned)
return;
IsSkinned = value;
SetTechnique();
if (!IsSkinned || SkinBonesArray != null)
return;
SkinBones = null;
}
}
internal BaseSkinnedEffect(GraphicsDevice device, string effectName) : base(device, effectName)
{
SkinBonesParam = Parameters["_SkinBones"];
}
}
}
| 36.888889 | 106 | 0.525435 | [
"MIT"
] | UnGaucho/StarDrive | SynapseGaming-SunBurn-Pro/SynapseGaming/LightingSystem/Effects/BaseSkinnedEffect.cs | 2,990 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using NetworkPrimitives.Utilities;
namespace NetworkPrimitives.Ipv4
{
/// <summary>
/// Represents an IPv4 Subnet
/// </summary>
public readonly struct Ipv4Subnet : INetworkPrimitive<Ipv4Subnet>
{
/// <summary>
/// The network address of the subnet
/// </summary>
public Ipv4Address NetworkAddress { get; }
/// <summary>
/// The subnet mask
/// </summary>
public Ipv4SubnetMask Mask { get; }
/// <summary>
/// The subnet mask, in CIDR notation
/// </summary>
public Ipv4Cidr Cidr => Mask.ToCidr();
/// <summary>
/// Create a subnet with an <see cref="Ipv4Address"/> and <see cref="Ipv4SubnetMask"/>
/// </summary>
/// <param name="address">An IP address</param>
/// <param name="mask">A subnet mask</param>
public Ipv4Subnet(Ipv4Address address, Ipv4SubnetMask mask)
{
this.NetworkAddress = address & mask;
this.Mask = mask;
}
/// <summary>
/// Create a subnet with an <see cref="Ipv4Address"/> and <see cref="Ipv4Cidr"/>
/// </summary>
/// <param name="address">An IP address</param>
/// <param name="cidr">A CIDR</param>
public Ipv4Subnet(Ipv4Address address, Ipv4Cidr cidr) : this(address, cidr.ToSubnetMask())
{
}
/// <summary>
/// Deconstruct an <see cref="Ipv4Subnet"/> into an <see cref="Ipv4Address"/>, <see cref="Ipv4SubnetMask"/>, and <see cref="Ipv4Cidr"/>
/// </summary>
/// <param name="networkAddress">The network address</param>
/// <param name="mask">The subnet mask</param>
/// <param name="cidr">The CIDR</param>
public void Deconstruct(out Ipv4Address networkAddress, out Ipv4SubnetMask mask, out Ipv4Cidr cidr)
{
networkAddress = this.NetworkAddress;
mask = this.Mask;
cidr = this.Cidr;
}
/// <summary>
/// Deconstruct an <see cref="Ipv4Subnet"/> into an <see cref="Ipv4Address"/> and <see cref="Ipv4SubnetMask"/>
/// </summary>
/// <param name="networkAddress">The network address</param>
/// <param name="mask">The subnet mask</param>
public void Deconstruct(out Ipv4Address networkAddress, out Ipv4SubnetMask mask)
{
networkAddress = this.NetworkAddress;
mask = this.Mask;
}
#region Subnetting
/// <summary>
/// The total number of hosts allowed by this <see cref="Ipv4Cidr"/>.
/// Includes the broadcast and network addresses.
/// </summary>
public ulong TotalHosts => Mask.TotalHosts;
/// <summary>
/// The number of usable hosts allowed by this <see cref="Ipv4Cidr"/>.
/// Does not include the broadcast or network address.
/// RFC 3021 states that for a /31 network, the number of usable hosts is 2.
/// The number of usable hosts for a /32 network is 1.
/// </summary>
/// <seealso href="https://datatracker.ietf.org/doc/html/rfc3021">RFC3021</seealso>
public uint UsableHosts => Mask.UsableHosts;
/// <summary>
/// The broadcast address of the subnet.
/// </summary>
public Ipv4Address BroadcastAddress => Mask.Value switch
{
0xFFFFFFFF => this.NetworkAddress,
0xFFFFFFFE => this.NetworkAddress.AddInternal(1),
_ => NetworkAddress.AddInternal((uint)(Mask.TotalHosts - 1)),
};
/// <summary>
/// The first usable address in the subnet.
/// </summary>
/// <remarks>
/// This property respects RFC 3021.
/// </remarks>
/// <seealso href="https://datatracker.ietf.org/doc/html/rfc3021">RFC3021</seealso>
public Ipv4Address FirstUsable => Mask.Value switch
{
0xFFFFFFFF => this.NetworkAddress,
0xFFFFFFFE => this.NetworkAddress,
_ => this.NetworkAddress.AddInternal(1),
};
/// <summary>
/// The last usable address in the subnet.
/// </summary>
/// <remarks>
/// This property respects RFC 3021.
/// </remarks>
/// <seealso href="https://datatracker.ietf.org/doc/html/rfc3021">RFC3021</seealso>
public Ipv4Address LastUsable => Mask.Value switch
{
0xFFFFFFFF => this.NetworkAddress,
0xFFFFFFFE => this.NetworkAddress.AddInternal(1),
_ => NetworkAddress.AddInternal((uint)(Mask.TotalHosts - 2)),
};
/// <summary>
/// Calculate the largest subnet that contains all of the given subnets
/// </summary>
/// <param name="subnets">
/// A collection of subnets to supernet.
/// </param>
/// <returns>
/// A subnet that contains all of the subnets in the collection <paramref name="subnets"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(params Ipv4Subnet[] subnets)
=> SubnetOperations.GetContainingSupernet(subnets);
/// <summary>
/// Calculate the largest subnet that contains all of the given subnets
/// </summary>
/// <param name="subnets">
/// A collection of subnets to supernet.
/// </param>
/// <returns>
/// A subnet that contains all of the subnets in the collection <paramref name="subnets"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(IEnumerable<Ipv4Subnet> subnets)
=> SubnetOperations.GetContainingSupernet(subnets);
/// <summary>
/// Calculate the largest subnet that contains all of the given subnets
/// </summary>
/// <param name="a">
/// The first subnet
/// </param>
/// <param name="b">
/// The second subnet
/// </param>
/// <returns>
/// A subnet that contains subnets <paramref name="a"/> and <paramref name="b"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(Ipv4Subnet a, Ipv4Subnet b)
=> SubnetOperations.GetContainingSupernet(a, b);
/// <summary>
/// Calculate the largest subnet that contains all of the given subnets
/// </summary>
/// <param name="a">
/// The first subnet
/// </param>
/// <param name="b">
/// The second subnet
/// </param>
/// <param name="c">
/// The second subnet
/// </param>
/// <returns>
/// A subnet that contains subnets <paramref name="a"/>, <paramref name="b"/>, and <paramref name="c"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(Ipv4Subnet a, Ipv4Subnet b, Ipv4Subnet c)
=> SubnetOperations.GetContainingSupernet(a, SubnetOperations.GetContainingSupernet(b, c));
/// <summary>
/// Calculate the largest subnet that contains all of the given addresses
/// </summary>
/// <param name="addresses">
/// A collection of addresses to supernet.
/// </param>
/// <returns>
/// A subnet that contains all of the addresses in the collection <paramref name="addresses"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(params Ipv4Address[] addresses)
=> SubnetOperations.GetContainingSupernet(addresses);
/// <summary>
/// Calculate the largest subnet that contains all of the given addresses
/// </summary>
/// <param name="addresses">
/// A collection of addresses to supernet.
/// </param>
/// <returns>
/// A subnet that contains all of the addresses in the collection <paramref name="addresses"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(IEnumerable<Ipv4Address> addresses)
=> SubnetOperations.GetContainingSupernet(addresses);
/// <summary>
/// Calculate the largest subnet that contains all of the given addresses
/// </summary>
/// <param name="a">
/// The first address
/// </param>
/// <param name="b">
/// The second address
/// </param>
/// <returns>
/// A subnet that contains addresses <paramref name="a"/> and <paramref name="b"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(Ipv4Address a, Ipv4Address b)
=> SubnetOperations.GetContainingSupernet(a, b);
/// <summary>
/// Calculate the largest subnet that contains all of the given addresses
/// </summary>
/// <param name="a">
/// The first address
/// </param>
/// <param name="b">
/// The second address
/// </param>
/// <param name="c">
/// The second address
/// </param>
/// <returns>
/// A subnet that contains addresses <paramref name="a"/>, <paramref name="b"/>, and <paramref name="c"/>
/// </returns>
public static Ipv4Subnet GetContainingSupernet(Ipv4Address a, Ipv4Address b, Ipv4Address c)
=> SubnetOperations.GetContainingSupernet(a, SubnetOperations.GetContainingSupernet(b, c));
/// <summary>
/// Determine if a given <see cref="Ipv4Address"/> is part of this <see cref="Ipv4Subnet"/> instance.
/// </summary>
/// <param name="address">
/// The address to check.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="address"/> is contained within this instance, otherwise, <see langword="false"/>
/// </returns>
public bool Contains(Ipv4Address address) => (address & this.Mask) == NetworkAddress;
/// <summary>
/// Determine if a given <see cref="Ipv4Subnet"/> is part of this <see cref="Ipv4Subnet"/> instance.
/// </summary>
/// <param name="subnet">
/// The subnet to check.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="subnet"/> is entirely contained within this instance, otherwise, <see langword="false"/>
/// </returns>
public bool Contains(Ipv4Subnet subnet)
{
if (subnet.Mask.ToCidr() < this.Mask.ToCidr())
return false;
return (subnet.NetworkAddress & this.Mask) == (this.NetworkAddress & this.Mask);
}
/// <summary>
/// Attempt to split this subnet into two smaller subnets.
/// </summary>
/// <param name="low">
/// If successful, an <see cref="Ipv4Subnet"/> that is exactly one half the size of this instance,
/// with a network address the same as this instance's network address.
/// </param>
/// <param name="high">
/// If successful, an <see cref="Ipv4Subnet"/> that is exactly one half the size of this instance,
/// with a broadcast address the same as this instance's broadcast address.
/// </param>
/// <returns>
/// <see langword="true"/> if successful.
/// This method will only fail if this subnet's subnet mask is 255.255.255.255 (or 32 in CIDR notation).
/// </returns>
public bool TrySplit(out Ipv4Subnet low, out Ipv4Subnet high)
{
low = default;
high = default;
var cidr = Mask.ToCidr();
if (cidr.Value == 32) return false;
var highAddress = NetworkAddress.AddInternal((uint)(TotalHosts / 2));
cidr = Ipv4Cidr.Parse((byte)(cidr.Value + 1));
low = new (NetworkAddress, cidr);
high = new (highAddress, cidr);
return true;
}
/// <summary>
/// Attempt to get the parent subnet of this subnet.
/// </summary>
/// <param name="parentSubnet">
/// If successful, an <see cref="Ipv4Subnet"/> that is exactly twice the size of this instance,
/// with a network address the same as this instance's network address.
/// </param>
/// <returns>
/// <see langword="true"/> if successful.
/// This method will only fail if this subnet's subnet mask is 0.0.0.0 (or 0 in CIDR notation).
/// </returns>
public bool TryGetParentSubnet(out Ipv4Subnet parentSubnet)
=> SubnetOperations.TryGetParent(this, out parentSubnet);
/// <summary>
/// Attempt to subnet this instance into a given number of subnets, all of equal size.
/// </summary>
/// <param name="numberOfNetworks">
/// The number of equal-sized subnets to create
/// </param>
/// <param name="subnets">
/// If successful, a list containing <i>at least</i> <paramref name="numberOfNetworks"/> instances of
/// <see cref="Ipv4Subnet"/>, all of equal size.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
public bool TrySubnetBasedOnCount(uint numberOfNetworks, [NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets)
=> SubnetOperations.TrySubnetBasedOnCount(this, numberOfNetworks, out subnets);
/// <summary>
/// Attempt to subnet this instance into a given number of subnets, all of equal size.
/// </summary>
/// <param name="numberOfNetworks">
/// The number of equal-sized subnets to create
/// </param>
/// <param name="subnets">
/// If successful, a list containing <i>at least</i> <paramref name="numberOfNetworks"/> instances of
/// <see cref="Ipv4Subnet"/>, all of equal size.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="numberOfNetworks"/> is negative.
/// </exception>
public bool TrySubnetBasedOnCount(int numberOfNetworks, [NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets)
{
if (numberOfNetworks < 0) throw new ArgumentOutOfRangeException(nameof(numberOfNetworks));
return SubnetOperations.TrySubnetBasedOnCount(this, (uint)numberOfNetworks, out subnets);
}
/// <summary>
/// Attempt to subnet this instance into a given number of subnets, all of equal size.
/// </summary>
/// <param name="sizeOfSubnets">
/// The minimum size of the subnets to create
/// </param>
/// <param name="subnets">
/// If successful, a list containing one or more subnets, each containing <i>at least</i>
/// <paramref name="sizeOfSubnets"/> usable IP addresses.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
public bool TrySubnetBasedOnSize(Ipv4SubnetMask sizeOfSubnets, [NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets)
=> SubnetOperations.TrySubnetBasedOnSize(this, sizeOfSubnets, out subnets);
/// <summary>
/// Attempt to subnet this instance into a given number of subnets, all of equal size.
/// </summary>
/// <param name="sizeOfSubnets">
/// The minimum size of the subnets to create
/// </param>
/// <param name="subnets">
/// If successful, a list containing one or more subnets, each containing <i>at least</i>
/// <paramref name="sizeOfSubnets"/> usable IP addresses.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
public bool TrySubnetBasedOnSize(Ipv4Cidr sizeOfSubnets, [NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets)
=> SubnetOperations.TrySubnetBasedOnSize(this, sizeOfSubnets, out subnets);
/// <summary>
/// Attempt to subnet this instance into a given number of subnets, all of equal size.
/// </summary>
/// <param name="sizeOfSubnets">
/// The minimum size of the subnets to create
/// </param>
/// <param name="subnets">
/// If successful, a list containing one or more subnets, each containing <i>at least</i>
/// <paramref name="sizeOfSubnets"/> usable IP addresses.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
public bool TrySubnetBasedOnSize(uint sizeOfSubnets, [NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets)
=> SubnetOperations.TrySubnetBasedOnSize(this, sizeOfSubnets, out subnets);
/// <summary>
/// Attempt to subnet this instance into a given number of subnets, all of equal size.
/// </summary>
/// <param name="sizeOfSubnets">
/// The minimum size of the subnets to create
/// </param>
/// <param name="subnets">
/// If successful, a list containing one or more subnets, each containing <i>at least</i>
/// <paramref name="sizeOfSubnets"/> usable IP addresses.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// If <paramref name="sizeOfSubnets"/> is negative.
/// </exception>
public bool TrySubnetBasedOnSize(int sizeOfSubnets, [NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets)
{
if (sizeOfSubnets < 0) throw new ArgumentOutOfRangeException(nameof(sizeOfSubnets));
return SubnetOperations.TrySubnetBasedOnSize(this, (uint)sizeOfSubnets, out subnets);
}
/// <summary>
/// Attempt to subnet this instance into multiple appropriate-sized subnets.
/// </summary>
/// <param name="subnets">
/// If successful, a list containing the subnets. It will contain at least one subnet for each item in
/// <paramref name="numberOfHosts"/> (possibly with some additional subnets).
/// </param>
/// <param name="numberOfHosts">
/// An array that represents the networks to create. Each element contains he number of usable hosts to place in each subnet.
/// </param>
/// <returns>
/// <see langword="true"/> if the subnetting was successful, <see langword="false"/> if not successful.
/// </returns>
public bool TryVariableLengthSubnet(
[NotNullWhen(true)] out IReadOnlyList<Ipv4Subnet>? subnets,
params uint[] numberOfHosts
) => SubnetOperations.TryVariableLengthSubnet(this, numberOfHosts, out subnets);
#endregion Subnetting
#region Formatting
int ITryFormat.MaximumLengthRequired => Ipv4Address.MAXIMUM_LENGTH * 2 + 1;
/// <summary>
/// Converts an <see cref="Ipv4Subnet"/> to its <see cref="string"/> representation (in CIDR notation)
/// </summary>
/// <returns>
/// A string that contains this subnet in CIDR notation
/// </returns>
public override string ToString() => this.GetString();
/// <summary>
/// Tries to format the current subnet into the provided span.
/// </summary>
/// <param name="destination">
/// When this method returns, the subnet, as a span of characters.
/// </param>
/// <param name="charsWritten">
/// When this method returns, the number of characters written into the span.
/// </param>
/// <returns>
/// <see langword="true"/> if the formatting was successful; otherwise, <see langword="false"/>.
/// </returns>
public bool TryFormat(Span<char> destination, out int charsWritten)
=> Ipv4Formatting.TryFormat(this, destination, out charsWritten, null, null);
#endregion Formatting
#region Equality
/// <summary>
/// Returns a value indicating whether this instance is equal to a specified <see cref="Ipv4Subnet"/>.
/// </summary>
/// <param name="obj">
/// A value to compare to this instance.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="obj"/> is an instance of <see cref="Ipv4Subnet"/> and
/// equals the value of this instance; otherwise, <see langword="false"/>.
/// </returns>
public override bool Equals(object? obj) => obj is Ipv4Subnet other && Equals(other);
/// <summary>
/// Returns a value indicating whether this instance is equal to a specified <see cref="Ipv4Subnet"/>.
/// </summary>
/// <param name="other">
/// A value to compare to this instance.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="other"/> has the same value as this instance; otherwise, <see langword="false"/>.
/// </returns>
public bool Equals(Ipv4Subnet other) => this.NetworkAddress.Equals(other.NetworkAddress) && this.Mask.Equals(other.Mask);
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer hash code.
/// </returns>
public override int GetHashCode() => HashCode.Combine(this.NetworkAddress, this.Mask);
/// <summary>
/// Returns a value indicating whether two instances of <see cref="Ipv4Subnet"/> are equal.
/// </summary>
/// <param name="left">
/// The first <see cref="Ipv4Subnet"/> to compare.
/// </param>
/// <param name="right">
/// The second <see cref="Ipv4Subnet"/> to compare.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> are equal; otherwise <see langword="false"/>.
/// </returns>
public static bool operator ==(Ipv4Subnet left, Ipv4Subnet right) => left.Equals(right);
/// <summary>
/// Returns a value indicating whether two instances of <see cref="Ipv4Subnet"/> are not equal.
/// </summary>
/// <param name="left">
/// The first <see cref="Ipv4Subnet"/> to compare.
/// </param>
/// <param name="right">
/// The second <see cref="Ipv4Subnet"/> to compare.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> are not equal; otherwise <see langword="false"/>.
/// </returns>
public static bool operator !=(Ipv4Subnet left, Ipv4Subnet right) => !left.Equals(right);
#endregion Equality
#region Enumeration
/// <summary>
/// Create an instance of <see cref="Ipv4AddressRange"/> that reflects the usable addresses in this subnet.
/// </summary>
/// <returns>
/// An instance of <see cref="Ipv4AddressRange"/> that reflects the usable addresses in this subnet.
/// </returns>
/// <remarks>
/// This method respects RFC 3021.
/// </remarks>
/// <seealso href="https://datatracker.ietf.org/doc/html/rfc3021">RFC3021</seealso>
public Ipv4AddressRange GetUsableAddresses() => new(this.FirstUsable, this.UsableHosts - 1);
/// <summary>
/// Create an instance of <see cref="Ipv4AddressRange"/> that reflects all addresses in this subnet.
/// </summary>
/// <returns>
/// An instance of <see cref="Ipv4AddressRange"/> that reflects all addresses in this subnet.
/// </returns>
public Ipv4AddressRange GetAllAddresses() => new (NetworkAddress, (uint)(TotalHosts - 1));
#endregion Enumeration
#region Parse
/// <summary>
/// Parse a subnet into an <see cref="Ipv4Subnet"/> instance.
/// </summary>
/// <param name="address">
/// A string that contains an IPv4 address in dotted decimal form.
/// </param>
/// <param name="mask">
/// A string that contains a subnet mask in dotted decimal form.
/// </param>
/// <returns>
/// An <see cref="Ipv4Subnet"/> instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// <paramref name="mask"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="FormatException">
/// <paramref name="address"/> is not a valid IPv4 address.
/// <paramref name="mask"/> is not a valid IPv4 subnet mask.
/// </exception>
public static Ipv4Subnet Parse(string? address, string? mask)
{
address = address ?? throw new ArgumentNullException(nameof(address));
mask = mask ?? throw new ArgumentNullException(nameof(mask));
return Ipv4Subnet.TryParse(address, mask, out var result)
? result
: throw new FormatException();
}
/// <summary>
/// Parse a subnet into an <see cref="Ipv4Subnet"/> instance.
/// </summary>
/// <param name="address">
/// A string that contains an IPv4 address in dotted decimal form.
/// </param>
/// <param name="cidr">
/// An IPv4 CIDR string that contains a subnet mask in dotted decimal form.
/// </param>
/// <returns>
/// An <see cref="Ipv4Subnet"/> instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="address"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="FormatException">
/// <paramref name="address"/> is not a valid IPv4 address.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="cidr"/> is not a valid IPv4 CIDR.
/// </exception>
public static Ipv4Subnet Parse(string? address, int cidr)
{
address = address ?? throw new ArgumentNullException(nameof(address));
if (!Ipv4Address.TryParse(address, out var add))
throw new FormatException();
if (cidr is < 0 or > 32)
throw new ArgumentOutOfRangeException(nameof(cidr));
return new (add, Ipv4Cidr.Parse(cidr));
}
/// <summary>
/// Parse a subnet into an <see cref="Ipv4Subnet"/> instance.
/// </summary>
/// <param name="text">
/// A string that contains a subnet in any of the supported formats (see examples).
/// </param>
/// <returns>
/// An <see cref="Ipv4Subnet"/> instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="text"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="FormatException">
/// <paramref name="text"/> is not a valid <see cref="Ipv4Subnet"/>.
/// </exception>
/// <example>10.0.0.0/24</example>
/// <example>10.0.0.5</example>
/// <example>10.0.0.0 255.255.255.0</example>
public static Ipv4Subnet Parse(string? text)
{
text = text ?? throw new ArgumentNullException(nameof(text));
return Ipv4Subnet.TryParse(text, out var result)
? result
: throw new FormatException();
}
/// <summary>
/// Parse a subnet into an <see cref="Ipv4Subnet"/> instance.
/// </summary>
/// <param name="text">
/// A span that contains a subnet in any of the supported formats (see examples).
/// </param>
/// <returns>
/// An <see cref="Ipv4Subnet"/> instance.
/// </returns>
/// <exception cref="FormatException">
/// <paramref name="text"/> is not a valid <see cref="Ipv4Subnet"/>.
/// </exception>
/// <example>10.0.0.0/24</example>
/// <example>10.0.0.5</example>
/// <example>10.0.0.0 255.255.255.0</example>
public static Ipv4Subnet Parse(ReadOnlySpan<char> text)
=> Ipv4Subnet.TryParse(text, out var result)
? result
: throw new FormatException();
private static bool ParseExact(Ipv4Address address, out Ipv4Subnet result, out bool implicitSlash32)
{
result = new (address, Ipv4Cidr.Parse(32));
implicitSlash32 = true;
return true;
}
#endregion Parse
#region TryParse
/// <summary>
/// Determines whether the specified character span represents a valid IPv4 subnet.
/// </summary>
/// <param name="text">
/// The character span to validate.
/// </param>
/// <param name="charsRead">
/// The length of the valid Ipv4 subnet.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> was able to be parsed as an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
///
/// If <paramref name="text"/> begins with a valid <see cref="Ipv4Subnet"/>, and is followed by other characters, this method will
/// return <see langword="true"/>. <paramref name="charsRead"/> will contain the length of the valid <see cref="Ipv4Subnet"/>.
/// </returns>
public static bool TryParse(ReadOnlySpan<char> text, out int charsRead, out Ipv4Subnet result)
=> TryParse(text, out charsRead, out result, out _);
/// <summary>
/// Determines whether the specified character span represents a valid IPv4 subnet.
/// </summary>
/// <param name="text">
/// The character span to validate.
/// </param>
/// <param name="charsRead">
/// The length of the valid Ipv4 subnet.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <param name="implicitSlash32">
/// <see langword="true"/> if <paramref name="text"/> contained a valid IPv4 address, with no subnet mask or CIDR.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> was able to be parsed as an IP address; otherwise, <see langword="false"/>.
///
/// If <paramref name="text"/> begins with a valid <see cref="Ipv4Subnet"/>, and is followed by other characters, this method will
/// return <see langword="true"/>. <paramref name="charsRead"/> will contain the length of the valid <see cref="Ipv4Subnet"/>.
/// </returns>
public static bool TryParse(ReadOnlySpan<char> text, out int charsRead, out Ipv4Subnet result, out bool implicitSlash32)
{
charsRead = default;
return Ipv4Subnet.TryParseInternal(ref text, ref charsRead, out result, out implicitSlash32);
}
/// <summary>
/// Determines whether the specified character span represents a valid IPv4 subnet.
/// </summary>
/// <param name="text">
/// The character span to validate.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> was able to be parsed as an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool TryParse(ReadOnlySpan<char> text, out Ipv4Subnet result)
=> TryParse(text, out result, out _);
/// <summary>
/// Determines whether the specified character span represents a valid IPv4 subnet.
/// </summary>
/// <param name="text">
/// The character span to validate.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <param name="implicitSlash32">
/// <see langword="true"/> if <paramref name="text"/> contained a valid IPv4 address, with no subnet mask or CIDR.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> was able to be parsed as an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool TryParse(ReadOnlySpan<char> text, out Ipv4Subnet result, out bool implicitSlash32)
=> TryParse(text, out var charsRead, out result, out implicitSlash32) && charsRead == text.Length;
private static bool TryParseWithCidr(ref ReadOnlySpan<char> text, ref int charsRead, Ipv4Address address, out Ipv4Subnet result)
{
result = default;
var textCopy = text;
var charsReadCopy = charsRead;
if (!textCopy.TryReadCharacter(ref charsReadCopy, '/'))
return false;
if (!Ipv4Cidr.TryParse(ref textCopy, ref charsReadCopy, out var cidr))
return false;
result = new (address, cidr);
charsRead = charsReadCopy;
text = textCopy;
return true;
}
private static bool TryParseWithMask(ref ReadOnlySpan<char> text, ref int charsRead, Ipv4Address address, out Ipv4Subnet result)
{
result = default;
var textCopy = text;
var charsReadCopy = charsRead;
if (!textCopy.TryReadCharacter(ref charsReadCopy, ' '))
return false;
if (!Ipv4SubnetMask.TryParse(ref textCopy, ref charsReadCopy, out var mask))
return false;
result = new (address, mask);
charsRead = charsReadCopy;
text = textCopy;
return true;
}
/// <summary>
/// Determines whether the specified string represents a valid IPv4 subnet.
/// </summary>
/// <param name="address">
/// The string to validate.
/// </param>
/// <param name="cidr">
/// An IPv4 CIDR.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="address"/> and <paramref name="cidr"/> were able to be
/// parsed into an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool TryParse(string? address, int cidr, out Ipv4Subnet result)
{
result = default;
if (!Ipv4Address.TryParse(address, out var parsedAddress))
return false;
if (!Ipv4Cidr.TryParse(cidr, out var parsedCidr))
return false;
result = new Ipv4Subnet(parsedAddress, parsedCidr);
return true;
}
/// <summary>
/// Determines whether the specified string represents a valid IPv4 subnet.
/// </summary>
/// <param name="address">
/// The string to validate.
/// </param>
/// <param name="maskOrCidr">
/// A subnet mask in dotted decimal notation, or a valid IPv4 CIDR.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="address"/> and <paramref name="maskOrCidr"/> were able to be
/// parsed into an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool TryParse(string? address, string? maskOrCidr, out Ipv4Subnet result)
{
result = default;
if (!Ipv4Address.TryParse(address, out var parsedAddress))
return false;
if (Ipv4SubnetMask.TryParse(maskOrCidr, out var mask))
{
result = new Ipv4Subnet(parsedAddress, mask);
return true;
}
if (!Ipv4Cidr.TryParse(maskOrCidr, out var cidr))
return false;
result = new Ipv4Subnet(parsedAddress, cidr);
return true;
}
/// <summary>
/// Determines whether the specified string represents a valid IPv4 subnet.
/// </summary>
/// <param name="text">
/// The string to validate.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> was able to be parsed as an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
/// </returns>
public static bool TryParse(string? text, out Ipv4Subnet result)
=> Ipv4Subnet.TryParseInternal(text, out _, out result, out _);
/// <summary>
/// Determines whether the specified string represents a valid IPv4 subnet.
/// </summary>
/// <param name="text">
/// The string to validate.
/// </param>
/// <param name="charsRead">
/// The length of the valid Ipv4 subnet.
/// </param>
/// <param name="result">
/// The <see cref="Ipv4Subnet"/> version of the character span.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="text"/> was able to be parsed as an <see cref="Ipv4Subnet"/>; otherwise, <see langword="false"/>.
///
/// If <paramref name="text"/> begins with a valid <see cref="Ipv4Subnet"/>, and is followed by other characters, this method will
/// return <see langword="true"/>. <paramref name="charsRead"/> will contain the length of the valid <see cref="Ipv4Subnet"/>.
/// </returns>
public static bool TryParse(string? text, out int charsRead, out Ipv4Subnet result)
=> Ipv4Subnet.TryParseInternal(text, out charsRead, out result, out _);
internal static bool TryParseInternal(string? text, out int charsRead, out Ipv4Subnet result, out bool implicitSlash32)
{
var span = (text ?? string.Empty).AsSpan();
charsRead = default;
return Ipv4Subnet.TryParseInternal(ref span, ref charsRead, out result, out implicitSlash32);
}
internal static bool TryParseInternal(ref ReadOnlySpan<char> text, ref int charsRead, out Ipv4Subnet result, out bool implicitSlash32)
{
implicitSlash32 = default;
result = default;
if (!Ipv4Address.TryParse(ref text, ref charsRead, out var address))
return false;
return TryParseWithCidr(ref text, ref charsRead, address, out result)
|| TryParseWithMask(ref text, ref charsRead, address, out result)
|| ParseExact(address, out result, out implicitSlash32);
}
#endregion TryParse
}
} | 43.907508 | 151 | 0.568883 | [
"MIT"
] | binarycow/NetworkPrimitives | src/NetworkPrimitives/Ipv4/Subnet/Ipv4Subnet.cs | 40,353 | C# |
using NSubstitute;
using NUnit.Framework;
using System.Collections;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.TestTools;
using Object = UnityEngine.Object;
namespace Tests
{
public class SearchBarViewShould
{
private SearchBarView view;
[SetUp]
public void SetUp()
{
const string prefabAssetPath =
"Assets/Scripts/MainScripts/DCL/Controllers/HUD/BuilderProjectsPanel/Prefabs/SearchBar/SearchBarView.prefab";
var prefab = AssetDatabase.LoadAssetAtPath<SearchBarView>(prefabAssetPath);
view = Object.Instantiate(prefab);
}
[TearDown]
public void TearDown()
{
Object.Destroy(view.gameObject);
}
[UnityTest]
public IEnumerator TriggerSearchWhenUserStopTyping()
{
const string searchValue = "Something";
const float idleTimeToTriggerSearch = SearchInputField.IDLE_TYPE_TIME_TRIGGER_SEARCH;
bool searchTriggered = false;
string searchValueReceived = "";
float searchTriggerTime = 0;
var handler = Substitute.For<ISectionSearchHandler>();
handler.WhenForAnyArgs(a => a.SetSearchString(""))
.Do(info =>
{
searchTriggered = true;
searchValueReceived = info.Arg<string>();
searchTriggerTime = Time.unscaledTime;
});
view.SetSearchBar(handler, null);
float searchTime = Time.unscaledTime;
view.inputField.inputField.text = searchValue;
yield return new WaitForSeconds(idleTimeToTriggerSearch);
Assert.IsTrue(searchTriggered);
Assert.AreEqual(searchValue, searchValueReceived);
Assert.GreaterOrEqual(searchTriggerTime, searchTime + idleTimeToTriggerSearch);
}
[Test]
public void ShowSpinnerAndClearSearchButton()
{
Assert.IsFalse(view.inputField.searchSpinner.activeSelf);
Assert.IsFalse(view.inputField.clearSearchButton.gameObject.activeSelf);
view.inputField.inputField.text = "searchValue";
Assert.IsTrue(view.inputField.searchSpinner.activeSelf);
Assert.IsFalse(view.inputField.clearSearchButton.gameObject.activeSelf);
view.inputField.inputField.onSubmit.Invoke("searchValue");
Assert.IsFalse(view.inputField.searchSpinner.activeSelf);
Assert.IsTrue(view.inputField.clearSearchButton.gameObject.activeSelf);
view.inputField.clearSearchButton.onClick.Invoke();
Assert.IsFalse(view.inputField.searchSpinner.activeSelf);
Assert.IsFalse(view.inputField.clearSearchButton.gameObject.activeSelf);
Assert.AreEqual(string.Empty, view.inputField.inputField.text);
}
[Test]
public void ShowFilters()
{
view.ShowFilters(true,false,false);
Assert.IsTrue(view.ownerToggle.gameObject.activeSelf);
Assert.IsFalse(view.operatorToggle.gameObject.activeSelf);
Assert.IsFalse(view.contributorToggle.gameObject.activeSelf);
view.ShowFilters(false,false,false);
Assert.IsFalse(view.ownerToggle.gameObject.activeSelf);
Assert.IsFalse(view.operatorToggle.gameObject.activeSelf);
Assert.IsFalse(view.contributorToggle.gameObject.activeSelf);
}
[Test]
public void TriggerFiltersCallback()
{
bool ownerON = false;
bool operatorON = false;
bool contributorON = false;
var handler = Substitute.For<ISectionSearchHandler>();
handler.WhenForAnyArgs(a => a.SetFilter(false, false, false))
.Do(info =>
{
ownerON = info.ArgAt<bool>(0);
operatorON = info.ArgAt<bool>(1);
contributorON = info.ArgAt<bool>(2);
});
view.SetSearchBar(handler, null);
view.ownerToggle.isOn = true;
Assert.IsTrue(ownerON);
Assert.IsFalse(operatorON);
Assert.IsFalse(contributorON);
view.operatorToggle.isOn = true;
Assert.IsTrue(ownerON);
Assert.IsTrue(operatorON);
Assert.IsFalse(contributorON);
view.contributorToggle.isOn = true;
Assert.IsTrue(ownerON);
Assert.IsTrue(operatorON);
Assert.IsTrue(contributorON);
view.ownerToggle.isOn = false;
view.operatorToggle.isOn = false;
view.contributorToggle.isOn = false;
Assert.IsFalse(ownerON);
Assert.IsFalse(operatorON);
Assert.IsFalse(contributorON);
}
[Test]
public void ShowSortDropdown()
{
string[] sortTypes = new[] {"Type1", "Type2", "Type3"};
view.SetSortTypes(sortTypes);
Assert.IsTrue(view.sortDropdown.activeButtons.TrueForAll(button => sortTypes.Contains(button.label.text)));
Assert.IsFalse(view.sortDropdown.gameObject.activeSelf);
view.sortButton.onClick.Invoke();
Assert.IsTrue(view.sortDropdown.gameObject.activeSelf);
}
[Test]
public void NotShowSortDropdownWhenLessThanTwoSortTypes()
{
string[] sortTypes = new[] {"Type1"};
view.SetSortTypes(sortTypes);
Assert.IsFalse(view.sortDropdown.gameObject.activeSelf);
view.sortButton.onClick.Invoke();
Assert.IsFalse(view.sortDropdown.gameObject.activeSelf);
}
[Test]
public void TriggerSortTypeCallback()
{
string selectedSort = "";
var handler = Substitute.For<ISectionSearchHandler>();
handler.WhenForAnyArgs(a => a.SetSortType(""))
.Do(info =>
{
selectedSort = info.Arg<string>();
});
view.SetSearchBar(handler, null);
string[] sortTypes = new[] {"Type1"};
view.SetSortTypes(sortTypes);
((IPointerDownHandler)view.sortDropdown.activeButtons[0]).OnPointerDown(null);
Assert.AreEqual(sortTypes[0], selectedSort);
Assert.AreEqual(sortTypes[0], view.sortTypeLabel.text);
}
[Test]
public void TriggerSortOrderCallback()
{
bool ascending = false;
var handler = Substitute.For<ISectionSearchHandler>();
handler.WhenForAnyArgs(a => a.SetSortOrder(false))
.Do(info =>
{
ascending = info.Arg<bool>();
});
view.SetSearchBar(handler, null);
view.sortOrderToggle.Set(true);
Assert.IsTrue(ascending);
view.sortOrderToggle.Set(false);
Assert.IsFalse(ascending);
}
}
} | 33.804762 | 125 | 0.596704 | [
"Apache-2.0"
] | cruzdanilo/decentraland | unity-client/Assets/Scripts/MainScripts/DCL/Controllers/HUD/BuilderProjectsPanel/Tests/SearchBarViewShould.cs | 7,101 | C# |
using System;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using Quartz.Spi;
namespace thorn.Jobs;
public class SingletonJobFactory : IJobFactory
{
private readonly IServiceProvider _serviceProvider;
public SingletonJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return _serviceProvider.GetRequiredService(bundle.JobDetail.JobType) as IJob;
}
public void ReturnJob(IJob job)
{
}
} | 22.64 | 85 | 0.750883 | [
"MIT"
] | scp-cs/Thorn | thorn/Jobs/SingletonJobFactory.cs | 566 | C# |
using Nager.Country.Currencies;
namespace Nager.Country.CountryInfos
{
/// <summary>
/// Paraguay
/// </summary>
public class ParaguayCountryInfo : ICountryInfo
{
///<inheritdoc/>
public string CommonName => "Paraguay";
///<inheritdoc/>
public string OfficialName => "Republic of Paraguay";
///<inheritdoc/>
public Alpha2Code Alpha2Code => Alpha2Code.PY;
///<inheritdoc/>
public Alpha3Code Alpha3Code => Alpha3Code.PRY;
///<inheritdoc/>
public int NumericCode => 600;
///<inheritdoc/>
public string[] TLD => new [] { ".py" };
///<inheritdoc/>
public Region Region => Region.Americas;
///<inheritdoc/>
public SubRegion SubRegion => SubRegion.SouthAmerica;
///<inheritdoc/>
public Alpha2Code[] BorderCountries => new Alpha2Code[]
{
Alpha2Code.AR,
Alpha2Code.BO,
Alpha2Code.BR,
};
///<inheritdoc/>
public ICurrency[] Currencies => new [] { new PygCurrency() };
///<inheritdoc/>
public string[] CallingCodes => new [] { "595" };
}
}
| 28.214286 | 70 | 0.552743 | [
"MIT"
] | Tri125/Nager.Country | src/Nager.Country/CountryInfos/ParaguayCountryInfo.cs | 1,185 | C# |
// Licensed to Elasticsearch B.V under
// one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Runtime.ExceptionServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Elastic.Apm.Tests.MockApmServer;
using Elastic.Apm.Tests.Utilities;
using FluentAssertions;
using Xunit;
using static Elastic.Apm.Config.ConfigConsts;
using LogLevel = Elastic.Apm.Logging.LogLevel;
namespace Elastic.Apm.StartupHook.Tests
{
public class StartupHookTests
{
/// <summary>
/// Asserts that startup hooks successfully hook up the APM agent and
/// send data to mock APM server for the supported framework versions
/// </summary>
/// <param name="targetFramework"></param>
/// <returns></returns>
[Theory]
[InlineData("netcoreapp3.0")]
[InlineData("netcoreapp3.1")]
[InlineData("net5.0")]
public async Task Auto_Instrument_With_StartupHook_Should_Capture_Transaction(string targetFramework)
{
var apmLogger = new InMemoryBlockingLogger(LogLevel.Error);
var apmServer = new MockApmServer(apmLogger, nameof(Auto_Instrument_With_StartupHook_Should_Capture_Transaction));
var port = apmServer.FindAvailablePortToListen();
apmServer.RunInBackground(port);
var waitHandle = new ManualResetEvent(false);
apmServer.OnReceive += o =>
{
if (o is TransactionDto)
waitHandle.Set();
};
using (var sampleApp = new SampleApplication())
{
var environmentVariables = new Dictionary<string, string>
{
[EnvVarNames.ServerUrl] = $"http://localhost:{port}",
[EnvVarNames.CloudProvider] = "none"
};
var uri = sampleApp.Start(targetFramework, environmentVariables);
var client = new HttpClient();
var response = await client.GetAsync(uri);
response.IsSuccessStatusCode.Should().BeTrue();
waitHandle.WaitOne(TimeSpan.FromMinutes(2));
apmServer.ReceivedData.Transactions.Should().HaveCount(1);
var transaction = apmServer.ReceivedData.Transactions.First();
transaction.Name.Should().Be("GET Home/Index");
}
await apmServer.StopAsync();
}
[Theory]
[InlineData("netcoreapp3.0", ".NET Core", "3.0.0.0")]
[InlineData("netcoreapp3.1", ".NET Core", "3.1.0.0")]
[InlineData("net5.0", ".NET 5", "5.0.0.0")]
public async Task Auto_Instrument_With_StartupHook_Should_Capture_Metadata(
string targetFramework,
string expectedRuntimeName,
string expectedFrameworkVersion)
{
var apmLogger = new InMemoryBlockingLogger(LogLevel.Error);
var apmServer = new MockApmServer(apmLogger, nameof(Auto_Instrument_With_StartupHook_Should_Capture_Metadata));
var port = apmServer.FindAvailablePortToListen();
apmServer.RunInBackground(port);
var waitHandle = new ManualResetEvent(false);
apmServer.OnReceive += o =>
{
if (o is MetadataDto)
waitHandle.Set();
};
using (var sampleApp = new SampleApplication())
{
var environmentVariables = new Dictionary<string, string>
{
[EnvVarNames.ServerUrl] = $"http://localhost:{port}",
[EnvVarNames.CloudProvider] = "none"
};
var uri = sampleApp.Start(targetFramework, environmentVariables);
var client = new HttpClient();
var response = await client.GetAsync(uri);
response.IsSuccessStatusCode.Should().BeTrue();
waitHandle.WaitOne(TimeSpan.FromMinutes(2));
apmServer.ReceivedData.Metadata.Should().HaveCountGreaterOrEqualTo(1);
var metadata = apmServer.ReceivedData.Metadata.First();
metadata.Service.Runtime.Name.Should().Be(expectedRuntimeName);
metadata.Service.Framework.Name.Should().Be("ASP.NET Core");
metadata.Service.Framework.Version.Should().Be(expectedFrameworkVersion);
}
await apmServer.StopAsync();
}
[Theory]
[InlineData("webapi", "WebApi30", "netcoreapp3.0", "weatherforecast")]
[InlineData("webapi", "WebApi31", "netcoreapp3.1", "weatherforecast")]
[InlineData("webapi", "WebApi50", "net5.0", "weatherforecast")]
[InlineData("webapp", "WebApp30", "netcoreapp3.0", "")]
[InlineData("webapp", "WebApp31", "netcoreapp3.1", "")]
[InlineData("webapp", "WebApp50", "net5.0", "")]
[InlineData("mvc", "Mvc30", "netcoreapp3.0", "")]
[InlineData("mvc", "Mvc31", "netcoreapp3.1", "")]
[InlineData("mvc", "Mvc50", "net5.0", "")]
public async Task Auto_Instrument_With_StartupHook(string template, string name, string targetFramework, string path)
{
var apmLogger = new InMemoryBlockingLogger(LogLevel.Trace);
var apmServer = new MockApmServer(apmLogger, nameof(Auto_Instrument_With_StartupHook));
var port = apmServer.FindAvailablePortToListen();
apmServer.RunInBackground(port);
var transactionWaitHandle = new ManualResetEvent(false);
var metadataWaitHandle = new ManualResetEvent(false);
apmServer.OnReceive += o =>
{
if (o is TransactionDto)
transactionWaitHandle.Set();
else if (o is MetadataDto)
metadataWaitHandle.Set();
};
using var project = DotnetProject.Create(name, template, targetFramework, "--no-https");
var environmentVariables = new Dictionary<string, string>
{
[EnvVarNames.ServerUrl] = $"http://localhost:{port}",
[EnvVarNames.CloudProvider] = "none"
};
using (var process = project.CreateProcess(SolutionPaths.AgentZip, environmentVariables))
{
var startHandle = new ManualResetEvent(false);
Uri uri = null;
ExceptionDispatchInfo e = null;
var capturedLines = new List<string>();
var endpointRegex = new Regex(@"\s*Now listening on:\s*(?<endpoint>http\:[^\s]*)");
process.SubscribeLines(
line =>
{
capturedLines.Add(line.Line);
var match = endpointRegex.Match(line.Line);
if (match.Success)
{
try
{
var endpoint = match.Groups["endpoint"].Value.Trim();
uri = new UriBuilder(endpoint) { Path = path }.Uri;
}
catch (Exception exception)
{
e = ExceptionDispatchInfo.Capture(exception);
}
startHandle.Set();
}
},
exception => e = ExceptionDispatchInfo.Capture(exception));
var timeout = TimeSpan.FromMinutes(2);
var signalled = startHandle.WaitOne(timeout);
if (!signalled)
{
throw new Exception($"Could not start dotnet project within timeout {timeout}: "
+ string.Join(Environment.NewLine, capturedLines));
}
e?.Throw();
var client = new HttpClient();
var response = await client.GetAsync(uri);
response.IsSuccessStatusCode.Should().BeTrue();
signalled = transactionWaitHandle.WaitOne(timeout);
if (!signalled)
{
throw new Exception($"Did not receive transaction within timeout {timeout}: "
+ string.Join(Environment.NewLine, capturedLines)
+ Environment.NewLine
+ string.Join(Environment.NewLine, apmLogger.Lines));
}
apmServer.ReceivedData.Transactions.Should().HaveCount(1);
var transaction = apmServer.ReceivedData.Transactions.First();
transaction.Name.Should().NotBeNullOrEmpty();
signalled = metadataWaitHandle.WaitOne(timeout);
if (!signalled)
{
throw new Exception($"Did not receive metadata within timeout {timeout}: "
+ string.Join(Environment.NewLine, capturedLines)
+ Environment.NewLine
+ string.Join(Environment.NewLine, apmLogger.Lines));
}
apmServer.ReceivedData.Metadata.Should().HaveCountGreaterOrEqualTo(1);
var metadata = apmServer.ReceivedData.Metadata.First();
metadata.Service.Runtime.Name.Should().NotBeNullOrEmpty();
metadata.Service.Framework.Name.Should().Be("ASP.NET Core");
metadata.Service.Framework.Version.Should().NotBeNullOrEmpty();
}
await apmServer.StopAsync();
}
}
}
| 34.476596 | 120 | 0.683905 | [
"Apache-2.0"
] | ejsmith/apm-agent-dotnet | test/Elastic.Apm.StartupHook.Tests/StartupHookTests.cs | 8,102 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using Kudu.Core.Infrastructure;
using Newtonsoft.Json;
using SignalR.Client;
namespace Kudu.Core.Deployment {
public class RemoteDeploymentManager : IDeploymentManager {
private readonly HttpClient _client;
private readonly Connection _connection;
public event Action<DeployResult> StatusChanged;
public RemoteDeploymentManager(string serviceUrl) {
serviceUrl = UrlUtility.EnsureTrailingSlash(serviceUrl);
_client = HttpClientHelper.Create(serviceUrl);
// Raise the event when data comes in
_connection = new Connection(serviceUrl + "status");
_connection.Received += data => {
if (StatusChanged != null) {
var result = JsonConvert.DeserializeObject<DeployResult>(data);
StatusChanged(result);
}
};
_connection.Error += exception => {
// If we get a 404 back stop listening for changes
WebException webException = exception as WebException;
if (webException != null) {
var webResponse = (HttpWebResponse)webException.Response;
if (webResponse != null &&
webResponse.StatusCode == HttpStatusCode.NotFound) {
_connection.Stop();
}
}
};
_connection.Closed += () => {
Debug.WriteLine("SignalR connection to {0} was closed.", serviceUrl);
};
_connection.Start().Wait();
}
public bool IsActive {
get {
return _connection.IsActive;
}
}
public string ActiveDeploymentId {
get {
return _client.Get("id").EnsureSuccessful()
.Content
.ReadAsString();
}
}
public IEnumerable<DeployResult> GetResults() {
return _client.GetJson<IEnumerable<DeployResult>>("log");
}
public DeployResult GetResult(string id) {
return _client.GetJson<DeployResult>("details?id=" + id);
}
public IEnumerable<LogEntry> GetLogEntries(string id) {
return _client.GetJson<IEnumerable<LogEntry>>("log?id=" + id);
}
public void Deploy(string id) {
_client.Post(String.Empty, new FormUrlEncodedContent(new Dictionary<string, string> {
{ "id", id }
})).EnsureSuccessful();
}
public void Deploy() {
_client.Post(String.Empty, new StringContent(String.Empty)).EnsureSuccessful();
}
public void Build(string id) {
_client.Post("new", new FormUrlEncodedContent(new Dictionary<string, string> {
{ "id", id }
})).EnsureSuccessful();
}
}
}
| 32.989247 | 97 | 0.551825 | [
"Apache-2.0"
] | RaleighHokie/kudu | Kudu.Core/Deployment/RemoteDeploymentManager.cs | 3,070 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.ComponentModel;
namespace System.Data.Common
{
public class DbEnumerator : IEnumerator
{
internal IDataReader _reader;
internal DbDataRecord _current;
internal SchemaInfo[] _schemaInfo; // shared schema info among all the data records
internal PropertyDescriptorCollection _descriptors; // cached property descriptors
private FieldNameLookup _fieldNameLookup;
private readonly bool _closeReader;
// users must get enumerators off of the datareader interfaces
public DbEnumerator(IDataReader reader)
{
if (null == reader)
{
throw ADP.ArgumentNull(nameof(reader));
}
_reader = reader;
}
public DbEnumerator(IDataReader reader, bool closeReader)
{
if (null == reader)
{
throw ADP.ArgumentNull(nameof(reader));
}
_reader = reader;
_closeReader = closeReader;
}
public DbEnumerator(DbDataReader reader)
: this((IDataReader)reader)
{
}
public DbEnumerator(DbDataReader reader, bool closeReader)
: this((IDataReader)reader, closeReader)
{
}
public object Current => _current;
public bool MoveNext()
{
if (null == _schemaInfo)
{
BuildSchemaInfo();
}
Debug.Assert(null != _schemaInfo && null != _descriptors, "unable to build schema information!");
_current = null;
if (_reader.Read())
{
// setup our current record
object[] values = new object[_schemaInfo.Length];
_reader.GetValues(values); // this.GetValues()
_current = new DataRecordInternal(_schemaInfo, values, _descriptors, _fieldNameLookup);
return true;
}
if (_closeReader)
{
_reader.Close();
}
return false;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void Reset()
{
throw ADP.NotSupported();
}
private void BuildSchemaInfo()
{
int count = _reader.FieldCount;
string[] fieldnames = new string[count];
for (int i = 0; i < count; ++i)
{
fieldnames[i] = _reader.GetName(i);
}
ADP.BuildSchemaTableInfoTableNames(fieldnames);
SchemaInfo[] si = new SchemaInfo[count];
PropertyDescriptor[] props = new PropertyDescriptor[_reader.FieldCount];
for (int i = 0; i < si.Length; i++)
{
SchemaInfo s = default;
s.name = _reader.GetName(i);
s.type = _reader.GetFieldType(i);
s.typeName = _reader.GetDataTypeName(i);
props[i] = new DbColumnDescriptor(i, fieldnames[i], s.type);
si[i] = s;
}
_schemaInfo = si;
_fieldNameLookup = new FieldNameLookup(_reader, -1);
_descriptors = new PropertyDescriptorCollection(props);
}
private sealed class DbColumnDescriptor : PropertyDescriptor
{
private readonly int _ordinal;
private readonly Type _type;
internal DbColumnDescriptor(int ordinal, string name, Type type)
: base(name, null)
{
_ordinal = ordinal;
_type = type;
}
public override Type ComponentType => typeof(IDataRecord);
public override bool IsReadOnly => true;
public override Type PropertyType => _type;
public override bool CanResetValue(object component) => false;
public override object GetValue(object component) => ((IDataRecord)component)[_ordinal];
public override void ResetValue(object component)
{
throw ADP.NotSupported();
}
public override void SetValue(object component, object value)
{
throw ADP.NotSupported();
}
public override bool ShouldSerializeValue(object component) => false;
}
}
}
| 31.646259 | 109 | 0.557825 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Data.Common/src/System/Data/Common/DbEnumerator.cs | 4,652 | C# |
// Dash Teleport|Scripts|0220
namespace VRTK
{
using UnityEngine;
using System.Collections;
/// <summary>
/// Event Payload
/// </summary>
/// <param name="hits">An array of objects that the CapsuleCast has collided with.</param>
public struct DashTeleportEventArgs
{
public RaycastHit[] hits;
}
/// <summary>
/// Event Payload
/// </summary>
/// <param name="sender">this object</param>
/// <param name="e"><see cref="DashTeleportEventArgs"/></param>
public delegate void DashTeleportEventHandler(object sender, DashTeleportEventArgs e);
/// <summary>
/// The dash teleporter extends the height adjust teleporter and allows to have the `[CameraRig]` dashing to a new teleport location.
/// </summary>
/// <remarks>
/// Like the basic teleporter and the height adjustable teleporter the Dash Teleport script is attached to the `[CameraRig]` prefab and requires a World Pointer to be available.
///
/// The basic principle is to dash for a very short amount of time, to avoid sim sickness. The default value is 100 miliseconds. This value is fixed for all normal and longer distances. When the distances get very short the minimum speed is clamped to 50 mps, so the dash time becomes even shorter.
///
/// The minimum distance for the fixed time dash is determined by the minSpeed and normalLerpTime values, if you want to always lerp with a fixed mps speed instead, set the normalLerpTime to a high value. Right before the teleport a capsule is cast towards the target and registers all colliders blocking the way. These obstacles are then broadcast in an event so that for example their gameobjects or renderers can be turned off while the dash is in progress.
/// </remarks>
/// <example>
/// `SteamVR_Unity_Toolkit/Examples/038_CameraRig_DashTeleport` shows how to turn off the mesh renderers of objects that are in the way during the dash.
/// </example>
public class VRTK_DashTeleport : VRTK_HeightAdjustTeleport
{
[Tooltip("The fixed time it takes to dash to a new position.")]
public float normalLerpTime = 0.1f; // 100ms for every dash above minDistanceForNormalLerp
[Tooltip("The minimum speed for dashing in meters per second.")]
public float minSpeedMps = 50.0f; // clamped to minimum speed 50m/s to avoid sickness
[Tooltip("The Offset of the CapsuleCast above the camera.")]
public float capsuleTopOffset = 0.2f;
[Tooltip("The Offset of the CapsuleCast below the camera.")]
public float capsuleBottomOffset = 0.5f;
[Tooltip("The radius of the CapsuleCast.")]
public float capsuleRadius = 0.5f;
/// <summary>
/// Emitted when the CapsuleCast towards the target has found that obstacles are in the way.
/// </summary>
public event DashTeleportEventHandler WillDashThruObjects;
/// <summary>
/// Emitted when obstacles have been crossed and the dash has ended.
/// </summary>
public event DashTeleportEventHandler DashedThruObjects;
// The minimum distance for fixed time lerp is determined by the minSpeed and the normalLerpTime
// If you want to always lerp with a fixed mps speed, set the normalLerpTime to a high value
private float minDistanceForNormalLerp;
private float lerpTime = 0.1f;
public virtual void OnWillDashThruObjects(DashTeleportEventArgs e)
{
if (WillDashThruObjects != null)
{
WillDashThruObjects(this, e);
}
}
public virtual void OnDashedThruObjects(DashTeleportEventArgs e)
{
if (DashedThruObjects != null)
{
DashedThruObjects(this, e);
}
}
protected override void Awake()
{
base.Awake();
minDistanceForNormalLerp = minSpeedMps * normalLerpTime; // default values give 5.0f
}
protected override void SetNewPosition(Vector3 position, Transform target)
{
Vector3 targetPosition = CheckTerrainCollision(position, target);
StartCoroutine(lerpToPosition(targetPosition, target));
}
private IEnumerator lerpToPosition(Vector3 targetPosition, Transform target)
{
enableTeleport = false;
bool gameObjectInTheWay = false;
// Find the objects we will be dashing through and broadcast them via events
Vector3 eyeCameraPosition = eyeCamera.transform.position;
Vector3 eyeCameraPositionOnGround = new Vector3(eyeCameraPosition.x, transform.position.y, eyeCameraPosition.z);
Vector3 eyeCameraRelativeToRig = eyeCameraPosition - transform.position;
Vector3 targetEyeCameraPosition = targetPosition + eyeCameraRelativeToRig;
Vector3 direction = (targetEyeCameraPosition - eyeCameraPosition).normalized;
Vector3 bottomPoint = eyeCameraPositionOnGround + (Vector3.up * capsuleBottomOffset) + direction;
Vector3 topPoint = eyeCameraPosition + (Vector3.up * capsuleTopOffset) + direction;
float maxDistance = Vector3.Distance(transform.position, targetPosition - direction * 0.5f);
RaycastHit[] allHits = Physics.CapsuleCastAll(bottomPoint, topPoint, capsuleRadius, direction, maxDistance);
foreach (RaycastHit hit in allHits)
{
gameObjectInTheWay = hit.collider.gameObject != target.gameObject ? true : false;
}
if (gameObjectInTheWay)
{
OnWillDashThruObjects(SetDashTeleportEvent(allHits));
}
if (maxDistance >= minDistanceForNormalLerp)
{
lerpTime = normalLerpTime; // fixed time for all bigger dashes
}
else
{
lerpTime = (1f / minSpeedMps) * maxDistance; // clamped to speed for small dashes
}
Vector3 startPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z);
float elapsedTime = 0;
float t = 0;
while (t < 1)
{
transform.position = Vector3.Lerp(startPosition, targetPosition, t);
elapsedTime += Time.deltaTime;
t = elapsedTime / lerpTime;
if (t > 1)
{
if (transform.position != targetPosition)
{
transform.position = targetPosition;
}
t = 1;
}
yield return new WaitForEndOfFrame();
}
if (gameObjectInTheWay)
{
OnDashedThruObjects(SetDashTeleportEvent(allHits));
}
gameObjectInTheWay = false;
enableTeleport = true;
}
private DashTeleportEventArgs SetDashTeleportEvent(RaycastHit[] hits)
{
DashTeleportEventArgs e;
e.hits = hits;
return e;
}
}
} | 44.283951 | 464 | 0.631865 | [
"MIT"
] | 3dit/steamvrtoolkit | Assets/VRTK/Scripts/VRTK_DashTeleport.cs | 7,174 | C# |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
namespace Microsoft.Azure.Management.Network.Models
{
/// <summary>
/// Id of the resource
/// </summary>
public partial class ResourceId
{
private string _id;
/// <summary>
/// Optional. Id of the resource
/// </summary>
public string Id
{
get { return this._id; }
set { this._id = value; }
}
/// <summary>
/// Initializes a new instance of the ResourceId class.
/// </summary>
public ResourceId()
{
}
}
}
| 27.431373 | 76 | 0.627591 | [
"Apache-2.0"
] | CerebralMischief/azure-sdk-for-net | src/ResourceManagement/Network/NetworkManagement/Generated/Models/ResourceId.cs | 1,399 | C# |
/**
* Copyright 2015 Canada Health Infoway, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: $LastChangedBy: jmis $
* Last modified: $LastChangedDate: 2015-09-15 10:24:28 -0400 (Tue, 15 Sep 2015) $
* Revision: $LastChangedRevision: 9776 $
*/
/* This class was auto-generated by the message builder generator tools. */
namespace Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Interaction {
using Ca.Infoway.Messagebuilder.Annotation;
using Ca.Infoway.Messagebuilder.Model;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Mcci_mt000100ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Quqi_mt020000ca;
using Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060280ca;
/**
* <summary>Business Name: PORX_IN060250CA: Medication
* prescription detail query</summary>
*
* <p>Requests retrieval of detailed information about a single
* medication prescription referenced by id, optionally
* including detailed dispense information.</p> Message:
* MCCI_MT000100CA.Message Control Act:
* QUQI_MT020000CA.ControlActEvent --> Payload:
* PORX_MT060280CA.ParameterList
*/
[Hl7PartTypeMappingAttribute(new string[] {"PORX_IN060250CA"})]
public class MedicationPrescriptionDetailQuery : HL7Message<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Common.Quqi_mt020000ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_3.Pharmacy.Porx_mt060280ca.DrugPrescriptionDetailQueryParameters>>, IInteraction {
public MedicationPrescriptionDetailQuery() {
}
}
} | 46.145833 | 283 | 0.734989 | [
"ECL-2.0",
"Apache-2.0"
] | CanadaHealthInfoway/message-builder-dotnet | message-builder-release-v01_r04_3/Main/Ca/Infoway/Messagebuilder/Model/Pcs_cerx_v01_r04_3/Interaction/MedicationPrescriptionDetailQuery.cs | 2,215 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Inputs.Database.V1Alpha1
{
/// <summary>
/// A ResourceClaimStatus represents the observed status of a resource claim.
/// </summary>
public class MySQLInstanceStatusArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Phase represents the binding phase of a managed resource or claim. Unbindable resources cannot be bound, typically because they are currently unavailable, or still being created. Unbound resource are available for binding, and Bound resources have successfully bound to another resource.
/// </summary>
[Input("bindingPhase")]
public Input<string>? BindingPhase { get; set; }
[Input("conditions")]
private InputList<Pulumi.Kubernetes.Types.Inputs.Database.V1Alpha1.MySQLInstanceStatusConditionsArgs>? _conditions;
/// <summary>
/// Conditions of the resource.
/// </summary>
public InputList<Pulumi.Kubernetes.Types.Inputs.Database.V1Alpha1.MySQLInstanceStatusConditionsArgs> Conditions
{
get => _conditions ?? (_conditions = new InputList<Pulumi.Kubernetes.Types.Inputs.Database.V1Alpha1.MySQLInstanceStatusConditionsArgs>());
set => _conditions = value;
}
public MySQLInstanceStatusArgs()
{
}
}
}
| 39.292683 | 299 | 0.6946 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/crossplane/dotnet/Kubernetes/Crds/Operators/Crossplane/Database/V1Alpha1/Inputs/MySQLInstanceStatusArgs.cs | 1,611 | C# |
// Copyright 2015-2020 Rik Essenius
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System.Collections.ObjectModel;
namespace TestSlim
{
using TableType = Collection<Collection<string>>;
public class AddOneColumn
{
public static TableType DoTable(TableType table)
{
foreach (var row in table)
{
// Make all columns empty to keep them unchanged
for (var i = 0; i < row.Count; i++)
{
row[i] = string.Empty;
}
row.Add("pass:ok");
}
return table;
}
}
}
| 32.742857 | 107 | 0.622164 | [
"Apache-2.0"
] | essenius/FitNesseFitSharpFeatureDemos | TestSlim/TestSlim/AddOneColumn.cs | 1,148 | C# |
namespace WastedgeQuerier.EditInExcel
{
partial class EditInExcelWaitForm
{
/// <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.formFlowFooter1 = new SystemEx.Windows.Forms.FormFlowFooter();
this._cancelButton = new System.Windows.Forms.Button();
this._acceptButton = new System.Windows.Forms.Button();
this.formHeader1 = new SystemEx.Windows.Forms.FormHeader();
this.panel1 = new System.Windows.Forms.Panel();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.formFlowFooter1.SuspendLayout();
this.panel1.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// formFlowFooter1
//
this.formFlowFooter1.Controls.Add(this._cancelButton);
this.formFlowFooter1.Controls.Add(this._acceptButton);
this.formFlowFooter1.Location = new System.Drawing.Point(0, 85);
this.formFlowFooter1.Name = "formFlowFooter1";
this.formFlowFooter1.Size = new System.Drawing.Size(462, 45);
this.formFlowFooter1.TabIndex = 0;
//
// _cancelButton
//
this._cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this._cancelButton.Location = new System.Drawing.Point(366, 11);
this._cancelButton.Name = "_cancelButton";
this._cancelButton.Size = new System.Drawing.Size(75, 23);
this._cancelButton.TabIndex = 0;
this._cancelButton.Text = "Cancel";
this._cancelButton.UseVisualStyleBackColor = true;
//
// _acceptButton
//
this._acceptButton.Location = new System.Drawing.Point(254, 11);
this._acceptButton.Name = "_acceptButton";
this._acceptButton.Size = new System.Drawing.Size(106, 23);
this._acceptButton.TabIndex = 1;
this._acceptButton.Text = "Upload Changes";
this._acceptButton.UseVisualStyleBackColor = true;
this._acceptButton.Click += new System.EventHandler(this._acceptButton_Click);
//
// formHeader1
//
this.formHeader1.Location = new System.Drawing.Point(0, 0);
this.formHeader1.Name = "formHeader1";
this.formHeader1.Size = new System.Drawing.Size(462, 47);
this.formHeader1.SubText = "Use Excel to modify the result set.";
this.formHeader1.TabIndex = 1;
this.formHeader1.Text = "Edit in Excel";
//
// panel1
//
this.panel1.AutoSize = true;
this.panel1.Controls.Add(this.tableLayoutPanel1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 47);
this.panel1.Name = "panel1";
this.panel1.Padding = new System.Windows.Forms.Padding(9);
this.panel1.Size = new System.Drawing.Size(462, 38);
this.panel1.TabIndex = 2;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.AutoSize = true;
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(9, 9);
this.tableLayoutPanel1.MaximumSize = new System.Drawing.Size(444, 9999);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 1;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.Size = new System.Drawing.Size(444, 20);
this.tableLayoutPanel1.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 3);
this.label1.Margin = new System.Windows.Forms.Padding(3);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(292, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Click Upload Changes once you\'ve made your modifications.";
//
// EditInExcelWaitForm
//
this.AcceptButton = this._acceptButton;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.CancelButton = this._cancelButton;
this.ClientSize = new System.Drawing.Size(462, 130);
this.Controls.Add(this.panel1);
this.Controls.Add(this.formHeader1);
this.Controls.Add(this.formFlowFooter1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "EditInExcelWaitForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Edit in Excel";
this.formFlowFooter1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private SystemEx.Windows.Forms.FormFlowFooter formFlowFooter1;
private SystemEx.Windows.Forms.FormHeader formHeader1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button _cancelButton;
private System.Windows.Forms.Button _acceptButton;
private System.Windows.Forms.Label label1;
}
} | 46.896774 | 136 | 0.590315 | [
"Apache-2.0"
] | wastedge/wastedge-querier | WastedgeQuerier/EditInExcel/EditInExcelWaitForm.Designer.cs | 7,271 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using ILLink.Shared.DataFlow;
using ILLink.Shared.TrimAnalysis;
using ILLink.Shared.TypeSystemProxy;
using Microsoft.CodeAnalysis;
using MultiValue = ILLink.Shared.DataFlow.ValueSet<ILLink.Shared.DataFlow.SingleValue>;
namespace ILLink.RoslynAnalyzer.TrimAnalysis
{
public readonly record struct TrimAnalysisMethodCallPattern (
IMethodSymbol CalledMethod,
MultiValue Instance,
ImmutableArray<MultiValue> Arguments,
IOperation Operation,
ISymbol OwningSymbol)
{
public TrimAnalysisMethodCallPattern Merge (ValueSetLattice<SingleValue> lattice, TrimAnalysisMethodCallPattern other)
{
Debug.Assert (Operation == other.Operation);
Debug.Assert (SymbolEqualityComparer.Default.Equals (CalledMethod, other.CalledMethod));
Debug.Assert (Arguments.Length == other.Arguments.Length);
var argumentsBuilder = ImmutableArray.CreateBuilder<MultiValue> ();
for (int i = 0; i < Arguments.Length; i++) {
argumentsBuilder.Add (lattice.Meet (Arguments[i], other.Arguments[i]));
}
return new TrimAnalysisMethodCallPattern (
CalledMethod,
lattice.Meet (Instance, other.Instance),
argumentsBuilder.ToImmutable (),
Operation,
OwningSymbol);
}
public IEnumerable<Diagnostic> CollectDiagnostics ()
{
DiagnosticContext diagnosticContext = new (Operation.Syntax.GetLocation ());
HandleCallAction handleCallAction = new (diagnosticContext, OwningSymbol, Operation);
if (!handleCallAction.Invoke (new MethodProxy (CalledMethod), Instance, Arguments, out _, out _)) {
// If the intrinsic handling didn't work we have to:
// Handle the instance value
// Handle argument passing
// Construct the return value
// Note: this is temporary as eventually the handling of all method calls should be done in the shared code (not just intrinsics)
if (!CalledMethod.IsStatic) {
var requireDynamicallyAccessedMembersAction = new RequireDynamicallyAccessedMembersAction (diagnosticContext, new ReflectionAccessAnalyzer ());
requireDynamicallyAccessedMembersAction.Invoke (Instance, new MethodThisParameterValue (CalledMethod));
}
for (int argumentIndex = 0; argumentIndex < Arguments.Length; argumentIndex++) {
var requireDynamicallyAccessedMembersAction = new RequireDynamicallyAccessedMembersAction (diagnosticContext, new ReflectionAccessAnalyzer ());
requireDynamicallyAccessedMembersAction.Invoke (Arguments[argumentIndex], new MethodParameterValue (CalledMethod.Parameters[argumentIndex]));
}
}
return diagnosticContext.Diagnostics;
}
}
}
| 42.208955 | 148 | 0.776167 | [
"MIT"
] | AlexanderSemenyak/linker | src/ILLink.RoslynAnalyzer/TrimAnalysis/TrimAnalysisMethodCallPattern.cs | 2,828 | C# |
using System;
using Newtonsoft.Json;
using SignalRStresser.Enums;
namespace SignalRStresser.Connection
{
class HubConnectionContext
{
[JsonProperty("id")]
public string Id { get; set; } = Guid.NewGuid().ToString();
[JsonProperty("connectionInitialized")]
public bool ConnectionInitialized { get; set; } = false;
[JsonProperty("currentRetries")]
public int CurrentRetries { get; set; } = 1;
[JsonProperty("nextRetryTime")]
public TimeSpan NextRetry { get; set; } = TimeSpan.FromTicks(DateTime.MinValue.Ticks);
[JsonProperty("nextTestTime")]
public TimeSpan NextTest { get; set; } = TimeSpan.FromTicks(DateTime.MinValue.Ticks);
[JsonProperty("resolved")]
public bool Resolved { get; set; } = false;
[JsonProperty("resolvedTime")]
public long ResolvedTime { get; set; } = -1;
[JsonProperty("errored")]
public bool Errored { get; set; } = false;
[JsonProperty("errorType")]
public HubConnectionErrorType ErrorType { get; set; }
[JsonProperty("lastPingTime")]
public TimeSpan LastPingTime { get; set; } = TimeSpan.FromTicks(DateTime.MinValue.Ticks);
[JsonProperty("lastPingForPersistTime")]
public TimeSpan LastPingForPersistTime { get; set; } = TimeSpan.FromTicks(DateTime.MinValue.Ticks);
[JsonProperty("utcStartDate")]
public DateTime UtcStartDate { get; set; } = DateTime.UtcNow;
public void Reset()
{
this.CurrentRetries = 1;
this.NextRetry = TimeSpan.FromTicks(DateTime.MinValue.Ticks);
this.Resolved = false;
this.ResolvedTime = -1;
this.Errored = false;
this.LastPingTime = TimeSpan.FromTicks(DateTime.UtcNow.Ticks);
this.LastPingForPersistTime = TimeSpan.FromTicks(DateTime.UtcNow.Ticks);
}
}
}
| 34.754386 | 108 | 0.615851 | [
"MIT"
] | urbanspr1nter/sload | SignalRStresser/SignalRStresser/Connection/HubConnectionContext.cs | 1,983 | C# |
#region "Copyright"
/*
FOR FURTHER DETAILS ABOUT LICENSING, PLEASE VISIT "LICENSE.txt" INSIDE THE SAGEFRAME FOLDER
*/
#endregion
#region "References"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion
namespace SageFrame.ListManagement
{
/// <summary>
/// Feedback setting class.
/// </summary>
public class FeedbackSettingInfo
{
/// <summary>
/// Sets or gets Setting value
/// </summary>
public string SettingValue { get; set; }
}
}
| 17.03125 | 91 | 0.655046 | [
"MIT"
] | AspxCommerce/AspxCommerce2.7 | SageFrame.Core/SageFrame.ListManagement/Entities/FeedbackSettingInfo.cs | 547 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Monitor.Models
{
public partial class LocalizableString
{
internal static LocalizableString DeserializeLocalizableString(JsonElement element)
{
string value = default;
Optional<string> localizedValue = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("value"))
{
value = property.Value.GetString();
continue;
}
if (property.NameEquals("localizedValue"))
{
localizedValue = property.Value.GetString();
continue;
}
}
return new LocalizableString(value, localizedValue.Value);
}
}
}
| 28.194444 | 91 | 0.562562 | [
"MIT"
] | ChenTanyi/azure-sdk-for-net | sdk/monitor/Azure.ResourceManager.Monitor/src/Generated/Models/LocalizableString.Serialization.cs | 1,015 | 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("Example")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Example")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("3d5900ae-111a-45be-96b3-d9e4606ca793")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.888889 | 85 | 0.731429 | [
"Unlicense"
] | jf26028/Jeff | Example/Properties/AssemblyInfo.cs | 1,403 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Umbraco.Core.Logging;
using uSync8.Core;
using uSync8.Core.Extensions;
using uSync8.Core.Models;
using uSync8.Core.Serialization;
using Vendr.Core;
using Vendr.Core.Api;
using Vendr.Core.Models;
using Vendr.uSync.Extensions;
using Vendr.uSync.SyncModels;
namespace Vendr.uSync.Serializers
{
[SyncSerializer("22F98052-DD59-4A0C-AA13-52398B794ED5", "TaxClass Serializer", VendrConstants.Serialization.TaxClass)]
public class TaxClassSerializer : VendrSerializerBase<TaxClassReadOnly>, ISyncSerializer<TaxClassReadOnly>
{
public TaxClassSerializer(IVendrApi vendrApi, IUnitOfWorkProvider uowProvider, ILogger logger)
: base(vendrApi, uowProvider, logger)
{
}
protected override SyncAttempt<XElement> SerializeCore(TaxClassReadOnly item, SyncSerializerOptions options)
{
var node = InitializeBaseNode(item, ItemAlias(item));
node.Add(new XElement(nameof(item.Name), item.Name));
node.Add(new XElement(nameof(item.SortOrder), item.SortOrder));
node.AddStoreId(item.StoreId);
node.Add(new XElement(nameof(item.DefaultTaxRate), item.DefaultTaxRate.Value));
node.Add(SerializeTaxRates(item));
return SyncAttempt<XElement>.SucceedIf(node != null, item.Name, node, ChangeType.Export);
}
private XElement SerializeTaxRates(TaxClassReadOnly item)
{
var root = new XElement("TaxRates");
foreach (var rate in item.CountryRegionTaxRates)
{
root.Add(new XElement("Rate",
new XElement("CountryId", rate.CountryId),
new XElement("RegionId", rate.RegionId),
new XElement("TaxRate", rate.TaxRate)));
}
return root;
}
public override bool IsValid(XElement node)
=> base.IsValid(node)
&& node.GetStoreId() != Guid.Empty;
protected override SyncAttempt<TaxClassReadOnly> DeserializeCore(XElement node, SyncSerializerOptions options)
{
var readonlyItem = FindItem(node);
var alias = node.GetAlias();
var id = node.GetKey();
var name = node.Element(nameof(readonlyItem.Name)).ValueOrDefault(alias);
var storeId = node.GetStoreId();
var defaultTaxRate = node.Element(nameof(readonlyItem.DefaultTaxRate)).ValueOrDefault((decimal)0);
using (var uow = _uowProvider.Create())
{
TaxClass item;
if (readonlyItem == null)
{
item = TaxClass.Create(uow, id, storeId, alias, name, defaultTaxRate);
}
else
{
item = readonlyItem.AsWritable(uow);
item.SetAlias(alias)
.SetName(name)
.SetDefaultTaxRate(defaultTaxRate);
}
item.SetSortOrder(node.Element(nameof(item.SortOrder)).ValueOrDefault(item.SortOrder));
DeserializeTaxRates(node, item);
_vendrApi.SaveTaxClass(item);
uow.Complete();
return SyncAttempt<TaxClassReadOnly>.Succeed(name, item.AsReadOnly(), ChangeType.Import);
}
}
protected List<SyncTaxModel> GetTaxRates(XElement node)
{
var taxRates = new List<SyncTaxModel>();
// load the regions from the xml.
var root = node.Element("TaxRates");
if (root != null && root.HasElements)
{
foreach (var value in root.Elements("Rate"))
{
taxRates.Add(new SyncTaxModel
{
CountryId = node.GetGuidValue("CountryId"),
RegionId = node.GetGuidValue("RegionId"),
Rate = node.Element("TaxRate").ValueOrDefault((decimal)0)
});
}
}
return taxRates;
}
protected void DeserializeTaxRates(XElement node, TaxClass item)
{
var rates = GetTaxRates(node);
var ratesToRemove = item.CountryRegionTaxRates
.Where(x => rates == null || !rates.Any(y => y.CountryId == x.CountryId && y.RegionId == x.RegionId))
.ToList();
foreach (var rate in rates)
{
if (rate.RegionId == null)
{
item.SetCountryTaxRate(rate.CountryId.Value, rate.Rate);
}
else
{
item.SetRegionTaxRate(rate.CountryId.Value, rate.RegionId.Value, rate.Rate);
}
}
foreach (var rate in ratesToRemove)
{
if (rate.RegionId == null)
{
item.ClearCountryTaxRate(rate.CountryId);
}
else
{
item.ClearRegionTaxRate(rate.CountryId, rate.RegionId.Value);
}
}
}
protected override void DeleteItem(TaxClassReadOnly item)
=> _vendrApi.DeleteTaxClass(item.Id);
protected override TaxClassReadOnly FindItem(Guid key)
=> _vendrApi.GetTaxClass(key);
protected override string ItemAlias(TaxClassReadOnly item)
=> item.Alias;
protected override void SaveItem(TaxClassReadOnly item)
{
using (var uow = _uowProvider.Create())
{
var entity = item.AsWritable(uow);
_vendrApi.SaveTaxClass(entity);
uow.Complete();
}
}
}
}
| 33.488636 | 122 | 0.554632 | [
"MIT"
] | Xanashi/vendr-usync | src/Vendr.uSync/Serializers/TaxClassSerializer.cs | 5,896 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Elsa.Models;
using Elsa.Serialization;
using Elsa.Services;
using Elsa.Services.Models;
using LinqKit;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Storage.Net;
using Storage.Net.Blobs;
namespace Elsa.Providers.Workflows
{
public class BlobStorageWorkflowProviderOptions
{
public Func<IBlobStorage> BlobStorageFactory { get; set; } = () => StorageFactory.Blobs.InMemory();
}
public class BlobStorageWorkflowProvider : WorkflowProvider
{
private readonly IBlobStorage _storage;
private readonly IWorkflowBlueprintMaterializer _workflowBlueprintMaterializer;
private readonly IContentSerializer _contentSerializer;
private readonly ILogger _logger;
public BlobStorageWorkflowProvider(
IOptions<BlobStorageWorkflowProviderOptions> options,
IWorkflowBlueprintMaterializer workflowBlueprintMaterializer,
IContentSerializer contentSerializer,
ILogger<BlobStorageWorkflowProvider> logger)
{
_storage = options.Value.BlobStorageFactory();
_workflowBlueprintMaterializer = workflowBlueprintMaterializer;
_contentSerializer = contentSerializer;
_logger = logger;
}
public override async IAsyncEnumerable<IWorkflowBlueprint> ListAsync(
VersionOptions versionOptions,
int? skip = default,
int? take = default,
string? tenantId = default,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var enumerable = ListInternalAsync(cancellationToken).OrderBy(x => x.Name).WithVersion(versionOptions);
if (!string.IsNullOrWhiteSpace(tenantId))
enumerable = enumerable.Where(x => x.TenantId == tenantId);
if (skip != null)
enumerable = enumerable.Skip(skip.Value);
if (take != null)
enumerable = enumerable.Take(take.Value);
await foreach (var workflowBlueprint in enumerable.WithCancellation(cancellationToken))
yield return workflowBlueprint;
}
public override async ValueTask<int> CountAsync(VersionOptions versionOptions, string? tenantId = default, CancellationToken cancellationToken = default)
{
var enumerable = ListInternalAsync(cancellationToken).WithVersion(versionOptions);
if (!string.IsNullOrWhiteSpace(tenantId))
enumerable = enumerable.Where(x => x.TenantId == tenantId);
return await enumerable.CountAsync(cancellationToken);
}
public override async ValueTask<IWorkflowBlueprint?> FindAsync(string definitionId, VersionOptions versionOptions, string? tenantId = default, CancellationToken cancellationToken = default)
{
Expression<Func<IWorkflowBlueprint, bool>> predicate = x => x.Id == definitionId && x.WithVersion(versionOptions);
if (!string.IsNullOrWhiteSpace(tenantId))
predicate = predicate.And(x => x.TenantId == tenantId);
return await ListInternalAsync(cancellationToken).FirstOrDefaultAsync(predicate.Compile(), cancellationToken);
}
public override async ValueTask<IWorkflowBlueprint?> FindByDefinitionVersionIdAsync(string definitionVersionId, string? tenantId = default, CancellationToken cancellationToken = default)
{
Expression<Func<IWorkflowBlueprint, bool>> predicate = x => x.VersionId == definitionVersionId;
if (!string.IsNullOrWhiteSpace(tenantId))
predicate = predicate.And(x => x.TenantId == tenantId);
return await ListInternalAsync(cancellationToken).FirstOrDefaultAsync(predicate.Compile(), cancellationToken);
}
public override async ValueTask<IWorkflowBlueprint?> FindByNameAsync(string name, VersionOptions versionOptions, string? tenantId = default, CancellationToken cancellationToken = default)
{
Expression<Func<IWorkflowBlueprint, bool>> predicate = x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase) && x.WithVersion(versionOptions);
if (!string.IsNullOrWhiteSpace(tenantId))
predicate = predicate.And(x => x.TenantId == tenantId);
return await ListInternalAsync(cancellationToken).FirstOrDefaultAsync(predicate.Compile(), cancellationToken);
}
public override async ValueTask<IWorkflowBlueprint?> FindByTagAsync(string tag, VersionOptions versionOptions, string? tenantId = default, CancellationToken cancellationToken = default)
{
Expression<Func<IWorkflowBlueprint, bool>> predicate = x => string.Equals(x.Tag, tag, StringComparison.OrdinalIgnoreCase) && x.WithVersion(versionOptions);
if (!string.IsNullOrWhiteSpace(tenantId))
predicate = predicate.And(x => x.TenantId == tenantId);
return await ListInternalAsync(cancellationToken).FirstOrDefaultAsync(predicate.Compile(), cancellationToken);
}
public override async ValueTask<IEnumerable<IWorkflowBlueprint>> FindManyByDefinitionIds(IEnumerable<string> definitionIds, VersionOptions versionOptions, CancellationToken cancellationToken = default)
{
var idList = definitionIds.ToList();
return await ListInternalAsync(cancellationToken).Where(x => idList.Contains(x.Id) && x.WithVersion(versionOptions)).ToListAsync(cancellationToken);
}
public override async ValueTask<IEnumerable<IWorkflowBlueprint>> FindManyByDefinitionVersionIds(IEnumerable<string> definitionVersionIds, CancellationToken cancellationToken = default)
{
var idList = definitionVersionIds.ToList();
return await ListInternalAsync(cancellationToken).Where(x => idList.Contains(x.VersionId)).ToListAsync(cancellationToken);
}
public override async ValueTask<IEnumerable<IWorkflowBlueprint>> FindManyByNames(IEnumerable<string> names, CancellationToken cancellationToken = default)
{
var nameList = names.ToList();
return await ListInternalAsync(cancellationToken).Where(x => nameList.Contains(x.VersionId)).ToListAsync(cancellationToken);
}
public override async ValueTask<IEnumerable<IWorkflowBlueprint>> FindManyByTagAsync(string tag, VersionOptions versionOptions, string? tenantId = default, CancellationToken cancellationToken = default) =>
await ListInternalAsync(cancellationToken).Where(x => string.Equals(tag, x.Tag, StringComparison.OrdinalIgnoreCase) && x.WithVersion(versionOptions)).ToListAsync(cancellationToken);
private async IAsyncEnumerable<IWorkflowBlueprint> ListInternalAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var blobs = await _storage.ListFilesAsync(new ListOptions(), cancellationToken);
foreach (var blob in blobs)
{
var json = await _storage.ReadTextAsync(blob.FullPath, Encoding.UTF8, cancellationToken);
var model = _contentSerializer.Deserialize<WorkflowDefinition>(json);
var blueprint = await TryMaterializeBlueprintAsync(model, cancellationToken);
if (blueprint != null)
yield return blueprint;
}
}
private async Task<IWorkflowBlueprint?> TryMaterializeBlueprintAsync(WorkflowDefinition workflowDefinition, CancellationToken cancellationToken)
{
try
{
return await _workflowBlueprintMaterializer.CreateWorkflowBlueprintAsync(workflowDefinition, cancellationToken);
}
catch (Exception e)
{
_logger.LogWarning(e, "Failed to materialize workflow definition {WorkflowDefinitionId} with version {WorkflowDefinitionVersion}", workflowDefinition.DefinitionId, workflowDefinition.Version);
}
return null;
}
}
} | 49.610778 | 213 | 0.704043 | [
"MIT"
] | PBBlox/elsa-core | src/core/Elsa.Core/Providers/Workflows/BlobStorageWorkflowProvider.cs | 8,287 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RogueFlashNetCoreMvc.Daos;
using RogueFlashNetCoreMvc.Model;
using System;
using System.Threading.Tasks;
namespace RogueFlashNetCoreMvc.Controllers
{
public class AjaxSaveCardController : AbstractController
{
public AjaxSaveCardController(
AppDbContext dbContext,
ILoggerFactory loggerFactory)
: base(dbContext, loggerFactory)
{
//
}
[HttpPost]
public async Task<JsonResult> Index(int cardId)
{
try
{
await SaveCard(cardId);
return GetEmptyJson();
}
catch (Exception e)
{
Logger.LogDebug(e.Message);
return GetEmptyJsonError();
}
}
private async Task SaveCard(int cardId)
{
using (var cardDao = new CardDao(DbContext))
{
var card = await cardDao.GetCardWithInstances(cardId);
if (card == null)
{
return;
}
var updated = await TryUpdateModelAsync(
card,
"",
e => e.SideA,
e => e.SideB,
e => e.Notes,
e => e.Tags);
if (!updated)
{
throw new ArgumentException();
}
card.GetInstanceSideBToA().Disabled = !GetBooleanParameter("sideBToA");
await cardDao.UpdateCard(card);
}
}
}
}
| 25.455882 | 87 | 0.464471 | [
"Unlicense"
] | RogueModron/RogueFlashNetCoreMvc | src/RogueFlashNetCoreMvc/Controllers/Ajax/AjaxSaveCardController.cs | 1,733 | C# |
using CarsVelingrad.ViewModels;
namespace CarsVelingrad.Services
{
public interface IVehicleService
{
void Create(VehicleInputViewModel inputModel);
VehiclesViewModel GetVehicles(int pageNumber = 1);
TopVehicleViewModel GetTopExpensiveVehicles();
TopVehicleViewModel SearchByPrice();
TopVehicleViewModel GetLastAddedVehicles();
SearchVehiclesViewModel SearchByPrice(int minPrice, int maxPrice, int pageNumber);
bool DeleteVehicle(int id);
}
} | 24.666667 | 90 | 0.727799 | [
"MIT"
] | Kalin1603/CarsVelingrad | CarsVelingrad/CarsVelingrad.Services/IVehicleService.cs | 520 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
namespace OrderManager
{
[Serializable]
public class Order
{
public Order()
{
OrderId = 0;
Details = new List<OrderDetails>();
}
public Order(string productName, int productNum, string customerName, decimal orderAmount)
: this(0, productName, productNum, customerName, orderAmount)
{
}
public Order(string customerName, decimal orderAmount, params OrderDetails[] details)
: this(0, customerName, orderAmount, details)
{
}
public Order(int orderId, string productName, int productNum, string customerName, decimal orderAmount)
{
OrderId = orderId;
CustomerName = customerName;
OrderAmount = orderAmount;
Details = new List<OrderDetails>() { new OrderDetails(productName, productNum) };
}
public Order(int orderId, string customerName, decimal orderAmount, params OrderDetails[] details)
{
CustomerName = customerName;
OrderAmount = orderAmount;
OrderId = orderId;
Details = new List<OrderDetails>(details);
}
public Order(Order o)
{
OrderId = o.OrderId;
CustomerName = o.CustomerName;
OrderAmount = o.OrderAmount;
Details = o.Details.Select(od=>new OrderDetails(od)).ToList();
}
/// <summary>
/// 订单号
/// </summary>
//[Key]
public int OrderId { get; set; }
/// <summary>
/// 顾客名称
/// </summary>
public string CustomerName { get; set; }
/// <summary>
/// 价格,是不是应该根据订单详情计算更好?
/// 算了x偷懒
/// </summary>
public decimal OrderAmount { get; set; }
public int DetailCount
{
get
{
return Details?.Count ?? 0;
}
}
public List<OrderDetails> Details { get; set; }
public override string ToString()
{
return $"订单号: {OrderId}, 订单价格: {OrderAmount}, 客户名称: {CustomerName}, 订单详情:[{string.Join<OrderDetails>(",", Details)}]";
}
public override int GetHashCode()
{
int hashCode = -1723691444;
hashCode = hashCode * -1521134295 + OrderId.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(CustomerName);
hashCode = hashCode * -1521134295 + OrderAmount.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<List<OrderDetails>>.Default.GetHashCode(Details);
return hashCode;
}
public override bool Equals(object obj)
{
return obj is Order order &&
OrderId == order.OrderId &&
CustomerName == order.CustomerName &&
OrderAmount == order.OrderAmount &&
((Details == null && order.Details == null) ||
((Details != null && order.Details != null) &&
Enumerable.SequenceEqual(Details, order.Details)));
}
}
}
| 31.533333 | 130 | 0.552401 | [
"Apache-2.0"
] | warmthdawn/software_construction_homework | Exercise11/OrderManagerFramework/Order.cs | 3,405 | C# |
using System.Collections.Generic;
using TheoryTestCustomDataAttribute.Models;
namespace TheoryTestCustomDataAttribute.Services
{
public interface ICourseService
{
bool Enroll(Student student);
int Enroll(List<Student> group);
}
}
| 20.076923 | 48 | 0.739464 | [
"MIT"
] | leealso/blog-examples | xUnitCustomDataAttribute/xUnitCustomDataAttribute/Services/ICourseService.cs | 263 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Bing.ImageSearch
{
using Microsoft.Rest;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ImagesOperations operations.
/// </summary>
public partial interface IImagesOperations
{
/// <summary>
/// The Image Search API lets you send a search query to Bing and get
/// back a list of relevant images. This section provides technical
/// details about the query parameters and headers that you use to
/// request images and the JSON response objects that contain them. For
/// examples that show how to make requests, see [Searching the Web for
/// Images](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// </summary>
/// <param name='query'>
/// The user's search query term. The term cannot be empty. The term
/// may contain [Bing Advanced
/// Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
/// example, to limit images to a specific domain, use the
/// [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator.
/// To help improve relevance of an insights query (see
/// [insightsToken](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)),
/// you should always include the user's query term. Use this parameter
/// only with the Image Search API.Do not specify this parameter when
/// calling the Trending Images API.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user
/// interface strings. The list is in decreasing order of preference.
/// For additional information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// This header and the
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive; do not specify both. If you
/// set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter. To determine the market to return results for,
/// Bing uses the first supported language it finds from the list and
/// combines it with the cc parameter value. If the list does not
/// include a supported language, Bing finds the closest language and
/// market that supports the request or it uses an aggregated or
/// default market for the results. To determine the market that Bing
/// used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameters. A user interface string is a string that's used
/// as a label in a user interface. There are few user interface
/// strings in the JSON response objects. Any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to
/// provide mobile users with an optimized experience. Although
/// optional, you are encouraged to always specify this header. The
/// user-agent should be the same string that any commonly used browser
/// sends. For information about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone:
/// Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
/// IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla /
/// 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
/// GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0
/// Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS
/// 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile
/// / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko.
/// iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit /
/// 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari /
/// 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior
/// across Bing API calls. Bing often flights new features and
/// improvements, and it uses the client ID as a key for assigning
/// traffic on different flights. If you do not use the same client ID
/// for a user across multiple requests, then Bing may assign the user
/// to multiple conflicting flights. Being assigned to multiple
/// conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight
/// assignment than the first, the experience may be unexpected. Also,
/// Bing can use the client ID to tailor web results to that client
/// ID’s search history, providing a richer experience for the user.
/// Bing also uses this header to help improve result rankings by
/// analyzing the activity generated by a client ID. The relevance
/// improvements help with better quality of results delivered by Bing
/// APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this
/// header required. Persisting the client ID across multiple requests
/// for the same end user and device combination enables 1) the API
/// consumer to receive a consistent user experience, and 2) higher
/// click-through rates via better quality of results from the Bing
/// APIs. Each user that uses your application on the device must have
/// a unique, Bing generated client ID. If you do not include this
/// header in the request, Bing generates an ID and returns it in the
/// X-MSEdge-ClientID response header. The only time that you should
/// NOT include this header in a request is the first time the user
/// uses your app on that device. Use the client ID for each Bing API
/// request that your app makes for this user on the device. Persist
/// the client ID. To persist the ID in a browser app, use a persistent
/// HTTP cookie to ensure the ID is used across all sessions. Do not
/// use a session cookie. For other apps such as mobile apps, use the
/// device's persistent storage to persist the ID. The next time the
/// user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If
/// the response includes this header, capture the client ID and use it
/// for all subsequent Bing requests for the user on that device. If
/// you include the X-MSEdge-ClientID, you must not include cookies in
/// the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is
/// used to discover the user's location. Bing uses the location
/// information to determine safe search behavior. Although optional,
/// you are encouraged to always specify this header and the
/// X-Search-Location header. Do not obfuscate the address (for
/// example, by changing the last octet to 0). Obfuscating the address
/// results in the location not being anywhere near the device's actual
/// location, which may result in Bing serving erroneous results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the
/// client's geographical location. Bing uses the location information
/// to determine safe search behavior and to return relevant local
/// content. Specify the key/value pair as <key>:<value>.
/// The following are the keys that you use to specify the user's
/// location. lat (required): The latitude of the client's location, in
/// degrees. The latitude must be greater than or equal to -90.0 and
/// less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long
/// (required): The longitude of the client's location, in degrees. The
/// longitude must be greater than or equal to -180.0 and less than or
/// equal to +180.0. Negative values indicate western longitudes and
/// positive values indicate eastern longitudes. re (required): The
/// radius, in meters, which specifies the horizontal accuracy of the
/// coordinates. Pass the value returned by the device's location
/// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell
/// tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the
/// location. (The UNIX timestamp is the number of seconds since
/// January 1, 1970.) head (optional): The client's relative heading or
/// direction of travel. Specify the direction of travel as degrees
/// from 0 through 360, counting clockwise relative to true north.
/// Specify this key only if the sp key is nonzero. sp (optional): The
/// horizontal velocity (speed), in meters per second, that the client
/// device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that
/// specifies the vertical accuracy of the coordinates. Specify this
/// key only if you specify the alt key. Although many of the keys are
/// optional, the more information that you provide, the more accurate
/// the location results are. Although optional, you are encouraged to
/// always specify the user's geographical location. Providing the
/// location is especially important if the client's IP address does
/// not accurately reflect the user's physical location (for example,
/// if the client uses VPN). For optimal results, you should include
/// this header and the X-MSEdge-ClientIP header, but at a minimum, you
/// should include this header.
/// </param>
/// <param name='aspect'>
/// Filter images by the following aspect ratios. All: Do not filter by
/// aspect.Specifying this value is the same as not specifying the
/// aspect parameter. Square: Return images with standard aspect ratio.
/// Wide: Return images with wide screen aspect ratio. Tall: Return
/// images with tall aspect ratio. Possible values include: 'All',
/// 'Square', 'Wide', 'Tall'
/// </param>
/// <param name='color'>
/// Filter images by the following color options. ColorOnly: Return
/// color images. Monochrome: Return black and white images. Return
/// images with one of the following dominant colors: Black, Blue,
/// Brown, Gray, Green, Orange, Pink, Purple, Red, Teal, White, Yellow.
/// Possible values include: 'ColorOnly', 'Monochrome', 'Black',
/// 'Blue', 'Brown', 'Gray', 'Green', 'Orange', 'Pink', 'Purple',
/// 'Red', 'Teal', 'White', 'Yellow'
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come
/// from. For a list of possible values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// If you set this parameter, you must also specify the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// header. Bing uses the first supported language it finds from the
/// languages list, and combine that language with the country code
/// that you specify to determine the market to return results for. If
/// the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or
/// it may use an aggregated or default market for the results instead
/// of a specified one. You should use this query parameter and the
/// Accept-Language query parameter only if you specify multiple
/// languages; otherwise, you should use the mkt and setLang query
/// parameters. This parameter and the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='count'>
/// The number of images to return in the response. The actual number
/// delivered may be less than requested. The default is 35. The
/// maximum value is 150. You use this parameter along with the offset
/// parameter to page results.For example, if your user interface
/// displays 20 images per page, set count to 20 and offset to 0 to get
/// the first page of results.For each subsequent page, increment
/// offset by 20 (for example, 0, 20, 40). Use this parameter only with
/// the Image Search API.Do not specify this parameter when calling the
/// Insights, Trending Images, or Web Search APIs.
/// </param>
/// <param name='freshness'>
/// Filter images by the following discovery options. Day: Return
/// images discovered by Bing within the last 24 hours. Week: Return
/// images discovered by Bing within the last 7 days. Month: Return
/// images discovered by Bing within the last 30 days. Possible values
/// include: 'Day', 'Week', 'Month'
/// </param>
/// <param name='height'>
/// Filter images that have the specified height, in pixels. You may
/// use this filter with the size filter to return small images that
/// have a height of 150 pixels.
/// </param>
/// <param name='id'>
/// An ID that uniquely identifies an image. Use this parameter to
/// ensure that the specified image is the first image in the list of
/// images that Bing returns. The
/// [Image](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// object's imageId field contains the ID that you set this parameter
/// to.
/// </param>
/// <param name='imageContent'>
/// Filter images by the following content types. Face: Return images
/// that show only a person's face. Portrait: Return images that show
/// only a person's head and shoulders. Possible values include:
/// 'Face', 'Portrait'
/// </param>
/// <param name='imageType'>
/// Filter images by the following image types. AnimatedGif: Return
/// only animated GIFs. Clipart: Return only clip art images. Line:
/// Return only line drawings. Photo: Return only photographs(excluding
/// line drawings, animated Gifs, and clip art). Shopping: Return only
/// images that contain items where Bing knows of a merchant that is
/// selling the items. This option is valid in the en - US market
/// only.Transparent: Return only images with a transparent background.
/// Possible values include: 'AnimatedGif', 'Clipart', 'Line', 'Photo',
/// 'Shopping', 'Transparent'
/// </param>
/// <param name='license'>
/// Filter images by the following license types. All: Do not filter by
/// license type.Specifying this value is the same as not specifying
/// the license parameter. Any: Return images that are under any
/// license type. The response doesn't include images that do not
/// specify a license or the license is unknown. Public: Return images
/// where the creator has waived their exclusive rights, to the fullest
/// extent allowed by law. Share: Return images that may be shared with
/// others. Changing or editing the image might not be allowed. Also,
/// modifying, sharing, and using the image for commercial purposes
/// might not be allowed. Typically, this option returns the most
/// images. ShareCommercially: Return images that may be shared with
/// others for personal or commercial purposes. Changing or editing the
/// image might not be allowed. Modify: Return images that may be
/// modified, shared, and used. Changing or editing the image might not
/// be allowed. Modifying, sharing, and using the image for commercial
/// purposes might not be allowed. ModifyCommercially: Return images
/// that may be modified, shared, and used for personal or commercial
/// purposes. Typically, this option returns the fewest images. For
/// more information about these license types, see [Filter Images By
/// License Type](http://go.microsoft.com/fwlink/?LinkId=309768).
/// Possible values include: 'All', 'Any', 'Public', 'Share',
/// 'ShareCommercially', 'Modify', 'ModifyCommercially'
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the
/// country where the user is making the request from. However, it
/// could be a different country if the user is not located in a
/// country where Bing delivers results. The market must be in the form
/// <language code>-<country code>. For example, en-US. The
/// string is case insensitive. For a list of possible market values,
/// see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// NOTE: If known, you are encouraged to always specify the market.
/// Specifying the market helps Bing route the request and return an
/// appropriate and optimal response. If you specify a market that is
/// not listed in [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview),
/// Bing uses a best fit market code based on an internal mapping that
/// is subject to change. This parameter and the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='maxFileSize'>
/// Filter images that are less than or equal to the specified file
/// size. The maximum file size that you may specify is 520,192 bytes.
/// If you specify a larger value, the API uses 520,192. It is possible
/// that the response may include images that are slightly larger than
/// the specified maximum. You may specify this filter and minFileSize
/// to filter images within a range of file sizes.
/// </param>
/// <param name='maxHeight'>
/// Filter images that have a height that is less than or equal to the
/// specified height. Specify the height in pixels. You may specify
/// this filter and minHeight to filter images within a range of
/// heights. This filter and the height filter are mutually exclusive.
/// </param>
/// <param name='maxWidth'>
/// Filter images that have a width that is less than or equal to the
/// specified width. Specify the width in pixels. You may specify this
/// filter and maxWidth to filter images within a range of widths. This
/// filter and the width filter are mutually exclusive.
/// </param>
/// <param name='minFileSize'>
/// Filter images that are greater than or equal to the specified file
/// size. The maximum file size that you may specify is 520,192 bytes.
/// If you specify a larger value, the API uses 520,192. It is possible
/// that the response may include images that are slightly smaller than
/// the specified minimum. You may specify this filter and maxFileSize
/// to filter images within a range of file sizes.
/// </param>
/// <param name='minHeight'>
/// Filter images that have a height that is greater than or equal to
/// the specified height. Specify the height in pixels. You may specify
/// this filter and maxHeight to filter images within a range of
/// heights. This filter and the height filter are mutually exclusive.
/// </param>
/// <param name='minWidth'>
/// Filter images that have a width that is greater than or equal to
/// the specified width. Specify the width in pixels. You may specify
/// this filter and maxWidth to filter images within a range of widths.
/// This filter and the width filter are mutually exclusive.
/// </param>
/// <param name='offset'>
/// The zero-based offset that indicates the number of images to skip
/// before returning images. The default is 0. The offset should be
/// less than
/// ([totalEstimatedMatches](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// - count). Use this parameter along with the count parameter to page
/// results. For example, if your user interface displays 20 images per
/// page, set count to 20 and offset to 0 to get the first page of
/// results. For each subsequent page, increment offset by 20 (for
/// example, 0, 20, 40). It is possible for multiple pages to include
/// some overlap in results. To prevent duplicates, see
/// [nextOffset](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// Use this parameter only with the Image API. Do not specify this
/// parameter when calling the Trending Images API or the Web Search
/// API.
/// </param>
/// <param name='safeSearch'>
/// Filter images for adult content. The following are the possible
/// filter values. Off: May return images with adult content. If the
/// request is through the Image Search API, the response includes
/// thumbnail images that are clear (non-fuzzy). However, if the
/// request is through the Web Search API, the response includes
/// thumbnail images that are pixelated (fuzzy). Moderate: If the
/// request is through the Image Search API, the response doesn't
/// include images with adult content. If the request is through the
/// Web Search API, the response may include images with adult content
/// (the thumbnail images are pixelated (fuzzy)). Strict: Do not return
/// images with adult content. The default is Moderate. If the request
/// comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and
/// uses Strict. If you use the site: query operator, there is the
/// chance that the response may contain adult content regardless of
/// what the safeSearch query parameter is set to. Use site: only if
/// you are aware of the content on the site and your scenario supports
/// the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='size'>
/// Filter images by the following sizes. All: Do not filter by size.
/// Specifying this value is the same as not specifying the size
/// parameter. Small: Return images that are less than 200x200 pixels.
/// Medium: Return images that are greater than or equal to 200x200
/// pixels but less than 500x500 pixels. Large: Return images that are
/// 500x500 pixels or larger. Wallpaper: Return wallpaper images. You
/// may use this parameter along with the height or width parameters.
/// For example, you may use height and size to request small images
/// that are 150 pixels tall. Possible values include: 'All', 'Small',
/// 'Medium', 'Large', 'Wallpaper'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the
/// language using the ISO 639-1 2-letter language code. For example,
/// the language code for English is EN. The default is EN (English).
/// Although optional, you should always specify the language.
/// Typically, you set setLang to the same language specified by mkt
/// unless the user wants the user interface strings displayed in a
/// different language. This parameter and the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// header are mutually exclusive; do not specify both. A user
/// interface string is a string that's used as a label in a user
/// interface. There are few user interface strings in the JSON
/// response objects. Also, any links to Bing.com properties in the
/// response objects apply the specified language.
/// </param>
/// <param name='width'>
/// Filter images that have the specified width, in pixels. You may use
/// this filter with the size filter to return small images that have a
/// width of 150 pixels.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<Images>> SearchWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string aspect = default(string), string color = default(string), string countryCode = default(string), int? count = default(int?), string freshness = default(string), int? height = default(int?), string id = default(string), string imageContent = default(string), string imageType = default(string), string license = default(string), string market = default(string), long? maxFileSize = default(long?), long? maxHeight = default(long?), long? maxWidth = default(long?), long? minFileSize = default(long?), long? minHeight = default(long?), long? minWidth = default(long?), long? offset = default(long?), string safeSearch = default(string), string size = default(string), string setLang = default(string), int? width = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Image Detail Search API lets you search on Bing and get back
/// insights about an image, such as webpages that include the image.
/// This section provides technical details about the query parameters
/// and headers that you use to request insights of images and the JSON
/// response objects that contain them. For examples that show how to
/// make requests, see [Searching the Web for
/// Images](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// </summary>
/// <param name='query'>
/// The user's search query term. The term cannot be empty. The term
/// may contain [Bing Advanced
/// Operators](http://msdn.microsoft.com/library/ff795620.aspx). For
/// example, to limit images to a specific domain, use the
/// [site:](http://msdn.microsoft.com/library/ff795613.aspx) operator.
/// To help improve relevance of an insights query (see
/// [insightsToken](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)),
/// you should always include the user's query term. Use this parameter
/// only with the Image Search API.Do not specify this parameter when
/// calling the Trending Images API.
/// </param>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user
/// interface strings. The list is in decreasing order of preference.
/// For additional information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// This header and the
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive; do not specify both. If you
/// set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter. To determine the market to return results for,
/// Bing uses the first supported language it finds from the list and
/// combines it with the cc parameter value. If the list does not
/// include a supported language, Bing finds the closest language and
/// market that supports the request or it uses an aggregated or
/// default market for the results. To determine the market that Bing
/// used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameters. A user interface string is a string that's used
/// as a label in a user interface. There are few user interface
/// strings in the JSON response objects. Any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='contentType'>
/// Optional request header. If you set the
/// [modules](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter to RecognizedEntities, you may specify the binary
/// of an image in the body of a POST request. If you specify the image
/// in the body of a POST request, you must specify this header and set
/// its value to multipart/form-data. The maximum image size is 1 MB.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to
/// provide mobile users with an optimized experience. Although
/// optional, you are encouraged to always specify this header. The
/// user-agent should be the same string that any commonly used browser
/// sends. For information about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone:
/// Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
/// IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla /
/// 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
/// GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0
/// Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS
/// 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile
/// / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko.
/// iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit /
/// 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari /
/// 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior
/// across Bing API calls. Bing often flights new features and
/// improvements, and it uses the client ID as a key for assigning
/// traffic on different flights. If you do not use the same client ID
/// for a user across multiple requests, then Bing may assign the user
/// to multiple conflicting flights. Being assigned to multiple
/// conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight
/// assignment than the first, the experience may be unexpected. Also,
/// Bing can use the client ID to tailor web results to that client
/// ID’s search history, providing a richer experience for the user.
/// Bing also uses this header to help improve result rankings by
/// analyzing the activity generated by a client ID. The relevance
/// improvements help with better quality of results delivered by Bing
/// APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this
/// header required. Persisting the client ID across multiple requests
/// for the same end user and device combination enables 1) the API
/// consumer to receive a consistent user experience, and 2) higher
/// click-through rates via better quality of results from the Bing
/// APIs. Each user that uses your application on the device must have
/// a unique, Bing generated client ID. If you do not include this
/// header in the request, Bing generates an ID and returns it in the
/// X-MSEdge-ClientID response header. The only time that you should
/// NOT include this header in a request is the first time the user
/// uses your app on that device. Use the client ID for each Bing API
/// request that your app makes for this user on the device. Persist
/// the client ID. To persist the ID in a browser app, use a persistent
/// HTTP cookie to ensure the ID is used across all sessions. Do not
/// use a session cookie. For other apps such as mobile apps, use the
/// device's persistent storage to persist the ID. The next time the
/// user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If
/// the response includes this header, capture the client ID and use it
/// for all subsequent Bing requests for the user on that device. If
/// you include the X-MSEdge-ClientID, you must not include cookies in
/// the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is
/// used to discover the user's location. Bing uses the location
/// information to determine safe search behavior. Although optional,
/// you are encouraged to always specify this header and the
/// X-Search-Location header. Do not obfuscate the address (for
/// example, by changing the last octet to 0). Obfuscating the address
/// results in the location not being anywhere near the device's actual
/// location, which may result in Bing serving erroneous results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the
/// client's geographical location. Bing uses the location information
/// to determine safe search behavior and to return relevant local
/// content. Specify the key/value pair as <key>:<value>.
/// The following are the keys that you use to specify the user's
/// location. lat (required): The latitude of the client's location, in
/// degrees. The latitude must be greater than or equal to -90.0 and
/// less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long
/// (required): The longitude of the client's location, in degrees. The
/// longitude must be greater than or equal to -180.0 and less than or
/// equal to +180.0. Negative values indicate western longitudes and
/// positive values indicate eastern longitudes. re (required): The
/// radius, in meters, which specifies the horizontal accuracy of the
/// coordinates. Pass the value returned by the device's location
/// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell
/// tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the
/// location. (The UNIX timestamp is the number of seconds since
/// January 1, 1970.) head (optional): The client's relative heading or
/// direction of travel. Specify the direction of travel as degrees
/// from 0 through 360, counting clockwise relative to true north.
/// Specify this key only if the sp key is nonzero. sp (optional): The
/// horizontal velocity (speed), in meters per second, that the client
/// device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that
/// specifies the vertical accuracy of the coordinates. Specify this
/// key only if you specify the alt key. Although many of the keys are
/// optional, the more information that you provide, the more accurate
/// the location results are. Although optional, you are encouraged to
/// always specify the user's geographical location. Providing the
/// location is especially important if the client's IP address does
/// not accurately reflect the user's physical location (for example,
/// if the client uses VPN). For optimal results, you should include
/// this header and the X-MSEdge-ClientIP header, but at a minimum, you
/// should include this header.
/// </param>
/// <param name='cropBottom'>
/// The bottom coordinate of the region to crop. The coordinate is a
/// fractional value of the original image's height and is measured
/// from the top, left corner of the image. Specify the coordinate as a
/// value from 0.0 through 1.0. Use this parameter only with the
/// Insights API. Do not specify this parameter when calling the
/// Images, Trending Images, or Web Search APIs.
/// </param>
/// <param name='cropLeft'>
/// The left coordinate of the region to crop. The coordinate is a
/// fractional value of the original image's height and is measured
/// from the top, left corner of the image. Specify the coordinate as a
/// value from 0.0 through 1.0. Use this parameter only with the
/// Insights API. Do not specify this parameter when calling the
/// Images, Trending Images, or Web Search APIs.
/// </param>
/// <param name='cropRight'>
/// The right coordinate of the region to crop. The coordinate is a
/// fractional value of the original image's height and is measured
/// from the top, left corner of the image. Specify the coordinate as a
/// value from 0.0 through 1.0. Use this parameter only with the
/// Insights API. Do not specify this parameter when calling the
/// Images, Trending Images, or Web Search APIs.
/// </param>
/// <param name='cropTop'>
/// The top coordinate of the region to crop. The coordinate is a
/// fractional value of the original image's height and is measured
/// from the top, left corner of the image. Specify the coordinate as a
/// value from 0.0 through 1.0. Use this parameter only with the
/// Insights API. Do not specify this parameter when calling the
/// Images, Trending Images, or Web Search APIs.
/// </param>
/// <param name='cropType'>
/// The crop type to use when cropping the image based on the
/// coordinates specified in the cal, cat, car, and cab parameters. The
/// following are the possible values. 0: Rectangular (default). Use
/// this parameter only with the Insights API. Do not specify this
/// parameter when calling the Images, Trending Images, or Web Search
/// APIs. Possible values include: 'Rectangular'
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come
/// from. For a list of possible values, see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// If you set this parameter, you must also specify the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// header. Bing uses the first supported language it finds from the
/// languages list, and combine that language with the country code
/// that you specify to determine the market to return results for. If
/// the languages list does not include a supported language, Bing
/// finds the closest language and market that supports the request, or
/// it may use an aggregated or default market for the results instead
/// of a specified one. You should use this query parameter and the
/// Accept-Language query parameter only if you specify multiple
/// languages; otherwise, you should use the mkt and setLang query
/// parameters. This parameter and the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='id'>
/// An ID that uniquely identifies an image. Use this parameter to
/// ensure that the specified image is the first image in the list of
/// images that Bing returns. The
/// [Image](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// object's imageId field contains the ID that you set this parameter
/// to.
/// </param>
/// <param name='imageUrl'>
/// The URL of an image that you want to get insights of. Use this
/// parameter as an alternative to using the insightsToken parameter to
/// specify the image. You may also specify the image by placing the
/// binary of the image in the body of a POST request. If you use the
/// binary option, see the
/// [Content-Type](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// header. The maximum supported image size is 1 MB. Use this
/// parameter only with the Insights API. Do not specify this parameter
/// when calling the Images, Trending Images, or Web Search APIs.
/// </param>
/// <param name='insightsToken'>
/// An image token. The
/// [Image](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// object's
/// [imageInsightsToken](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// contains the token. Specify this parameter to get additional
/// information about an image, such as a caption or shopping source.
/// For a list of the additional information about an image that you
/// can get, see the
/// [modules](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter. Use this parameter only with the Insights API. Do
/// not specify this parameter when calling the Images, Trending
/// Images, or Web Search APIs.
/// </param>
/// <param name='modules'>
/// A comma-delimited list of insights to request. The following are
/// the possible case-insensitive values. All: Return all insights, if
/// available, except RecognizedEntities. BRQ: Best representative
/// query. The query term that best describes the image. Caption: A
/// caption that provides information about the image. If the caption
/// contains entities, the response may include links to images of
/// those entities. Collections: A list of related images. Recipes: A
/// list of recipes for cooking the food shown in the images.
/// PagesIncluding: A list of webpages that include the image.
/// RecognizedEntities: A list of entities (people) that were
/// recognized in the image. NOTE: You may not specify this module with
/// any other module. If you specify it with other modules, the
/// response doesn't include recognized entities. RelatedSearches: A
/// list of related searches made by others. ShoppingSources: A list of
/// merchants where you can buy related offerings. SimilarImages: A
/// list of images that are visually similar to the original image.
/// SimilarProducts: A list of images that contain a product that is
/// similar to a product found in the original image. Tags: Provides
/// characteristics of the type of content found in the image. For
/// example, if the image is of a person, the tags might indicate the
/// person's gender and type of clothes they're wearing. If you specify
/// a module and there is no data for the module, the response object
/// doesn't include the related field. For example, if you specify
/// Caption and it does not exist, the response doesn't include the
/// imageCaption field. To include related searches, the request must
/// include the original query string. Although the original query
/// string is not required for similar images or products, you should
/// always include it because it can help improve relevance and the
/// results. Use this parameter only with the Insights API. Do not
/// specify this parameter when calling the Images, Trending Images, or
/// Web Search APIs.
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the
/// country where the user is making the request from. However, it
/// could be a different country if the user is not located in a
/// country where Bing delivers results. The market must be in the form
/// <language code>-<country code>. For example, en-US. The
/// string is case insensitive. For a list of possible market values,
/// see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// NOTE: If known, you are encouraged to always specify the market.
/// Specifying the market helps Bing route the request and return an
/// appropriate and optimal response. If you specify a market that is
/// not listed in [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview),
/// Bing uses a best fit market code based on an internal mapping that
/// is subject to change. This parameter and the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='safeSearch'>
/// Filter images for adult content. The following are the possible
/// filter values. Off: May return images with adult content. If the
/// request is through the Image Search API, the response includes
/// thumbnail images that are clear (non-fuzzy). However, if the
/// request is through the Web Search API, the response includes
/// thumbnail images that are pixelated (fuzzy). Moderate: If the
/// request is through the Image Search API, the response doesn't
/// include images with adult content. If the request is through the
/// Web Search API, the response may include images with adult content
/// (the thumbnail images are pixelated (fuzzy)). Strict: Do not return
/// images with adult content. The default is Moderate. If the request
/// comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and
/// uses Strict. If you use the site: query operator, there is the
/// chance that the response may contain adult content regardless of
/// what the safeSearch query parameter is set to. Use site: only if
/// you are aware of the content on the site and your scenario supports
/// the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the
/// language using the ISO 639-1 2-letter language code. For example,
/// the language code for English is EN. The default is EN (English).
/// Although optional, you should always specify the language.
/// Typically, you set setLang to the same language specified by mkt
/// unless the user wants the user interface strings displayed in a
/// different language. This parameter and the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// header are mutually exclusive; do not specify both. A user
/// interface string is a string that's used as a label in a user
/// interface. There are few user interface strings in the JSON
/// response objects. Also, any links to Bing.com properties in the
/// response objects apply the specified language.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<ImageInsights>> DetailsWithHttpMessagesAsync(string query, string acceptLanguage = default(string), string contentType = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), double? cropBottom = default(double?), double? cropLeft = default(double?), double? cropRight = default(double?), double? cropTop = default(double?), string cropType = default(string), string countryCode = default(string), string id = default(string), string imageUrl = default(string), string insightsToken = default(string), IList<string> modules = default(IList<string>), string market = default(string), string safeSearch = default(string), string setLang = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// The Image Trending Search API lets you search on Bing and get back
/// a list of images that are trending based on search requests made by
/// others. The images are broken out into different categories. For
/// example, Popular People Searches. For a list of markets that
/// support trending images, see [Trending
/// Images](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// </summary>
/// <param name='acceptLanguage'>
/// A comma-delimited list of one or more languages to use for user
/// interface strings. The list is in decreasing order of preference.
/// For additional information, including expected format, see
/// [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html).
/// This header and the
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive; do not specify both. If you
/// set this header, you must also specify the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter. To determine the market to return results for,
/// Bing uses the first supported language it finds from the list and
/// combines it with the cc parameter value. If the list does not
/// include a supported language, Bing finds the closest language and
/// market that supports the request or it uses an aggregated or
/// default market for the results. To determine the market that Bing
/// used, see the BingAPIs-Market header. Use this header and the cc
/// query parameter only if you specify multiple languages. Otherwise,
/// use the
/// [mkt](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// and
/// [setLang](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameters. A user interface string is a string that's used
/// as a label in a user interface. There are few user interface
/// strings in the JSON response objects. Any links to Bing.com
/// properties in the response objects apply the specified language.
/// </param>
/// <param name='userAgent'>
/// The user agent originating the request. Bing uses the user agent to
/// provide mobile users with an optimized experience. Although
/// optional, you are encouraged to always specify this header. The
/// user-agent should be the same string that any commonly used browser
/// sends. For information about user agents, see [RFC
/// 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The
/// following are examples of user-agent strings. Windows Phone:
/// Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0;
/// IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla /
/// 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build /
/// GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0
/// Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS
/// 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile
/// / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0
/// (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko.
/// iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit /
/// 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari /
/// 9537.53
/// </param>
/// <param name='clientId'>
/// Bing uses this header to provide users with consistent behavior
/// across Bing API calls. Bing often flights new features and
/// improvements, and it uses the client ID as a key for assigning
/// traffic on different flights. If you do not use the same client ID
/// for a user across multiple requests, then Bing may assign the user
/// to multiple conflicting flights. Being assigned to multiple
/// conflicting flights can lead to an inconsistent user experience.
/// For example, if the second request has a different flight
/// assignment than the first, the experience may be unexpected. Also,
/// Bing can use the client ID to tailor web results to that client
/// ID’s search history, providing a richer experience for the user.
/// Bing also uses this header to help improve result rankings by
/// analyzing the activity generated by a client ID. The relevance
/// improvements help with better quality of results delivered by Bing
/// APIs and in turn enables higher click-through rates for the API
/// consumer. IMPORTANT: Although optional, you should consider this
/// header required. Persisting the client ID across multiple requests
/// for the same end user and device combination enables 1) the API
/// consumer to receive a consistent user experience, and 2) higher
/// click-through rates via better quality of results from the Bing
/// APIs. Each user that uses your application on the device must have
/// a unique, Bing generated client ID. If you do not include this
/// header in the request, Bing generates an ID and returns it in the
/// X-MSEdge-ClientID response header. The only time that you should
/// NOT include this header in a request is the first time the user
/// uses your app on that device. Use the client ID for each Bing API
/// request that your app makes for this user on the device. Persist
/// the client ID. To persist the ID in a browser app, use a persistent
/// HTTP cookie to ensure the ID is used across all sessions. Do not
/// use a session cookie. For other apps such as mobile apps, use the
/// device's persistent storage to persist the ID. The next time the
/// user uses your app on that device, get the client ID that you
/// persisted. Bing responses may or may not include this header. If
/// the response includes this header, capture the client ID and use it
/// for all subsequent Bing requests for the user on that device. If
/// you include the X-MSEdge-ClientID, you must not include cookies in
/// the request.
/// </param>
/// <param name='clientIp'>
/// The IPv4 or IPv6 address of the client device. The IP address is
/// used to discover the user's location. Bing uses the location
/// information to determine safe search behavior. Although optional,
/// you are encouraged to always specify this header and the
/// X-Search-Location header. Do not obfuscate the address (for
/// example, by changing the last octet to 0). Obfuscating the address
/// results in the location not being anywhere near the device's actual
/// location, which may result in Bing serving erroneous results.
/// </param>
/// <param name='location'>
/// A semicolon-delimited list of key/value pairs that describe the
/// client's geographical location. Bing uses the location information
/// to determine safe search behavior and to return relevant local
/// content. Specify the key/value pair as <key>:<value>.
/// The following are the keys that you use to specify the user's
/// location. lat (required): The latitude of the client's location, in
/// degrees. The latitude must be greater than or equal to -90.0 and
/// less than or equal to +90.0. Negative values indicate southern
/// latitudes and positive values indicate northern latitudes. long
/// (required): The longitude of the client's location, in degrees. The
/// longitude must be greater than or equal to -180.0 and less than or
/// equal to +180.0. Negative values indicate western longitudes and
/// positive values indicate eastern longitudes. re (required): The
/// radius, in meters, which specifies the horizontal accuracy of the
/// coordinates. Pass the value returned by the device's location
/// service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell
/// tower triangulation, and 18,000m for reverse IP lookup. ts
/// (optional): The UTC UNIX timestamp of when the client was at the
/// location. (The UNIX timestamp is the number of seconds since
/// January 1, 1970.) head (optional): The client's relative heading or
/// direction of travel. Specify the direction of travel as degrees
/// from 0 through 360, counting clockwise relative to true north.
/// Specify this key only if the sp key is nonzero. sp (optional): The
/// horizontal velocity (speed), in meters per second, that the client
/// device is traveling. alt (optional): The altitude of the client
/// device, in meters. are (optional): The radius, in meters, that
/// specifies the vertical accuracy of the coordinates. Specify this
/// key only if you specify the alt key. Although many of the keys are
/// optional, the more information that you provide, the more accurate
/// the location results are. Although optional, you are encouraged to
/// always specify the user's geographical location. Providing the
/// location is especially important if the client's IP address does
/// not accurately reflect the user's physical location (for example,
/// if the client uses VPN). For optimal results, you should include
/// this header and the X-MSEdge-ClientIP header, but at a minimum, you
/// should include this header.
/// </param>
/// <param name='countryCode'>
/// A 2-character country code of the country where the results come
/// from. This API supports only the United States, Canada, Australia,
/// and China markets. If you specify this query parameter, it must be
/// set to us, ca, au, or cn. If you set this parameter, you must also
/// specify the Accept-Language header. Bing uses the first supported
/// language it finds from the languages list, and combine that
/// language with the country code that you specify to determine the
/// market to return results for. If the languages list does not
/// include a supported language, Bing finds the closest language and
/// market that supports the request, or it may use an aggregated or
/// default market for the results instead of a specified one. You
/// should use this query parameter and the Accept-Language query
/// parameter only if you specify multiple languages; otherwise, you
/// should use the mkt and setLang query parameters. This parameter and
/// the mkt query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='market'>
/// The market where the results come from. Typically, mkt is the
/// country where the user is making the request from. However, it
/// could be a different country if the user is not located in a
/// country where Bing delivers results. The market must be in the form
/// <language code>-<country code>. For example, en-US. The
/// string is case insensitive. For a list of possible market values,
/// see [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview).
/// NOTE: If known, you are encouraged to always specify the market.
/// Specifying the market helps Bing route the request and return an
/// appropriate and optimal response. If you specify a market that is
/// not listed in [Market
/// Codes](https://docs.microsoft.com/en-us/bing/bing-image-search/overview),
/// Bing uses a best fit market code based on an internal mapping that
/// is subject to change. This parameter and the
/// [cc](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// query parameter are mutually exclusive—do not specify both.
/// </param>
/// <param name='safeSearch'>
/// Filter images for adult content. The following are the possible
/// filter values. Off: May return images with adult content. If the
/// request is through the Image Search API, the response includes
/// thumbnail images that are clear (non-fuzzy). However, if the
/// request is through the Web Search API, the response includes
/// thumbnail images that are pixelated (fuzzy). Moderate: If the
/// request is through the Image Search API, the response doesn't
/// include images with adult content. If the request is through the
/// Web Search API, the response may include images with adult content
/// (the thumbnail images are pixelated (fuzzy)). Strict: Do not return
/// images with adult content. The default is Moderate. If the request
/// comes from a market that Bing's adult policy requires that
/// safeSearch is set to Strict, Bing ignores the safeSearch value and
/// uses Strict. If you use the site: query operator, there is the
/// chance that the response may contain adult content regardless of
/// what the safeSearch query parameter is set to. Use site: only if
/// you are aware of the content on the site and your scenario supports
/// the possibility of adult content. Possible values include: 'Off',
/// 'Moderate', 'Strict'
/// </param>
/// <param name='setLang'>
/// The language to use for user interface strings. Specify the
/// language using the ISO 639-1 2-letter language code. For example,
/// the language code for English is EN. The default is EN (English).
/// Although optional, you should always specify the language.
/// Typically, you set setLang to the same language specified by mkt
/// unless the user wants the user interface strings displayed in a
/// different language. This parameter and the
/// [Accept-Language](https://docs.microsoft.com/en-us/bing/bing-image-search/overview)
/// header are mutually exclusive; do not specify both. A user
/// interface string is a string that's used as a label in a user
/// interface. There are few user interface strings in the JSON
/// response objects. Also, any links to Bing.com properties in the
/// response objects apply the specified language.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<HttpOperationResponse<TrendingImages>> TrendingWithHttpMessagesAsync(string acceptLanguage = default(string), string userAgent = default(string), string clientId = default(string), string clientIp = default(string), string location = default(string), string countryCode = default(string), string market = default(string), string safeSearch = default(string), string setLang = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 68.126719 | 1,123 | 0.654319 | [
"MIT"
] | josmperez1/bing-search-sdk-for-net-1 | sdk/ImageSearch/src/Generated/IImagesOperations.cs | 69,371 | 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("02.Get-largest-number")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.Get-largest-number")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("277a8ca6-5880-415a-8df3-591f26d65814")]
// 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")]
| 38.243243 | 84 | 0.74417 | [
"MIT"
] | YaneYosifov/Telerik | C# Part II/Homeworks/03.Methods/02.Get-largest-number/Properties/AssemblyInfo.cs | 1,418 | C# |
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Movies.Client.Interactive.Controllers
{
[Authorize]
public class AccountController : Controller
{
public IActionResult AccessDenied()
{
return View();
}
}
}
| 17.066667 | 47 | 0.761719 | [
"MIT"
] | Khatami/SecureMicroservices | src/WebApp/Movies.Client.Interactive/Controllers/AccountController.cs | 258 | C# |
using System;
using System.Reflection;
using Newtonsoft.Json.Linq;
namespace Grouper2.GPPAssess
{
public partial class AssessGpp
{
private readonly JObject _gpp;
public AssessGpp(JObject gpp)
{
_gpp = gpp;
}
public JObject GetAssessed(string assessName)
{
//construct the method name based on the assessName and get it using reflection
MethodInfo mi = GetType().GetMethod("GetAssessed" + assessName, BindingFlags.NonPublic | BindingFlags.Instance);
//invoke the found method
try
{
JObject gppToAssess = (JObject)_gpp[assessName];
if (mi != null)
{
JObject assessedThing = (JObject)mi.Invoke(this, parameters: new object[] { gppToAssess });
if (assessedThing != null)
{
return assessedThing;
}
else
{
Utility.Output.DebugWrite("GetAssessed" + assessName + " didn't return anything. This isn't a problem in itself, it just means that nothing met the interest level criteria. This message is only for debugging.");
return null;
}
}
else
{
Utility.Output.DebugWrite("Failed to find method: GetAssessed" + assessName + ". This probably just means I never wrote one. If you think that Group Policy Preferences " + assessName + " are likely to have useful stuff in there, let me know on GitHub?");
return null;
}
}
catch (Exception e)
{
Utility.Output.DebugWrite(e.ToString());
return null;
}
}
}
}
| 36.339623 | 274 | 0.509346 | [
"MIT"
] | FDlucifer/Grouper2 | Grouper2/Assess/GPPAssess/AssessGpp.cs | 1,928 | 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;
namespace Calculos_Basicos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
}
private void btnLimpar_Click(object sender, EventArgs e)
{
txtNume1.Text = ""; //fara com que o campo seja limpo ao clicar no bt limpar
txtNume2.Text = "";
txtResultado.Text = "";
}
private void btnSair_Click(object sender, EventArgs e)
{
Close();
}
private void btnSomar_Click(object sender, EventArgs e)
{
double num1, num2, resultado;
num1 = Convert.ToDouble(txtNume1.Text);
num2 = Convert.ToDouble(txtNume2.Text);
resultado = num1 + num2;
txtResultado.Text = resultado.ToString();
}
private void btnSubtrair_Click(object sender, EventArgs e)
{
double num1, num2, resultado;
num1 = Convert.ToDouble(txtNume1.Text);
num2 = Convert.ToDouble(txtNume2.Text);
resultado = num1 - num2;
txtResultado.Text = resultado.ToString();
}
private void btnMultiplicar_Click(object sender, EventArgs e)
{
double num1, num2, resultado;
num1 = Convert.ToDouble(txtNume1.Text);
num2 = Convert.ToDouble(txtNume2.Text);
resultado = num1 * num2;
txtResultado.Text = resultado.ToString();
}
private void btnDividir_Click(object sender, EventArgs e)
{
double num1, num2, resultado;
num1 = Convert.ToDouble(txtNume1.Text);
num2 = Convert.ToDouble(txtNume2.Text);
resultado = num1 / num2;
txtResultado.Text = resultado.ToString();
}
}
}
| 28.106667 | 88 | 0.58112 | [
"MIT"
] | luana-karlla/Curso-CSharp-Basico | Curso Csharp Basico/Calculos_Basicos/Form1.cs | 2,110 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Twisty.Engine.Presenters.Rubiks
{
public interface IRubikBlockFaceTextView
{
/// <summary>
/// Get shte specified line to display in the console.
/// </summary>
/// <param name="i">Index of the line to display.</param>
/// <returns>Line to display for the requested index of the view.</returns>
string GetLine(int i);
/// <summary>
/// Gets the id of the color used to display this face in the console.
/// </summary>
string Color { get; }
/// <summary>
/// Gets the collection of lines to display in the console for this Block face.
/// </summary>
IEnumerable<string> Lines { get; }
}
} | 26.884615 | 81 | 0.680973 | [
"MIT"
] | jardons/twisty-engine | Twisty.Engine/Presenters/Rubiks/IRubikBlockFaceTextView.cs | 701 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class sfxWalking : MonoBehaviour {
// Use this for initialization
private HeroMovement hm;
public AudioSource sfxFootstep;
public AudioSource sfxJump;
//private bool doublejump = false;
private bool candoublejump = false;
private bool isKitty = false;
private int jumpCount = 0;
void Start () {
hm = GetComponent<HeroMovement>();
if (gameObject.name == "Kitty(Clone)" || gameObject.name == "Kitty")
{
isKitty = true;
}
}
// Update is called once per frame
void Update () {
//walking sfx
if((hm.grounded || hm.grounded2) && hm.currentSpeed != 0 && sfxFootstep.isPlaying == false)
{
sfxFootstep.pitch = Random.Range(1.2f, 1.5f);
sfxFootstep.Play();
}
//jumping sfx
if(hm.jump == true && sfxJump.isPlaying == false)
{
sfxJump.pitch = Random.Range(1.0f, 1.3f);
sfxJump.Play();
}
else if (candoublejump && isKitty && hm.doublejump == true)
{
sfxJump.pitch = Random.Range(1.4f, 1.7f);
sfxJump.Play();
}
else if (isKitty && jumpCount == 0 && hm.doublejump == true)
{
sfxJump.pitch = Random.Range(1.4f, 1.7f);
sfxJump.Play();
}
}
}
| 27.115385 | 93 | 0.558865 | [
"Apache-2.0"
] | Panther450/450Game | NEFMA/Assets/Scripts/sfxWalking.cs | 1,412 | 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("06.FixEmails")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("06.FixEmails")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2017")]
[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("cd290e1e-5414-4d1c-bf08-4cbe025f8551")]
// 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")]
| 38.432432 | 84 | 0.750352 | [
"MIT"
] | ShadyObeyd/ProgrammingFundamentals-Homeworks | 18.FilesAndExceptions-Exercises/06.FixEmails/Properties/AssemblyInfo.cs | 1,425 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/winioctl.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public enum DEVICE_INTERNAL_STATUS_DATA_SET
{
DeviceStatusDataSetUndefined = 0,
DeviceStatusDataSet1,
DeviceStatusDataSet2,
DeviceStatusDataSet3,
DeviceStatusDataSet4,
DeviceStatusDataSetMax,
}
}
| 31.722222 | 145 | 0.728546 | [
"MIT"
] | Ethereal77/terrafx.interop.windows | sources/Interop/Windows/um/winioctl/DEVICE_INTERNAL_STATUS_DATA_SET.cs | 573 | C# |
using AmbientFuckery.Pocos;
using SixLabors.ImageSharp;
namespace AmbientFuckery.Contracts
{
public interface IImageManipulator
{
IImageInfo ParseImage(ImageData image);
}
} | 19.5 | 47 | 0.748718 | [
"MIT"
] | JoshuaRichards/AmbientFuckery | AmbientFuckery/Contracts/IImageManipulator.cs | 197 | C# |
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System;
using Pivotal.NetCore.WebApi.Template.Features;
using Pivotal.NetCore.WebApi.Template.Features.Values;
using Xunit;
namespace Pivotal.NetCore.WebApi.Template.Unit.Tests.Models
{
public class ValuesRequestTests
{
[Fact]
public void TestRequestTypes()
{
var request = new GetValues.Request();
Assert.True(request is IRequest);
Assert.True(request is IRequest<GetValues.Response>);
}
[Fact]
public void TestRequestProperties()
{
var request = new GetValues.Request();
Assert.NotNull(request.GetType().GetProperty("Param1"));
Assert.Equal("String", request.GetType().GetProperty("Param1").PropertyType.Name);
Assert.NotNull(request.GetType().GetProperty("Param2"));
Assert.Equal("String", request.GetType().GetProperty("Param2").PropertyType.Name);
}
}
}
| 29.969697 | 94 | 0.646107 | [
"MIT"
] | CedricYao/pivotal-webapi-dotnet-core | Pivotal.NetCore.WebApi.Template/Content/Pivotal.NetCore.WebApi.Template/test/Unit.Tests/Models/ValuesRequestTests.cs | 991 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.CCC;
using Aliyun.Acs.CCC.Transform;
using Aliyun.Acs.CCC.Transform.V20170705;
namespace Aliyun.Acs.CCC.Model.V20170705
{
public class ListJobStatusRequest : RpcAcsRequest<ListJobStatusResponse>
{
public ListJobStatusRequest()
: base("CCC", "2017-07-05", "ListJobStatus")
{
}
private string contactName;
private string instanceId;
private string timeAlignment;
private string groupId;
private string phoneNumber;
private int? pageSize;
private long? endTime;
private long? startTime;
private string scenarioId;
private int? pageNumber;
public string ContactName
{
get
{
return contactName;
}
set
{
contactName = value;
DictionaryUtil.Add(QueryParameters, "ContactName", value);
}
}
public string InstanceId
{
get
{
return instanceId;
}
set
{
instanceId = value;
DictionaryUtil.Add(QueryParameters, "InstanceId", value);
}
}
public string TimeAlignment
{
get
{
return timeAlignment;
}
set
{
timeAlignment = value;
DictionaryUtil.Add(QueryParameters, "TimeAlignment", value);
}
}
public string GroupId
{
get
{
return groupId;
}
set
{
groupId = value;
DictionaryUtil.Add(QueryParameters, "GroupId", value);
}
}
public string PhoneNumber
{
get
{
return phoneNumber;
}
set
{
phoneNumber = value;
DictionaryUtil.Add(QueryParameters, "PhoneNumber", value);
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public long? EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
DictionaryUtil.Add(QueryParameters, "EndTime", value.ToString());
}
}
public long? StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
DictionaryUtil.Add(QueryParameters, "StartTime", value.ToString());
}
}
public string ScenarioId
{
get
{
return scenarioId;
}
set
{
scenarioId = value;
DictionaryUtil.Add(QueryParameters, "ScenarioId", value);
}
}
public int? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString());
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override ListJobStatusResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return ListJobStatusResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 19.346734 | 98 | 0.634286 | [
"Apache-2.0"
] | xueandfeng/aliyun-openapi-net-sdk | aliyun-net-sdk-ccc/CCC/Model/V20170705/ListJobStatusRequest.cs | 3,850 | C# |
using System;
namespace DotNetDesign.Common
{
/// <summary>
/// Defines the method signature of a method to handle the unregister callback.
/// </summary>
/// <typeparam name="TEventHandler"></typeparam>
/// <param name="eventHandler">The event handler.</param>
public delegate void UnregisterCallback<TEventHandler>(EventHandler<TEventHandler> eventHandler)
where TEventHandler : EventArgs;
} | 34.5 | 98 | 0.7343 | [
"MIT"
] | dotnetdesign/Common | src/DotNetDesign.Common/UnregisteredCallback.cs | 416 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.R.Editor.Formatting;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.R.Package.Repl.Commands {
class ReplFormatDocumentCommand : FormatDocumentCommand {
public ReplFormatDocumentCommand(ITextView view, ITextBuffer buffer) : base(view, buffer) { }
public override ITextBuffer TargetBuffer {
get {
return base.TargetBuffer.GetInteractiveWindow().CurrentLanguageBuffer;
}
}
}
}
| 36.5 | 101 | 0.738356 | [
"MIT"
] | AlexanderSher/RTVS-Old | src/Package/Impl/Repl/Commands/ReplFormatDocumentCommand.cs | 732 | C# |
using DataTablesCoreMVCEntity.Models;
using Microsoft.EntityFrameworkCore;
namespace DataTablesCoreMVCEntity.Data
{
public class CustomerContext : DbContext
{
public CustomerContext(DbContextOptions<CustomerContext> options)
: base(options)
{
}
public DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("Customer");
}
}
}
| 23.318182 | 74 | 0.668616 | [
"MIT"
] | peter-schlosser/DataTablesCoreMVCEntity | DataTablesCoreMVCEntity/Data/CustomerContext.cs | 515 | C# |
namespace ooohCar.Client.Infrastructure.Routes
{
public class DashboardEndpoints
{
public static string GetData = "api/v1/dashboard";
}
} | 22.571429 | 58 | 0.696203 | [
"MIT"
] | codeBalok/ooohcarBlazor-backend | ooohCar.Client.Infrastructure/Routes/DashboardEndpoints.cs | 160 | C# |
namespace ContosoUniversity.Models
{
public class Move
{
public int ID { get; set; }
public int ComboID { get; set; }
public int Seq { get; set; }
public string Text { get; set; }
public Combo Combo { get; set; }
}
} | 21.769231 | 42 | 0.522968 | [
"MIT"
] | twoutlook/taichi2021 | ContosoUniversity/Models/Move.cs | 283 | C# |
// <copyright file="MeterProviderBuilderBase.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Text.RegularExpressions;
using OpenTelemetry.Internal;
using OpenTelemetry.Resources;
namespace OpenTelemetry.Metrics
{
/// <summary>
/// Build MeterProvider with Resource, Readers, and Instrumentation.
/// </summary>
public abstract class MeterProviderBuilderBase : MeterProviderBuilder
{
internal const int MaxMetricsDefault = 1000;
internal const int MaxMetricPointsPerMetricDefault = 2000;
private readonly List<InstrumentationFactory> instrumentationFactories = new();
private readonly List<string> meterSources = new();
private readonly List<Func<Instrument, MetricStreamConfiguration>> viewConfigs = new();
private ResourceBuilder resourceBuilder = ResourceBuilder.CreateDefault();
private int maxMetricStreams = MaxMetricsDefault;
private int maxMetricPointsPerMetricStream = MaxMetricPointsPerMetricDefault;
protected MeterProviderBuilderBase()
{
}
internal List<MetricReader> MetricReaders { get; } = new List<MetricReader>();
/// <inheritdoc />
public override MeterProviderBuilder AddInstrumentation<TInstrumentation>(Func<TInstrumentation> instrumentationFactory)
{
Guard.ThrowIfNull(instrumentationFactory);
this.instrumentationFactories.Add(
new InstrumentationFactory(
typeof(TInstrumentation).Name,
"semver:" + typeof(TInstrumentation).Assembly.GetName().Version,
instrumentationFactory));
return this;
}
/// <inheritdoc />
public override MeterProviderBuilder AddMeter(params string[] names)
{
Guard.ThrowIfNull(names);
foreach (var name in names)
{
Guard.ThrowIfNullOrWhitespace(name);
this.meterSources.Add(name);
}
return this;
}
internal MeterProviderBuilder AddReader(MetricReader reader)
{
this.MetricReaders.Add(reader);
return this;
}
internal MeterProviderBuilder AddView(string instrumentName, string name)
{
return this.AddView(
instrumentName,
new MetricStreamConfiguration
{
Name = name,
});
}
internal MeterProviderBuilder AddView(string instrumentName, MetricStreamConfiguration metricStreamConfiguration)
{
if (instrumentName.IndexOf('*') != -1)
{
var pattern = '^' + Regex.Escape(instrumentName).Replace("\\*", ".*");
var regex = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return this.AddView(instrument => regex.IsMatch(instrument.Name) ? metricStreamConfiguration : null);
}
else
{
return this.AddView(instrument => instrument.Name.Equals(instrumentName, StringComparison.OrdinalIgnoreCase) ? metricStreamConfiguration : null);
}
}
internal MeterProviderBuilder AddView(Func<Instrument, MetricStreamConfiguration> viewConfig)
{
this.viewConfigs.Add(viewConfig);
return this;
}
internal MeterProviderBuilder SetMaxMetricStreams(int maxMetricStreams)
{
Guard.ThrowIfOutOfRange(maxMetricStreams, min: 1);
this.maxMetricStreams = maxMetricStreams;
return this;
}
internal MeterProviderBuilder SetMaxMetricPointsPerMetricStream(int maxMetricPointsPerMetricStream)
{
Guard.ThrowIfOutOfRange(maxMetricPointsPerMetricStream, min: 1);
this.maxMetricPointsPerMetricStream = maxMetricPointsPerMetricStream;
return this;
}
internal MeterProviderBuilder SetResourceBuilder(ResourceBuilder resourceBuilder)
{
Debug.Assert(resourceBuilder != null, $"{nameof(resourceBuilder)} must not be null");
this.resourceBuilder = resourceBuilder;
return this;
}
/// <summary>
/// Run the configured actions to initialize the <see cref="MeterProvider"/>.
/// </summary>
/// <returns><see cref="MeterProvider"/>.</returns>
protected MeterProvider Build()
{
return new MeterProviderSdk(
this.resourceBuilder.Build(),
this.meterSources,
this.instrumentationFactories,
this.viewConfigs,
this.maxMetricStreams,
this.maxMetricPointsPerMetricStream,
this.MetricReaders.ToArray());
}
internal readonly struct InstrumentationFactory
{
public readonly string Name;
public readonly string Version;
public readonly Func<object> Factory;
internal InstrumentationFactory(string name, string version, Func<object> factory)
{
this.Name = name;
this.Version = version;
this.Factory = factory;
}
}
}
}
| 36.095808 | 161 | 0.632548 | [
"Apache-2.0"
] | swetharavichandrancisco/opentelemetry-dotnet | src/OpenTelemetry/Metrics/MeterProviderBuilderBase.cs | 6,028 | C# |
// license:BSD-3-Clause
// copyright-holders:Edward Fast
using System;
using System.Collections.Generic;
using game_driver_map = mame.std.unordered_map<string, mame.game_driver>;
using s8 = System.SByte;
using s16 = System.Int16;
using s32 = System.Int32;
using s64 = System.Int64;
using u8 = System.Byte;
using u16 = System.UInt16;
using u32 = System.UInt32;
using u64 = System.UInt64;
using validity_checker_int_map = mame.std.unordered_map<string, object>; //using int_map = std::unordered_map<std::string, uintptr_t>;
using validity_checker_string_set = mame.std.unordered_set<string>; //using string_set = std::unordered_set<std::string>;
namespace mame
{
// core validity checker class
public class validity_checker : osd_output, IDisposable
{
// internal map types
//using game_driver_map = std::unordered_map<std::string, game_driver const *>;
//using int_map = std::unordered_map<std::string, uintptr_t>;
//using string_set = std::unordered_set<std::string>;
// internal driver list
driver_enumerator m_drivlist;
// blank options for use during validation
emu_options m_blank_options;
// error tracking
int m_errors;
int m_warnings;
bool m_print_verbose;
string m_error_text;
string m_warning_text;
string m_verbose_text;
// maps for finding duplicates
game_driver_map m_names_map = new game_driver_map();
game_driver_map m_descriptions_map = new game_driver_map();
game_driver_map m_roms_map = new game_driver_map();
validity_checker_int_map m_defstr_map = new validity_checker_int_map();
// current state
game_driver m_current_driver;
device_t m_current_device;
string m_current_ioport;
validity_checker_int_map m_region_map = new validity_checker_int_map();
validity_checker_string_set m_ioport_set = new validity_checker_string_set();
validity_checker_string_set m_already_checked = new validity_checker_string_set();
bool m_checking_card;
bool m_quick;
//-------------------------------------------------
// validity_checker - constructor
//-------------------------------------------------
public validity_checker(emu_options options, bool quick)
{
m_drivlist = new driver_enumerator(options);
m_errors = 0;
m_warnings = 0;
m_print_verbose = options.verbose();
m_current_driver = null;
m_current_device = null;
m_current_ioport = null;
m_checking_card = false;
m_quick = quick;
// pre-populate the defstr map with all the default strings
for (int strnum = 1; strnum < (int)INPUT_STRING.INPUT_STRING_COUNT; strnum++)
{
string str = ioport_string_from_index((UInt32)strnum);
if (!string.IsNullOrEmpty(str))
m_defstr_map.insert(str, strnum);
}
}
~validity_checker()
{
g.assert(m_isDisposed); // can remove
}
bool m_isDisposed = false;
public void Dispose()
{
validate_end();
m_isDisposed = true;
}
// getters
public int errors() { return m_errors; }
public int warnings() { return m_warnings; }
bool quick() { return m_quick; }
// setter
public void set_verbose(bool verbose) { m_print_verbose = verbose; }
// operations
//void check_driver(const game_driver &driver);
//-------------------------------------------------
// check_shared_source - check all drivers that
// share the same source file as the given driver
//-------------------------------------------------
public void check_shared_source(game_driver driver)
{
// initialize
validate_begin();
// then iterate over all drivers and check the ones that share the same source file
m_drivlist.reset();
while (m_drivlist.next())
{
if (std.strcmp(driver.type.source(), m_drivlist.driver().type.source()) == 0)
validate_one(m_drivlist.driver());
}
// cleanup
validate_end();
}
//-------------------------------------------------
// check_all_matching - check all drivers whose
// names match the given string
//-------------------------------------------------
public bool check_all_matching(string str = "*")
{
// start by checking core stuff
validate_begin();
validate_integer_semantics();
validate_inlines();
validate_rgb();
validate_delegates_mfp();
validate_delegates_latebind();
validate_delegates_functoid();
// if we had warnings or errors, output
if (m_errors > 0 || m_warnings > 0 || !string.IsNullOrEmpty(m_verbose_text))
{
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "Core: {0} errors, {1} warnings\n", m_errors, m_warnings);
if (m_errors > 0)
output_indented_errors(m_error_text, "Errors");
if (m_warnings > 0)
output_indented_errors(m_warning_text, "Warnings");
if (!string.IsNullOrEmpty(m_verbose_text))
output_indented_errors(m_verbose_text, "Messages");
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "\n");
}
// then iterate over all drivers and check them
m_drivlist.reset();
bool validated_any = false;
while (m_drivlist.next())
{
if (driver_list.matches(str, m_drivlist.driver().name))
{
validate_one(m_drivlist.driver());
validated_any = true;
}
}
// validate devices
if (str == null)
validate_device_types();
// cleanup
validate_end();
// if we failed to match anything, it
if (str != null && !validated_any)
throw new emu_fatalerror(g.EMU_ERR_NO_SUCH_SYSTEM, "No matching systems found for '{0}'", str);
return !(m_errors > 0 || m_warnings > 0);
}
// helpers for devices
//void validate_tag(const char *tag);
public int region_length(string tag) { return (int)m_region_map.find(tag); }
public bool ioport_missing(string tag) { return !m_checking_card && (m_ioport_set.find(tag)); }
// generic registry of already-checked stuff
//bool already_checked(const char *string) { return (m_already_checked.add(string, 1, false) == TMERR_DUPLICATE); }
// osd_output interface
//-------------------------------------------------
// error_output - error message output override
//-------------------------------------------------
public override void output_callback(osd_output_channel channel, string format, params object [] args) //virtual void output_callback(osd_output_channel channel, const util::format_argument_pack<std::ostream> &args) override;
{
string output = "";
switch (channel)
{
case osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR:
// count the error
m_errors++;
// output the source(driver) device 'tag'
build_output_prefix(ref output);
// generate the string
output += string.Format(format, args);
m_error_text = m_error_text.append_(output);
break;
case osd_output_channel.OSD_OUTPUT_CHANNEL_WARNING:
// count the error
m_warnings++;
// output the source(driver) device 'tag'
build_output_prefix(ref output);
// generate the string and output to the original target
output += string.Format(format, args);
m_warning_text = m_warning_text.append_(output);
break;
case osd_output_channel.OSD_OUTPUT_CHANNEL_VERBOSE:
// if we're not verbose, skip it
if (!m_print_verbose) break;
// output the source(driver) device 'tag'
build_output_prefix(ref output);
// generate the string and output to the original target
output += string.Format(format, args);
m_verbose_text = m_verbose_text.append_(output);
break;
default:
chain_output(channel, format, args);
break;
}
}
// internal helpers
//int get_defstr_index(const char *string, bool suppress_error = false);
// core helpers
//-------------------------------------------------
// validate_begin - prepare for validation by
// taking over the output callbacks and resetting
// our internal state
//-------------------------------------------------
void validate_begin()
{
// take over error and warning outputs
osd_output.push(this);
// reset all our maps
m_names_map.clear();
m_descriptions_map.clear();
m_roms_map.clear();
m_defstr_map.clear();
m_region_map.clear();
m_ioport_set.clear();
// reset internal state
m_errors = 0;
m_warnings = 0;
m_already_checked.clear();
}
//-------------------------------------------------
// validate_end - restore output callbacks and
// clean up
//-------------------------------------------------
void validate_end()
{
// restore the original output callbacks
osd_output.pop(this);
}
//-------------------------------------------------
// validate_drivers - master validity checker
//-------------------------------------------------
void validate_one(game_driver driver)
{
// help verbose validation detect configuration-related crashes
if (m_print_verbose)
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "Validating driver {0} ({1})...\n", driver.name, g.core_filename_extract_base(driver.type.source()));
// set the current driver
m_current_driver = driver;
m_current_device = null;
m_current_ioport = null;
m_region_map.clear();
m_ioport_set.clear();
m_checking_card = false;
// reset error/warning state
int start_errors = m_errors;
int start_warnings = m_warnings;
m_error_text = "";
m_warning_text = "";
m_verbose_text = "";
// wrap in try/catch to catch fatalerrors
try
{
machine_config config = new machine_config(driver, m_blank_options);
validate_driver(config.root_device());
validate_roms(config.root_device());
validate_inputs(config.root_device());
validate_devices(config);
}
catch (emu_fatalerror err)
{
g.osd_printf_error("Fatal error {0}", err.what());
}
// if we had warnings or errors, output
if (m_errors > start_errors || m_warnings > start_warnings || !string.IsNullOrEmpty(m_verbose_text))
{
if (!m_print_verbose)
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "Driver {0} (file {1}): {2} errors, {3} warnings\n", driver.name, g.core_filename_extract_base(driver.type.source()), m_errors - start_errors, m_warnings - start_warnings);
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "{0} errors, {1} warnings\n", m_errors - start_errors, m_warnings - start_warnings);
if (m_errors > start_errors)
output_indented_errors(m_error_text, "Errors");
if (m_warnings > start_warnings)
output_indented_errors(m_warning_text, "Warnings");
if (!string.IsNullOrEmpty(m_verbose_text))
output_indented_errors(m_verbose_text, "Messages");
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "\n");
}
// reset the driver/device
m_current_driver = null;
m_current_device = null;
m_current_ioport = null;
m_region_map.clear();
m_ioport_set.clear();
m_checking_card = false;
}
// internal sub-checks
//-------------------------------------------------
// validate_integer_semantics - validate that
// integers behave as expected, particularly
// with regards to overflow and shifting
//-------------------------------------------------
void validate_integer_semantics()
{
//throw new emu_unimplemented();
#if false
// basic system checks
if (~0 != -1) osd_printf_error("Machine must be two's complement\n");
#endif
u8 a = 0xff;
u8 b = (u8)(a + 1);
if (b > a) g.osd_printf_error("u8 must be 8 bits\n");
// check size of core integer types
if (sizeof(s8) != 1) g.osd_printf_error("s8 must be 8 bits\n");
if (sizeof(u8) != 1) g.osd_printf_error("u8 must be 8 bits\n");
if (sizeof(s16) != 2) g.osd_printf_error("s16 must be 16 bits\n");
if (sizeof(u16) != 2) g.osd_printf_error("u16 must be 16 bits\n");
if (sizeof(s32) != 4) g.osd_printf_error("s32 must be 32 bits\n");
if (sizeof(u32) != 4) g.osd_printf_error("u32 must be 32 bits\n");
if (sizeof(s64) != 8) g.osd_printf_error("s64 must be 64 bits\n");
if (sizeof(u64) != 8) g.osd_printf_error("u64 must be 64 bits\n");
//throw new emu_unimplemented();
#if false
// check signed right shift
s8 a8 = -3;
s16 a16 = -3;
s32 a32 = -3;
s64 a64 = -3;
if (a8 >> 1 != -2) osd_printf_error("s8 right shift must be arithmetic\n");
if (a16 >> 1 != -2) osd_printf_error("s16 right shift must be arithmetic\n");
if (a32 >> 1 != -2) osd_printf_error("s32 right shift must be arithmetic\n");
if (a64 >> 1 != -2) osd_printf_error("s64 right shift must be arithmetic\n");
#endif
//throw new emu_unimplemented();
#if false
// check pointer size
//#ifdef PTR64
if (sizeof(void *) != 8) osdcore_global.m_osdcore.osd_printf_error("PTR64 flag enabled, but was compiled for 32-bit target\n");
//#else
if (sizeof(void *) != 4) osdcore_global.m_osdcore.osd_printf_error("PTR64 flag not enabled, but was compiled for 64-bit target\n");
//#endif
#endif
//throw new emu_unimplemented();
#if false
// TODO: check if this is actually working
// check endianness definition
UINT16 lsbtest = 0;
*(UINT8 *)&lsbtest = 0xff;
//#ifdef LSB_FIRST
if (lsbtest == 0xff00) osdcore_global.m_osdcore.osd_printf_error("LSB_FIRST specified, but running on a big-endian machine\n");
//#else
if (lsbtest == 0x00ff) osdcore_global.m_osdcore.osd_printf_error("LSB_FIRST not specified, but running on a little-endian machine\n");
//#endif
#endif
}
//-------------------------------------------------
// validate_inlines - validate inline function
// behaviors
//-------------------------------------------------
void validate_inlines()
{
//throw new emu_unimplemented();
}
//-------------------------------------------------
// validate_rgb - validate optimised RGB utility
// class
//-------------------------------------------------
void validate_rgb()
{
//throw new emu_unimplemented();
}
//-------------------------------------------------
// validate_delegates_mfp - test delegate member
// function functionality
//-------------------------------------------------
void validate_delegates_mfp()
{
//throw new emu_unimplemented();
}
//-------------------------------------------------
// validate_delegates_latebind - test binding a
// delegate to an object after the function is
// set
//-------------------------------------------------
void validate_delegates_latebind()
{
}
//-------------------------------------------------
// validate_delegates_functoid - test delegate
// functoid functionality
//-------------------------------------------------
void validate_delegates_functoid()
{
}
//-------------------------------------------------
// validate_driver - validate basic driver
// information
//-------------------------------------------------
void validate_driver(device_t root)
{
//throw new emu_unimplemented();
}
//-------------------------------------------------
// validate_roms - validate ROM definitions
//-------------------------------------------------
void validate_roms(device_t root)
{
//throw new emu_unimplemented();
}
//void validate_analog_input_field(ioport_field &field);
//void validate_dip_settings(ioport_field &field);
//void validate_condition(ioport_condition &condition, device_t &device);
//-------------------------------------------------
// validate_inputs - validate input configuration
//-------------------------------------------------
void validate_inputs(device_t root)
{
//throw new emu_unimplemented();
}
//-------------------------------------------------
// validate_devices - run per-device validity
// checks
//-------------------------------------------------
void validate_devices(machine_config config)
{
//throw new emu_unimplemented();
}
void validate_device_types()
{
throw new emu_unimplemented();
}
// output helpers
//-------------------------------------------------
// build_output_prefix - create a prefix
// indicating the current source file, driver,
// and device
//-------------------------------------------------
void build_output_prefix(ref string str) //void build_output_prefix(std::ostream &str) const;
{
// if we have a current (non-root) device, indicate that
if (m_current_device != null && m_current_device.owner() != null)
str += string.Format("{0} device '{1}': ", m_current_device.name(), m_current_device.tag().Substring(1));
// if we have a current port, indicate that as well
if (m_current_ioport != null)
str += string.Format("ioport '{0}': ", m_current_ioport);
}
//-------------------------------------------------
// output_via_delegate - helper to output a
// message via a varargs string, so the argptr
// can be forwarded onto the given delegate
//-------------------------------------------------
void output_via_delegate(osd_output_channel channel, string fmt, params object [] args) //template <typename Format, typename... Params> void output_via_delegate(osd_output_channel channel, Format &&fmt, Params &&...args);
{
// call through to the delegate with the proper parameters
chain_output(channel, fmt, args);
}
//-------------------------------------------------
// output_indented_errors - helper to output error
// and warning messages with header and indents
//-------------------------------------------------
void output_indented_errors(string text, string header)
{
// remove trailing newline
if (text[text.Length - 1] == '\n')
text = text.Remove(text.Length);
text = text.Replace("\n", "\n ");
output_via_delegate(osd_output_channel.OSD_OUTPUT_CHANNEL_ERROR, "{0}:\n {1}\n", header, text);
}
//-------------------------------------------------
// ioport_string_from_index - return an indexed
// string from the I/O port system
//-------------------------------------------------
string ioport_string_from_index(u32 index)
{
return ioport_configurer.string_from_token(index.ToString());
}
}
}
| 37.79322 | 258 | 0.498699 | [
"BSD-3-Clause"
] | fasteddo/mcs | mcs/src/src/emu/validity.cs | 22,298 | 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("MultipleAppServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MultipleAppServer")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("ad6bd357-f907-4974-9fbe-86a424f37a10")]
// 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")]
| 38.513514 | 84 | 0.750175 | [
"Apache-2.0"
] | ChuckFork/SuperSocket | QuickStart/MultipleAppServer/Properties/AssemblyInfo.cs | 1,428 | C# |
using System.Collections.ObjectModel;
using System.Text.Json.Serialization;
namespace NetBungieAPI.Models.Destiny.Components
{
public sealed record DictionaryComponentResponseOfint64AndDestinyItemObjectivesComponent : ComponentResponse
{
[JsonPropertyName("data")]
public ReadOnlyDictionary<long, DestinyItemObjectivesComponent> Data { get; init; } =
Defaults.EmptyReadOnlyDictionary<long, DestinyItemObjectivesComponent>();
}
} | 39.166667 | 112 | 0.776596 | [
"MIT"
] | Tailtinn/.NetBungieAPI | NetBungieAPI/Models/Destiny/Components/DictionaryComponentResponseOfint64AndDestinyItemObjectivesComponent.cs | 472 | C# |
using System;
namespace UX.Lib2.Devices.Cisco.SystemUnit
{
public class SystemUnit : CodecApiElement
{
#region Fields
[CodecApiNameAttribute("Uptime")]
#pragma warning disable 649 // assigned using reflection
private TimeSpan _uptime;
#pragma warning restore 649
[CodecApiNameAttribute("ProductId")]
#pragma warning disable 649 // assigned using reflection
private string _productId;
#pragma warning restore 649
[CodecApiNameAttribute("ProductPlatform")]
#pragma warning disable 649 // assigned using reflection
private string _productPlatform;
#pragma warning restore 649
[CodecApiNameAttribute("ProductType")]
#pragma warning disable 649 // assigned using reflection
private string _productType;
#pragma warning restore 649
[CodecApiNameAttribute("Software")]
private Software _software;
[CodecApiNameAttribute("State")]
private State _state;
[CodecApiNameAttribute("Hardware")]
private Hardware _hardware;
#endregion
#region Constructors
internal SystemUnit(CiscoTelePresenceCodec codec)
: base(codec)
{
_software = new Software(this, "Software");
_state = new State(this, "State");
_hardware = new Hardware(this, "Hardware");
}
#endregion
#region Finalizers
#endregion
#region Events
#endregion
#region Delegates
#endregion
#region Properties
public string ProductId
{
get { return _productId; }
}
public string ProductPlatform
{
get { return _productPlatform; }
}
public string ProductType
{
get { return _productType; }
}
public TimeSpan Uptime
{
get { return _uptime; }
}
public Software Software
{
get { return _software; }
}
public State State
{
get { return _state; }
}
public Hardware Hardware
{
get { return _hardware; }
}
#endregion
#region Methods
#endregion
}
} | 22.75 | 58 | 0.559172 | [
"Unlicense"
] | uxav/lib2-devices | Cisco/SystemUnit/SystemUnit.cs | 2,366 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Monitor.Version2018_09_01.Models
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The Log Search Rule resource.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class LogSearchRuleResource : Resource
{
/// <summary>
/// Initializes a new instance of the LogSearchRuleResource class.
/// </summary>
public LogSearchRuleResource()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the LogSearchRuleResource class.
/// </summary>
/// <param name="location">Resource location</param>
/// <param name="source">Data Source against which rule will Query
/// Data</param>
/// <param name="action">Action needs to be taken on rule
/// execution.</param>
/// <param name="id">Azure resource Id</param>
/// <param name="name">Azure resource name</param>
/// <param name="type">Azure resource type</param>
/// <param name="tags">Resource tags</param>
/// <param name="description">The description of the Log Search
/// rule.</param>
/// <param name="enabled">The flag which indicates whether the Log
/// Search rule is enabled. Value should be true or false. Possible
/// values include: 'true', 'false'</param>
/// <param name="lastUpdatedTime">Last time the rule was updated in
/// IS08601 format.</param>
/// <param name="provisioningState">Provisioning state of the scheduled
/// query rule. Possible values include: 'Succeeded', 'Deploying',
/// 'Canceled', 'Failed'</param>
/// <param name="schedule">Schedule (Frequency, Time Window) for rule.
/// Required for action type - AlertingAction</param>
public LogSearchRuleResource(string location, Source source, Action action, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string description = default(string), string enabled = default(string), System.DateTime? lastUpdatedTime = default(System.DateTime?), string provisioningState = default(string), Schedule schedule = default(Schedule))
: base(location, id, name, type, tags)
{
Description = description;
Enabled = enabled;
LastUpdatedTime = lastUpdatedTime;
ProvisioningState = provisioningState;
Source = source;
Schedule = schedule;
Action = action;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the description of the Log Search rule.
/// </summary>
[JsonProperty(PropertyName = "properties.description")]
public string Description { get; set; }
/// <summary>
/// Gets or sets the flag which indicates whether the Log Search rule
/// is enabled. Value should be true or false. Possible values include:
/// 'true', 'false'
/// </summary>
[JsonProperty(PropertyName = "properties.enabled")]
public string Enabled { get; set; }
/// <summary>
/// Gets last time the rule was updated in IS08601 format.
/// </summary>
[JsonProperty(PropertyName = "properties.lastUpdatedTime")]
public System.DateTime? LastUpdatedTime { get; private set; }
/// <summary>
/// Gets provisioning state of the scheduled query rule. Possible
/// values include: 'Succeeded', 'Deploying', 'Canceled', 'Failed'
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; private set; }
/// <summary>
/// Gets or sets data Source against which rule will Query Data
/// </summary>
[JsonProperty(PropertyName = "properties.source")]
public Source Source { get; set; }
/// <summary>
/// Gets or sets schedule (Frequency, Time Window) for rule. Required
/// for action type - AlertingAction
/// </summary>
[JsonProperty(PropertyName = "properties.schedule")]
public Schedule Schedule { get; set; }
/// <summary>
/// Gets or sets action needs to be taken on rule execution.
/// </summary>
[JsonProperty(PropertyName = "properties.action")]
public Action Action { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
if (Source == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Source");
}
if (Action == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Action");
}
if (Source != null)
{
Source.Validate();
}
if (Schedule != null)
{
Schedule.Validate();
}
}
}
}
| 40.833333 | 465 | 0.584163 | [
"MIT"
] | Azure/azure-powershell-common | src/Monitor/Version2018_09_01/Models/LogSearchRuleResource.cs | 6,125 | C# |
using System.Runtime.InteropServices;
namespace GhostYak.IO.DeviceIOControl.Objects.Disk
{
[StructLayout(LayoutKind.Sequential)]
public struct STORAGE_PROPERTY_QUERY
{
public STORAGE_PROPERTY_ID PropertyId;
public STORAGE_QUERY_TYPE QueryType;
public byte[] AdditionalParameters;
}
}
| 25.076923 | 50 | 0.742331 | [
"MIT"
] | ygpark/bingrep | GhostYak/IO/DeviceIOControl/Objects/Disk/STORAGE_PROPERTY_QUERY.cs | 328 | C# |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace LyncUCWA.Service.Model
{
[JsonObject]
public class EventDetails
{
[JsonProperty("_links")]
public Link _links { get; set; }
[JsonProperty("sender")]
public List<Sender> sender { get; set; }
}
public class Message : ClsHref
{
public string direction { get; set; }
public DateTime timeStamp { get; set; }
public Link _links { get; set; }
}
public class Messaging : ClsHref
{
public string state { get; set; }
public List<string> negotiatedMessageFormats { get; set; }
public Link _links { get; set; }
}
public class Participant : ClsHref
{
public string title { get; set; }
}
public class AcceptedByParticipant
{
public string rel { get; set; }
public bool anonymous { get; set; }
public string name { get; set; }
public bool organizer { get; set; }
public string otherPhoneNumber { get; set; }
public string role { get; set; }
public string sourceNetwork { get; set; }
public string uri { get; set; }
public string workPhoneNumber { get; set; }
public Link _links { get; set; }
}
public class From : ClsHref
{
public bool anonymous { get; set; }
public string name { get; set; }
public bool organizer { get; set; }
public string otherPhoneNumber { get; set; }
public string role { get; set; }
public string sourceNetwork { get; set; }
public string uri { get; set; }
public string workPhoneNumber { get; set; }
public Link _links { get; set; }
}
public class EmbeddedInMsgInv
{
public List<AcceptedByParticipant> acceptedByParticipant { get; set; }
public From from { get; set; }
}
public class MessagingInvitation : ClsHref
{
public string direction { get; set; }
public string importance { get; set; }
public string operationId { get; set; }
public string state { get; set; }
public string subject { get; set; }
public string threadId { get; set; }
public string to { get; set; }
public Link _links { get; set; }
public EmbeddedInMsgInv _embedded { get; set; }
}
public class Conversation : ClsHref
{
public List<string> activeModalities { get; set; }
public string audienceMessaging { get; set; }
public string audienceMute { get; set; }
public DateTime created { get; set; }
public DateTime expirationTime { get; set; }
public string importance { get; set; }
public int participantCount { get; set; }
public bool readLocally { get; set; }
public bool recording { get; set; }
public string state { get; set; }
public string subject { get; set; }
public string threadId { get; set; }
public Link _links { get; set; }
}
public class LocalParticipant : ClsHref
{
public bool anonymous { get; set; }
public string name { get; set; }
public bool organizer { get; set; }
public string otherPhoneNumber { get; set; }
public string role { get; set; }
public string sourceNetwork { get; set; }
public string uri { get; set; }
public string workPhoneNumber { get; set; }
public Link _links { get; set; }
}
public class Event
{
public ClsHref link { get; set; }
public Embedded _embedded { get; set; }
public string type { get; set; }
}
public class Sender : ClsHref
{
public List<Event> events { get; set; }
}
}
| 30.508065 | 78 | 0.585514 | [
"MIT"
] | rencoder/LyncUCWA | LyncUCWA.Service/Model/EventDetails.cs | 3,785 | C# |
namespace Highcharts4Net.Library.Options
{
/// <summary>
/// A gauge showing values using a filled arc with colors indicating the value. The solid gauge plots values against the <code>yAxis</code>, which is extended with some color options, <a href='#yAxis.minColor'>minColor</a>, <a href='#yAxis.maxColor'>maxColor</a> and <a href='#yAxis.stops'>stops</a>, to control the color of the gauge itself.
/// </summary>
public class PlotOptionsSolidgauge: OptionsSolidgaugeBase
{
}
} | 37.923077 | 343 | 0.728195 | [
"MIT"
] | davcs86/Highcharts4Net | Highcharts4Net/Library/Options/PlotOptionsSolidgauge.cs | 493 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Net;
using System.Collections.Generic;
using Amazon.S3.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
namespace Amazon.S3.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for PutBucketLogging operation
/// </summary>
public class PutBucketLoggingResponseUnmarshaller : S3ReponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
PutBucketLoggingResponse response = new PutBucketLoggingResponse();
return response;
}
private static PutBucketLoggingResponseUnmarshaller _instance;
public static PutBucketLoggingResponseUnmarshaller Instance
{
get
{
if (_instance == null)
{
_instance = new PutBucketLoggingResponseUnmarshaller();
}
return _instance;
}
}
}
}
| 30 | 93 | 0.643275 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/S3/Custom/Model/Internal/MarshallTransformations/PutBucketLoggingResponseUnmarshaller.cs | 1,710 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
namespace Lab09_Manhattan.Classes
{
/// <summary>
/// New York class that contains all of the nested information from JSON file and normalizing it according to the syntax that was written in JSON file
/// </summary>
public class NewYork
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("geometry")]
public Geometry Geometry { get; set; }
[JsonProperty("properties")]
public Properties Properties { get; set; }
}
}
| 25.166667 | 154 | 0.65894 | [
"MIT"
] | jinwoov/Lab09-LINQ | Lab09-Manhattan/Lab09-Manhattan/Classes/NewYork.cs | 606 | C# |
#region File Description
//===================================================================
// DefaultPointSpriteParticleSystemTemplate.cs
//
// This file provides the template for creating a new Point Sprite Particle
// System that inherits from the Default Point Sprite Particle System.
//
// The spots that should be modified are marked with TODO statements.
//
// Copyright Daniel Schroeder 2008
//===================================================================
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
#endregion
namespace DPSF.ParticleSystems
{
//-----------------------------------------------------------
// TODO: Rename/Refactor the Particle System class
//-----------------------------------------------------------
/// <summary>
/// Create a new Particle System class that inherits from a
/// Default DPSF Particle System
/// </summary>
class MyParticleSystem : DefaultPointSpriteParticleSystem
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="cGame">Handle to the Game object being used. Pass in null for this
/// parameter if not using a Game object.</param>
public MyParticleSystem(Game cGame) : base(cGame) { }
//===========================================================
// Structures and Variables
//===========================================================
// Variable to tell if the Particles should be initialized to travel in the same direction or not
private bool mbInitializeParticlesWithRandomDirection = true;
// The Min and Max Distance a Particle must be from the Magnet to be affected by the Magnet
private float mfMinDistance = 0;
private float mfMaxDistance = 100;
/// <summary>
/// Get / Set the Max Force that the Magnets should exert on the Particles
/// </summary>
public float MagnetsForce
{
get { return mfMagnetsForce; }
set
{
mfMagnetsForce = value;
// Set the Max Force of each Magnet
foreach (DefaultParticleSystemMagnet cMagnet in MagnetList)
{
cMagnet.MaxForce = mfMagnetsForce;
}
}
}
private float mfMagnetsForce = 20;
/// <summary>
/// Get / Set the Distance Function that the Magnets use
/// </summary>
public DefaultParticleSystemMagnet.DistanceFunctions MagnetsDistanceFunction
{
get { return meMagnetsDistanceFunction; }
set
{
meMagnetsDistanceFunction = value;
// Set the Distance Function of each Magnet
foreach (DefaultParticleSystemMagnet cMagnet in MagnetList)
{
cMagnet.DistanceFunction = meMagnetsDistanceFunction;
}
}
}
private DefaultParticleSystemMagnet.DistanceFunctions meMagnetsDistanceFunction = DefaultParticleSystemMagnet.DistanceFunctions.Linear;
/// <summary>
/// Get / Set the Mode that the Magnets should use
/// </summary>
public DefaultParticleSystemMagnet.MagnetModes MagnetsMode
{
get { return meMagnetsMode; }
set
{
meMagnetsMode = value;
// Set the Magnet Mode of each Magnet
foreach (DefaultParticleSystemMagnet cMagnet in MagnetList)
{
cMagnet.Mode = meMagnetsMode;
}
}
}
private DefaultParticleSystemMagnet.MagnetModes meMagnetsMode = DefaultParticleSystemMagnet.MagnetModes.Attract;
/// <summary>
/// Get whether the Magnets affect a Particle's Position or Velocity
/// </summary>
public bool MagnetsAffectPosition { get; private set; }
//===========================================================
// Overridden Particle System Functions
//===========================================================
//===========================================================
// Initialization Functions
//===========================================================
/// <summary>
/// Function to Initialize the Particle System with default values.
/// Particle system properties should not be set until after this is called, as
/// they are likely to be reset to their default values.
/// </summary>
/// <param name="cGraphicsDevice">The Graphics Device the Particle System should use</param>
/// <param name="cContentManager">The Content Manager the Particle System should use to load resources</param>
/// <param name="cSpriteBatch">The Sprite Batch that the Sprite Particle System should use to draw its particles.
/// If this is not initializing a Sprite particle system, or you want the particle system to use its own Sprite Batch,
/// pass in null.</param>
public override void AutoInitialize(GraphicsDevice cGraphicsDevice, ContentManager cContentManager, SpriteBatch cSpriteBatch)
{
// Initialize the Particle System before doing anything else
InitializePointSpriteParticleSystem(cGraphicsDevice, cContentManager, 1000, 50000,
UpdateVertexProperties, "Textures/Star9");
// Finish loading the Particle System in a separate function call, so if
// we want to reset the Particle System later we don't need to completely
// re-initialize it, we can just call this function to reset it.
LoadParticleSystem();
}
/// <summary>
/// Load the Particle System Events and any other settings
/// </summary>
public void LoadParticleSystem()
{
// Set the Particle Initialization Function, as it can be changed on the fly
// and we want to make sure we are using the right one to start with to start with.
ParticleInitializationFunction = InitializeParticleProperties;
// Remove all Events first so that none are added twice if this function is called again
ParticleEvents.RemoveAllEvents();
ParticleSystemEvents.RemoveAllEvents();
// Setup the Emitter
Emitter.ParticlesPerSecond = 100;
Emitter.PositionData.Position = new Vector3(-100, 50, 0);
// Allow the Particle's Velocity, Rotational Velocity, Color, and Transparency to be updated each frame
ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionUsingVelocity);
ParticleEvents.AddEveryTimeEvent(UpdateParticleRotationUsingRotationalVelocity);
ParticleEvents.AddEveryTimeEvent(UpdateParticleColorUsingLerp);
// This function must be executed after the Color Lerp function as the Color Lerp will overwrite the Color's
// Transparency value, so we give this function an Execution Order of 100 to make sure it is executed last.
ParticleEvents.AddEveryTimeEvent(UpdateParticleTransparencyToFadeOutUsingLerp, 100);
//=================================================================
// Tutorial 7 Specific Code
//=================================================================
// Call function to add Magnet Particle Event
ToogleMagnetsAffectPositionOrVelocity();
// Specify to use the Point Magnet by defualt
UseMagnetType(DefaultParticleSystemMagnet.MagnetTypes.PointMagnet);
}
/// <summary>
/// Example of how to create a Particle Initialization Function
/// </summary>
/// <param name="cParticle">The Particle to be Initialized</param>
public void InitializeParticleProperties(DefaultPointSpriteParticle cParticle)
{
// Set the Particle's Lifetime (how long it should exist for) and initial Position
cParticle.Lifetime = 5;
cParticle.Position = Emitter.PositionData.Position;
// If the Particles should travel in random directions
if (mbInitializeParticlesWithRandomDirection)
{
// Give the Particle a random velocity direction to start with
cParticle.Velocity = DPSFHelper.RandomNormalizedVector() * 50;
}
else
{
// Emit all of the Particles in the same direction
cParticle.Velocity = Vector3.Right * 50;
// Adjust the Particle's starting velocity direction according to the Emitter's Orientation
cParticle.Velocity = Vector3.Transform(cParticle.Velocity, Emitter.OrientationData.Orientation);
}
cParticle.RotationalVelocity = RandomNumber.Between(-MathHelper.Pi, MathHelper.Pi);
cParticle.Size = 10;
cParticle.StartColor = cParticle.EndColor = cParticle.Color = DPSFHelper.RandomColor();
}
//===========================================================
// Particle Update Functions
//===========================================================
/// <summary>
/// Example of how to create a Particle Event Function
/// </summary>
/// <param name="cParticle">The Particle to update</param>
/// <param name="fElapsedTimeInSeconds">How long it has been since the last update</param>
public void UpdateParticleFunctionExample(DefaultPointSpriteParticle cParticle, float fElapsedTimeInSeconds)
{
// Place code to update the Particle here
// Example: cParticle.Position += cParticle.Velocity * fElapsedTimeInSeconds;
}
//===========================================================
// Particle System Update Functions
//===========================================================
/// <summary>
/// Example of how to create a Particle System Event Function
/// </summary>
/// <param name="fElapsedTimeInSeconds">How long it has been since the last update</param>
public void UpdateParticleSystemFunctionExample(float fElapsedTimeInSeconds)
{
// Place code to update the Particle System here
// Example: Emitter.EmitParticles = true;
// Example: SetTexture("TextureAssetName");
}
//===========================================================
// Other Particle System Functions
//===========================================================
/// <summary>
/// Toggles the variable indicating whether the Particles should be initialized
/// with a random direction or not
/// </summary>
public void ToggleInitialRandomDirection()
{
mbInitializeParticlesWithRandomDirection = !mbInitializeParticlesWithRandomDirection;
}
/// <summary>
/// Toggles if Magnets should affect the Particles' Position or Velocity, and adds
/// the appropriate Particle Event to do so
/// </summary>
public void ToogleMagnetsAffectPositionOrVelocity()
{
// Toggle if Magnets should affect the Particles' Position or Velocity
MagnetsAffectPosition = !MagnetsAffectPosition;
// Remove the previous Magnet Particle Events
ParticleEvents.RemoveAllEventsInGroup(1);
// If the Magnets should affect the Particles' Velocity
if (MagnetsAffectPosition)
{
// Specify that Magnets should affect the Particles' Position
ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionAccordingToMagnets, 0, 1);
}
// Else they should affect the Particles' Position
else
{
// Specify that Magnets should affect the Particles' Velocity
ParticleEvents.AddEveryTimeEvent(UpdateParticleVelocityAccordingToMagnets, 0, 1);
}
}
/// <summary>
/// Specify which Type of Magnet we should use to affect the Particles
/// </summary>
/// <param name="iMagnetTypeToEnabled">The Type of Magnet to use (1 - 4)</param>
public void UseMagnetType(DefaultParticleSystemMagnet.MagnetTypes eMagnetTypeToUse)
{
//=================================================================
// Tutorial 7 Specific Code
//=================================================================
// Clear all of the Magnets so they can be re-added
MagnetList.Clear();
// Use the specified Type of Magnet
switch (eMagnetTypeToUse)
{
default:
case DefaultParticleSystemMagnet.MagnetTypes.PointMagnet:
MagnetList.AddFirst(new MagnetPoint(new Vector3(0, 50, 0),
MagnetsMode, MagnetsDistanceFunction,
mfMinDistance, mfMaxDistance, MagnetsForce, 0));
break;
case DefaultParticleSystemMagnet.MagnetTypes.LineMagnet:
MagnetList.AddFirst(new MagnetLine(new Vector3(0, 50, 0), Vector3.Up,
MagnetsMode, MagnetsDistanceFunction,
mfMinDistance, mfMaxDistance, MagnetsForce, 0));
break;
case DefaultParticleSystemMagnet.MagnetTypes.LineSegmentMagnet:
MagnetList.AddFirst(new MagnetLineSegment(new Vector3(0, 25, 0), new Vector3(0, 75, 0),
MagnetsMode, MagnetsDistanceFunction,
mfMinDistance, mfMaxDistance, MagnetsForce, 0));
break;
case DefaultParticleSystemMagnet.MagnetTypes.PlaneMagnet:
MagnetList.AddFirst(new MagnetPlane(new Vector3(0, 50, 0), Vector3.Right,
MagnetsMode, MagnetsDistanceFunction,
mfMinDistance, mfMaxDistance, MagnetsForce, 0));
break;
}
}
}
}
| 42.962617 | 143 | 0.59169 | [
"MIT"
] | deadlydog/DPSF-XNA | XNA 3.1/Installer/Installer Files/Tutorials/Tutorial 7/Tutorial/Particle Systems/MyParticleSystem.cs | 13,793 | C# |
using Microsoft.AspNetCore.Mvc.Razor.Internal;
using Abp.AspNetCore.Mvc.Views;
using Abp.Runtime.Session;
namespace JD.CRS.Web.Views
{
public abstract class CRSRazorPage<TModel> : AbpRazorPage<TModel>
{
[RazorInject]
public IAbpSession AbpSession { get; set; }
protected CRSRazorPage()
{
LocalizationSourceName = CRSConsts.LocalizationSourceName;
}
}
}
| 23.333333 | 70 | 0.67381 | [
"MIT"
] | IT-Evan/JD.CRS | src/JD.CRS.Web.Mvc/Views/CRSRazorPage.cs | 422 | C# |
using System;
namespace Ahbc.Class.Eleven
{
public class Buick : Vehicle
{
public Buick(string plate) : base(plate)
{
Console.WriteLine("Buick created");
SpeedMph = 40;
}
public void EngageHandicapHanger()
{
}
}
public class SomeImposterBuick : Buick
{
public SomeImposterBuick(string plate) : base(plate)
{
}
public override void Drive()
{
base.Drive();
}
}
}
| 14.354839 | 56 | 0.595506 | [
"Apache-2.0"
] | JamilAbbas787/ahbc_dotnet_201810 | Ahbc.Class.Eleven/Ahbc.Class.Eleven/Buick.cs | 447 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("_struct", typeof(IronPython.Modules.PythonStruct))]
namespace IronPython.Modules {
public static class PythonStruct {
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException("structerror", dict, "error", "struct");
}
#region Public API
public const string __doc__ = null;
[PythonType, Documentation("Represents a compiled struct pattern")]
public class Struct : IWeakReferenceable {
private Format[] _formats; // the various formatting options for the compiled struct
private bool _isStandardized; // true if the format is in standardized mode
private bool _isLittleEndian; // true if the format is in little endian mode
private int _encodingCount = -1; // the number of objects consumed/produced by the format
private int _encodingSize = -1; // the number of bytes read/produced by the format
private WeakRefTracker _tracker; // storage for weak proxy's
private void InitializeFrom(Struct s) {
format = s.format;
_formats = s._formats;
_isStandardized = s._isStandardized;
_isLittleEndian = s._isLittleEndian;
_encodingCount = s._encodingCount;
_encodingSize = s._encodingSize;
_tracker = s._tracker;
}
internal Struct(CodeContext/*!*/ context, [NotNull]string/*!*/ fmt) {
__init__(context, fmt);
}
#region Python construction
[Documentation("creates a new uninitialized struct object - all arguments are ignored")]
public Struct(params object[] args) {
}
[Documentation("creates a new uninitialized struct object - all arguments are ignored")]
public Struct([ParamDictionary]IDictionary<object, object> kwArgs, params object[] args) {
}
[Documentation("initializes or re-initializes the compiled struct object with a new format")]
public void __init__(CodeContext/*!*/ context, object fmt) {
format = FormatObjectToString(fmt);
Struct s;
bool gotIt;
lock (_cache) {
gotIt = _cache.TryGetValue(format, out s);
}
InitializeFrom(gotIt ? s : CompileAndCache(context, format));
}
#endregion
#region Public API
[Documentation("gets the current format string for the compiled Struct")]
public string format { get; private set; }
[Documentation("returns a string consisting of the values serialized according to the format of the struct object")]
public Bytes/*!*/ pack(CodeContext/*!*/ context, params object[] values) {
if (values.Length != _encodingCount) {
throw Error(context, $"pack requires exactly {_encodingCount} arguments");
}
int curObj = 0;
var buffer = new byte[_encodingSize];
using var res = new MemoryStream(buffer);
foreach (Format curFormat in _formats) {
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
int nativeSize = curFormat.NativeSize;
int alignLength = Align((int)res.Position, nativeSize);
int padLength = alignLength - (int)res.Position;
res.WriteByteCount((byte)'\0', padLength);
}
switch (curFormat.Type) {
case FormatType.PadByte:
res.WriteByteCount((byte)'\0', curFormat.Count);
break;
case FormatType.Bool:
res.WriteByte((byte)(GetBoolValue(context, curObj++, values) ? 1 : 0));
break;
case FormatType.Char:
for (int j = 0; j < curFormat.Count; j++) {
res.WriteByte((byte)GetCharValue(context, curObj++, values));
}
break;
case FormatType.SignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.WriteByte((byte)GetSByteValue(context, curObj++, values));
}
break;
case FormatType.UnsignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.WriteByte(GetByteValue(context, curObj++, values));
}
break;
case FormatType.Short:
for (int j = 0; j < curFormat.Count; j++) {
WriteShort(res, _isLittleEndian, GetShortValue(context, curObj++, values));
}
break;
case FormatType.UnsignedShort:
for (int j = 0; j < curFormat.Count; j++) {
WriteUShort(res, _isLittleEndian, GetUShortValue(context, curObj++, values));
}
break;
case FormatType.Int:
for (int j = 0; j < curFormat.Count; j++) {
WriteInt(res, _isLittleEndian, GetIntValue(context, curObj++, values));
}
break;
case FormatType.UnsignedInt:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetULongValue(context, curObj++, values, "unsigned int"));
}
break;
case FormatType.UnsignedLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetULongValue(context, curObj++, values, "unsigned long"));
}
break;
case FormatType.Pointer:
for (int j = 0; j < curFormat.Count; j++) {
WritePointer(res, _isLittleEndian, GetPointer(context, curObj++, values));
}
break;
case FormatType.SignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
WriteSignedNetPointer(res, _isLittleEndian, GetSignedNetPointer(context, curObj++, values));
}
break;
case FormatType.UnsignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
WriteUnsignedNetPointer(res, _isLittleEndian, GetUnsignedNetPointer(context, curObj++, values));
}
break;
case FormatType.SignedSizeT:
for (int j = 0; j < curFormat.Count; j++) {
WriteInt(res, _isLittleEndian, GetSignedSizeT(context, curObj++, values));
}
break;
case FormatType.SizeT:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetSizeT(context, curObj++, values));
}
break;
case FormatType.LongLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteLong(res, _isLittleEndian, GetLongValue(context, curObj++, values));
}
break;
case FormatType.UnsignedLongLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteULong(res, _isLittleEndian, GetULongLongValue(context, curObj++, values));
}
break;
case FormatType.Double:
for (int j = 0; j < curFormat.Count; j++) {
WriteDouble(res, _isLittleEndian, GetDoubleValue(context, curObj++, values));
}
break;
case FormatType.Float:
for (int j = 0; j < curFormat.Count; j++) {
WriteFloat(res, _isLittleEndian, (float)GetDoubleValue(context, curObj++, values));
}
break;
case FormatType.CString:
WriteString(res, curFormat.Count, GetStringValue(context, curObj++, values));
break;
case FormatType.PascalString:
WritePascalString(res, curFormat.Count - 1, GetStringValue(context, curObj++, values));
break;
}
}
return Bytes.Make(buffer);
}
[Documentation("Stores the deserialized data into the provided array")]
public void pack_into(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset, params object[] args) {
byte[] existing = buffer.ToByteArray();
if (offset + size > existing.Length) {
throw Error(context, $"pack_into requires a buffer of at least {size} bytes");
}
var data = pack(context, args).UnsafeByteArray;
for (int i = 0; i < data.Length; i++) {
existing[i + offset] = data[i];
}
buffer.Clear();
buffer.FromStream(new MemoryStream(existing));
}
public void pack_into(CodeContext/*!*/ context, [NotNull]ByteArray/*!*/ buffer, int offset, params object[] args) {
IList<byte> existing = buffer.UnsafeByteList;
if (offset + size > existing.Count) {
throw Error(context, $"pack_into requires a buffer of at least {size} bytes");
}
var data = pack(context, args).UnsafeByteArray;
for (int i = 0; i < data.Length; i++) {
existing[i + offset] = data[i];
}
}
[Documentation("deserializes the string using the structs specified format")]
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [BytesLike][NotNull]IList<byte> @string) {
if (@string.Count != size) {
throw Error(context, $"unpack requires a bytes object of length {size}");
}
var data = @string;
int curIndex = 0;
var res = new object[_encodingCount];
var res_idx = 0;
foreach (Format curFormat in _formats) {
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
int nativeSize = curFormat.NativeSize;
if (nativeSize > 0) {
curIndex = Align(curIndex, nativeSize);
}
}
switch (curFormat.Type) {
case FormatType.PadByte:
curIndex += curFormat.Count;
break;
case FormatType.Bool:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateBoolValue(context, ref curIndex, data);
}
break;
case FormatType.Char:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = Bytes.FromByte(CreateCharValue(context, ref curIndex, data));
}
break;
case FormatType.SignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)(sbyte)CreateCharValue(context, ref curIndex, data);
}
break;
case FormatType.UnsignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)CreateCharValue(context, ref curIndex, data);
}
break;
case FormatType.Short:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)CreateShortValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.UnsignedShort:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)CreateUShortValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.Int:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateIntValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.UnsignedInt:
case FormatType.UnsignedLong:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = BigIntegerOps.__int__(CreateUIntValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.Pointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res[res_idx++] = CreateIntValue(context, ref curIndex, _isLittleEndian, data);
} else {
res[res_idx++] = BigIntegerOps.__int__(CreateLongValue(context, ref curIndex, _isLittleEndian, data));
}
}
break;
case FormatType.SignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res[res_idx++] = new IntPtr(CreateIntValue(context, ref curIndex, _isLittleEndian, data));
} else {
res[res_idx++] = new IntPtr(CreateLongValue(context, ref curIndex, _isLittleEndian, data));
}
}
break;
case FormatType.UnsignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res[res_idx++] = new UIntPtr(CreateUIntValue(context, ref curIndex, _isLittleEndian, data));
} else {
res[res_idx++] = new UIntPtr(CreateULongValue(context, ref curIndex, _isLittleEndian, data));
}
}
break;
case FormatType.SignedSizeT:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateIntValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.SizeT:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateUIntValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.LongLong:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = BigIntegerOps.__int__(CreateLongValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.UnsignedLongLong:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = BigIntegerOps.__int__(CreateULongValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.Float:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateFloatValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.Double:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateDoubleValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.CString:
res[res_idx++] = CreateString(context, ref curIndex, curFormat.Count, data);
break;
case FormatType.PascalString:
res[res_idx++] = CreatePascalString(context, ref curIndex, curFormat.Count - 1, data);
break;
}
}
System.Diagnostics.Debug.Assert(res_idx == res.Length);
return PythonTuple.MakeTuple(res);
}
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer)
=> unpack(context, buffer.ToByteArray());
[Documentation("reads the current format from the specified array")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
int bytesAvail = buffer.Count - offset;
if (bytesAvail < size) {
throw Error(context, $"unpack_from requires a buffer of at least {size} bytes");
}
return unpack(context, buffer.Substring(offset, size));
}
[Documentation("reads the current format from the specified array")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return unpack_from(context, buffer.ToByteArray(), offset);
}
[Documentation("iteratively unpack the current format from the specified array.")]
public PythonUnpackIterator iter_unpack(CodeContext/*!*/ context, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
return new PythonUnpackIterator(this, context, buffer, offset);
}
[Documentation("iteratively unpack the current format from the specified array.")]
public PythonUnpackIterator iter_unpack(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return new PythonUnpackIterator(this, context, buffer, offset);
}
[Documentation("gets the number of bytes that the serialized string will occupy or are required to deserialize the data")]
public int size {
get {
return _encodingSize;
}
}
#endregion
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _tracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
return Interlocked.CompareExchange(ref _tracker, value, null) == null;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_tracker = value;
}
#endregion
#region Implementation Details
private static Struct CompileAndCache(CodeContext/*!*/ context, string/*!*/ fmt) {
List<Format> res = new List<Format>();
int count = 1;
bool fLittleEndian = BitConverter.IsLittleEndian;
bool fStandardized = false;
for (int i = 0; i < fmt.Length; i++) {
switch (fmt[i]) {
case 'x': // pad byte
res.Add(new Format(FormatType.PadByte, count));
count = 1;
break;
case '?': // bool
res.Add(new Format(FormatType.Bool, count));
count = 1;
break;
case 'c': // char
res.Add(new Format(FormatType.Char, count));
count = 1;
break;
case 'b': // signed char
res.Add(new Format(FormatType.SignedChar, count));
count = 1;
break;
case 'B': // unsigned char
res.Add(new Format(FormatType.UnsignedChar, count));
count = 1;
break;
case 'h': // short
res.Add(new Format(FormatType.Short, count));
count = 1;
break;
case 'H': // unsigned short
res.Add(new Format(FormatType.UnsignedShort, count));
count = 1;
break;
case 'i': // int
case 'l': // long
res.Add(new Format(FormatType.Int, count));
count = 1;
break;
case 'I': // unsigned int
res.Add(new Format(FormatType.UnsignedInt, count));
count = 1;
break;
case 'L': // unsigned long
res.Add(new Format(FormatType.UnsignedLong, count));
count = 1;
break;
case 'q': // long long
res.Add(new Format(FormatType.LongLong, count));
count = 1;
break;
case 'Q': // unsigned long long
res.Add(new Format(FormatType.UnsignedLongLong, count));
count = 1;
break;
case 'f': // float
res.Add(new Format(FormatType.Float, count));
count = 1;
break;
case 'd': // double
res.Add(new Format(FormatType.Double, count));
count = 1;
break;
case 's': // char[]
res.Add(new Format(FormatType.CString, count));
count = 1;
break;
case 'p': // pascal char[]
res.Add(new Format(FormatType.PascalString, count));
count = 1;
break;
case 'P': // void *
res.Add(new Format(FormatType.Pointer, count));
count = 1;
break;
case 'r': // IntPtr
if (fStandardized) {
// r and R don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.SignedNetPointer, count));
count = 1;
break;
case 'R': // UIntPtr
if (fStandardized) {
// r and R don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.UnsignedNetPointer, count));
count = 1;
break;
case 'n': // ssize_t
if (fStandardized) {
// n and N don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.SignedSizeT, count));
count = 1;
break;
case 'N': // size_t
if (fStandardized) {
// n and N don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.SizeT, count));
count = 1;
break;
case ' ': // white space, ignore
case '\t':
break;
case '=': // native
if (i != 0) throw Error(context, "unexpected byte order");
fStandardized = true;
break;
case '@': // native
if (i != 0) throw Error(context, "unexpected byte order");
break;
case '<': // little endian
if (i != 0) throw Error(context, "unexpected byte order");
fLittleEndian = true;
fStandardized = true;
break;
case '>': // big endian
case '!': // big endian
if (i != 0) throw Error(context, "unexpected byte order");
fLittleEndian = false;
fStandardized = true;
break;
default:
if (char.IsDigit(fmt[i])) {
count = 0;
while (char.IsDigit(fmt[i])) {
count = count * 10 + (fmt[i] - '0');
i++;
}
if (char.IsWhiteSpace(fmt[i])) Error(context, "white space not allowed between count and format");
i--;
break;
}
throw Error(context, "bad char in struct format");
}
}
// store the new formats
var s = new Struct() {
format = fmt,
_formats = res.ToArray(),
_isStandardized = fStandardized,
_isLittleEndian = fLittleEndian,
};
s.InitCountAndSize();
lock (_cache) {
_cache.Add(fmt, s);
}
return s;
}
private void InitCountAndSize() {
var encodingCount = 0;
var encodingSize = 0;
foreach (Format format in _formats) {
if (format.Type != FormatType.PadByte) {
if (format.Type != FormatType.CString && format.Type != FormatType.PascalString) {
encodingCount += format.Count;
} else {
encodingCount++;
}
}
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
encodingSize = Align(encodingSize, format.NativeSize);
}
encodingSize += GetNativeSize(format.Type) * format.Count;
}
_encodingCount = encodingCount;
_encodingSize = encodingSize;
}
#endregion
#region Internal helpers
internal static Struct Create(string/*!*/ format) {
Struct res = new Struct();
res.__init__(DefaultContext.Default, format); // default context is only used for errors, this better be an error free format.
return res;
}
#endregion
}
[PythonType("unpack_iterator"), Documentation("Represents an iterator returned by _struct.iter_unpack()")]
public class PythonUnpackIterator : System.Collections.IEnumerator, System.Collections.IEnumerable {
private object _iter_current;
private int _next_offset;
private readonly CodeContext _context;
private readonly IList<byte> _buffer;
private readonly int _start_offset;
private readonly Struct _owner;
private PythonUnpackIterator() { }
internal PythonUnpackIterator(Struct/*!*/ owner, CodeContext/*!*/ context, IList<byte>/*!*/ buffer, int offset) {
_context = context;
_buffer = buffer;
_start_offset = offset;
_owner = owner;
Reset();
ValidateBufferLength();
}
internal PythonUnpackIterator(Struct/*!*/ owner, CodeContext/*!*/ context, ArrayModule.array/*!*/ buffer, int offset) {
_context = context;
_buffer = buffer.ToByteArray();
_start_offset = offset;
_owner = owner;
Reset();
ValidateBufferLength();
}
private void ValidateBufferLength() {
if (_buffer.Count - _start_offset < _owner.size) {
throw Error(_context, $"iterative unpacking requires a buffer of a multiple of {_owner.size} bytes");
}
}
#region IEnumerable
[PythonHidden]
public System.Collections.IEnumerator GetEnumerator() {
return this;
}
#endregion
#region IEnumerator
[PythonHidden]
public object Current => _iter_current;
[PythonHidden]
public bool MoveNext() {
if (_buffer.Count - _next_offset < _owner.size) {
return false;
}
_iter_current = _owner.unpack_from(_context, _buffer, _next_offset);
_next_offset += _owner.size;
return true;
}
[PythonHidden]
public void Reset() {
_iter_current = null;
_next_offset = _start_offset;
}
#endregion
public object __iter__() {
return this;
}
public object __next__() {
if (!MoveNext()) {
throw PythonOps.StopIteration();
}
return Current;
}
public int __length_hint__() {
return (_buffer.Count - _next_offset) / _owner.size;
}
}
#endregion
#region Compiled Format
/// <summary>
/// Enum which specifies the format type for a compiled struct
/// </summary>
private enum FormatType {
PadByte,
Bool,
Char,
SignedChar,
UnsignedChar,
Short,
UnsignedShort,
Int,
UnsignedInt,
UnsignedLong,
Float,
LongLong,
UnsignedLongLong,
Double,
CString,
PascalString,
Pointer,
SignedNetPointer,
UnsignedNetPointer,
SignedSizeT,
SizeT,
}
private static int GetNativeSize(FormatType c) {
switch (c) {
case FormatType.Char:
case FormatType.SignedChar:
case FormatType.UnsignedChar:
case FormatType.PadByte:
case FormatType.Bool:
case FormatType.CString:
case FormatType.PascalString:
return 1;
case FormatType.Short:
case FormatType.UnsignedShort:
return 2;
case FormatType.Int:
case FormatType.UnsignedInt:
case FormatType.UnsignedLong:
case FormatType.Float:
case FormatType.SignedSizeT:
case FormatType.SizeT:
return 4;
case FormatType.LongLong:
case FormatType.UnsignedLongLong:
case FormatType.Double:
return 8;
case FormatType.Pointer:
case FormatType.SignedNetPointer:
case FormatType.UnsignedNetPointer:
return UIntPtr.Size;
default:
throw new InvalidOperationException(c.ToString());
}
}
/// <summary>
/// Struct used to store the format and the number of times it should be repeated.
/// </summary>
private readonly struct Format {
public readonly FormatType Type;
public readonly int Count;
public Format(FormatType type, int count) {
Type = type;
Count = count;
}
public int NativeSize => GetNativeSize(Type);
}
#endregion
#region Cache of compiled struct patterns
private const int MAX_CACHE_SIZE = 1024;
private static CacheDict<string, Struct> _cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);
private static string FormatObjectToString(object fmt) {
if (Converter.TryConvertToString(fmt, out string res)) {
return res;
}
if (fmt is IList<byte> b) {
return PythonOps.MakeString(b);
}
throw PythonOps.TypeError("Struct() argument 1 must be a str or bytes object, not {0}", DynamicHelpers.GetPythonType(fmt).Name);
}
private static Struct GetStructFromCache(CodeContext/*!*/ context, object fmt) {
var formatString = FormatObjectToString(fmt);
Struct s;
bool gotIt;
lock (_cache) {
gotIt = _cache.TryGetValue(formatString, out s);
}
if (!gotIt) {
s = new Struct(context, formatString);
}
return s;
}
[Documentation("Clear the internal cache.")]
public static void _clearcache() {
_cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);
}
[Documentation("int(x[, base]) -> integer\n\nConvert a string or number to an integer, if possible. A floating point\nargument will be truncated towards zero (this does not include a string\nrepresentation of a floating point number!) When converting a string, use\nthe optional base. It is an error to supply a base when converting a\nnon-string. If base is zero, the proper base is guessed based on the\nstring content. If the argument is outside the integer range a\nlong object will be returned instead.")]
public static int calcsize(CodeContext/*!*/ context, object fmt) {
return GetStructFromCache(context, fmt).size;
}
[Documentation("Return string containing values v1, v2, ... packed according to fmt.")]
public static Bytes/*!*/ pack(CodeContext/*!*/ context, object fmt/*!*/, params object[] values) {
return GetStructFromCache(context, fmt).pack(context, values);
}
[Documentation("Pack the values v1, v2, ... according to fmt.\nWrite the packed bytes into the writable buffer buf starting at offset.")]
public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset, params object[] args) {
GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args);
}
public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNull]ByteArray/*!*/ buffer, int offset, params object[] args) {
GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, object fmt, [BytesLike][NotNull]IList<byte>/*!*/ buffer) {
return GetStructFromCache(context, fmt).unpack(context, buffer);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer) {
return GetStructFromCache(context, fmt).unpack(context, buffer);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, object fmt, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
[Documentation("Iteratively unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonUnpackIterator/*!*/ iter_unpack(CodeContext/*!*/ context, object fmt, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).iter_unpack(context, buffer, offset);
}
[Documentation("Iteratively unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonUnpackIterator/*!*/ iter_unpack(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).iter_unpack(context, buffer, offset);
}
#endregion
#region Write Helpers
private static void WriteByteCount(this MemoryStream stream, byte value, int repeatCount) {
while (repeatCount > 0) {
stream.WriteByte(value);
--repeatCount;
}
}
private static void WriteShort(this MemoryStream res, bool fLittleEndian, short val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
} else {
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteUShort(this MemoryStream res, bool fLittleEndian, ushort val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
} else {
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteInt(this MemoryStream res, bool fLittleEndian, int val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
} else {
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteUInt(this MemoryStream res, bool fLittleEndian, uint val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
} else {
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WritePointer(this MemoryStream res, bool fLittleEndian, ulong val) {
if (UIntPtr.Size == 4) {
res.WriteUInt(fLittleEndian, (uint)val);
} else {
res.WriteULong(fLittleEndian, val);
}
}
private static void WriteUnsignedNetPointer(this MemoryStream res, bool fLittleEndian, UIntPtr val) {
res.WritePointer(fLittleEndian, val.ToUInt64());
}
private static void WriteSignedNetPointer(this MemoryStream res, bool fLittleEndian, IntPtr val) {
res.WritePointer(fLittleEndian, unchecked((ulong)val.ToInt64()));
}
private static void WriteFloat(this MemoryStream res, bool fLittleEndian, float val) {
byte[] bytes = BitConverter.GetBytes(val);
if (BitConverter.IsLittleEndian == fLittleEndian) {
res.Write(bytes, 0, bytes.Length);
} else {
res.WriteByte(bytes[3]);
res.WriteByte(bytes[2]);
res.WriteByte(bytes[1]);
res.WriteByte(bytes[0]);
}
}
private static void WriteLong(this MemoryStream res, bool fLittleEndian, long val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 56) & 0xff));
} else {
res.WriteByte((byte)((val >> 56) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteULong(this MemoryStream res, bool fLittleEndian, ulong val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 56) & 0xff));
} else {
res.WriteByte((byte)((val >> 56) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteDouble(this MemoryStream res, bool fLittleEndian, double val) {
byte[] bytes = BitConverter.GetBytes(val);
if (BitConverter.IsLittleEndian == fLittleEndian) {
res.Write(bytes, 0, bytes.Length);
} else {
res.WriteByte(bytes[7]);
res.WriteByte(bytes[6]);
res.WriteByte(bytes[5]);
res.WriteByte(bytes[4]);
res.WriteByte(bytes[3]);
res.WriteByte(bytes[2]);
res.WriteByte(bytes[1]);
res.WriteByte(bytes[0]);
}
}
private static void WriteString(this MemoryStream res, int len, IList<byte> val) {
for (int i = 0; i < val.Count && i < len; i++) {
res.WriteByte(val[i]);
}
for (int i = val.Count; i < len; i++) {
res.WriteByte(0);
}
}
private static void WritePascalString(this MemoryStream res, int len, IList<byte> val) {
byte lenByte = (byte)Math.Min(255, Math.Min(val.Count, len));
res.WriteByte(lenByte);
for (int i = 0; i < val.Count && i < len; i++) {
res.WriteByte(val[i]);
}
for (int i = val.Count; i < len; i++) {
res.WriteByte(0);
}
}
#endregion
#region Data getter helpers
internal static bool GetBoolValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvert(val, typeof(bool), out object res)) {
return (bool)res;
}
// Should never happen
throw Error(context, "expected bool value got " + val.ToString());
}
internal static char GetCharValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (val is string strVal && strVal.Length == 1) return strVal[0];
if (val is IList<byte> byteVal && byteVal.Count == 1) return (char)byteVal[0];
throw Error(context, "char format requires string of length 1");
}
internal static sbyte GetSByteValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToSByte(val, out sbyte res)) {
return res;
}
throw Error(context, "expected sbyte value got " + val.ToString());
}
internal static byte GetByteValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToByte(val, out byte res)) return res;
if (Converter.TryConvertToChar(val, out char cres)) return (byte)cres;
throw Error(context, "expected byte value got " + val.ToString());
}
internal static short GetShortValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToInt16(val, out short res)) return res;
throw Error(context, "expected short value");
}
internal static ushort GetUShortValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToUInt16(val, out ushort res)) return res;
throw Error(context, "expected ushort value");
}
internal static int GetIntValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToInt32(val, out int res)) return res;
throw Error(context, "expected int value");
}
internal static uint GetULongValue(CodeContext/*!*/ context, int index, object[] args, string type) {
object val = GetValue(context, index, args);
if (val is int) {
CheckRange(context, (int)val, type);
return (uint)(int)val;
} else if (val is BigInteger) {
CheckRange(context, (BigInteger)val, type);
return (uint)(BigInteger)val;
} else if (val is Extensible<int>) {
CheckRange(context, ((Extensible<int>)val).Value, type);
return (uint)((Extensible<int>)val).Value;
} else if (val is Extensible<BigInteger>) {
CheckRange(context, ((Extensible<BigInteger>)val).Value, type);
return (uint)((Extensible<BigInteger>)val).Value;
} else {
if (PythonTypeOps.TryInvokeUnaryOperator(DefaultContext.Default, val, "__int__", out object objres)) {
if (objres is int) {
CheckRange(context, (int)objres, type);
return (uint)(int)objres;
}
}
if (Converter.TryConvertToUInt32(val, out uint res)) {
return res;
}
}
throw Error(context, "cannot convert argument to integer");
}
private static void CheckRange(CodeContext context, int val, string type) {
if (val < 0) {
OutOfRange(context, type);
}
}
private static void CheckRange(CodeContext context, BigInteger bi, string type) {
if (bi < 0 || bi > 4294967295) {
OutOfRange(context, type);
}
}
private static void OutOfRange(CodeContext context, string type) {
throw Error(context, $"integer out of range for '{(type == "unsigned long" ? "L" : "I")}' format code");
}
internal static int GetSignedSizeT(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToInt32(val, out int res)) return res;
throw Error(context, "expected signed size_t(aka ssize_t) value");
}
internal static uint GetSizeT(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToUInt32(val, out uint res)) return res;
throw Error(context, "expected size_t value");
}
internal static ulong GetPointer(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToBigInteger(val, out BigInteger bi)) {
if (UIntPtr.Size == 4) {
if (bi < 0) {
bi += new BigInteger(UInt32.MaxValue) + 1;
}
if (Converter.TryConvertToUInt32(bi, out uint res)) {
return res;
}
} else {
if (bi < 0) {
bi += new BigInteger(UInt64.MaxValue) + 1;
}
if (Converter.TryConvertToUInt64(bi, out ulong res)) {
return res;
}
}
}
throw Error(context, "expected pointer value");
}
internal static IntPtr GetSignedNetPointer(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (val is IntPtr iptr) {
return iptr;
} else if (val is UIntPtr uptr) {
return new IntPtr(unchecked((long)uptr.ToUInt64()));
}
throw Error(context, "expected .NET pointer value");
}
internal static UIntPtr GetUnsignedNetPointer(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (val is UIntPtr uptr) {
return uptr;
} else if (val is IntPtr iptr) {
return new UIntPtr(unchecked((ulong)iptr.ToInt64()));
}
throw Error(context, "expected .NET pointer value");
}
internal static long GetLongValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToInt64(val, out long res)) return res;
throw Error(context, "expected long value");
}
internal static ulong GetULongLongValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToUInt64(val, out ulong res)) return res;
throw Error(context, "expected ulong value");
}
internal static double GetDoubleValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (Converter.TryConvertToDouble(val, out double res)) return res;
throw Error(context, "expected double value");
}
internal static IList<byte> GetStringValue(CodeContext/*!*/ context, int index, object[] args) {
object val = GetValue(context, index, args);
if (val is IList<byte> res) return res;
throw Error(context, "expected bytes value");
}
internal static object GetValue(CodeContext/*!*/ context, int index, object[] args) {
if (index >= args.Length) throw Error(context, "not enough arguments");
return args[index];
}
#endregion
#region Data creater helpers
internal static bool CreateBoolValue(CodeContext/*!*/ context, ref int index, IList<byte> data) {
return (int)ReadData(context, ref index, data) != 0;
}
internal static byte CreateCharValue(CodeContext/*!*/ context, ref int index, IList<byte> data) {
return ReadData(context, ref index, data);
}
internal static short CreateShortValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
if (fLittleEndian) {
return (short)((b2 << 8) | b1);
} else {
return (short)((b1 << 8) | b2);
}
}
internal static ushort CreateUShortValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
if (fLittleEndian) {
return (ushort)((b2 << 8) | b1);
} else {
return (ushort)((b1 << 8) | b2);
}
}
internal static float CreateFloatValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
byte[] bytes = new byte[4];
if (fLittleEndian) {
bytes[0] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[3] = (byte)ReadData(context, ref index, data);
} else {
bytes[3] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[0] = (byte)ReadData(context, ref index, data);
}
float res = BitConverter.ToSingle(bytes, 0);
if (context.LanguageContext.FloatFormat == FloatFormat.Unknown) {
if (float.IsNaN(res) || float.IsInfinity(res)) {
throw PythonOps.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
}
}
return res;
}
internal static int CreateIntValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
byte b3 = (byte)ReadData(context, ref index, data);
byte b4 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (int)((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (int)((b1 << 24) | (b2 << 16) | (b3 << 8) | b4);
}
internal static uint CreateUIntValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
byte b1 = (byte)ReadData(context, ref index, data);
byte b2 = (byte)ReadData(context, ref index, data);
byte b3 = (byte)ReadData(context, ref index, data);
byte b4 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (uint)((b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (uint)((b1 << 24) | (b2 << 16) | (b3 << 8) | b4);
}
internal static long CreateLongValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
long b1 = (byte)ReadData(context, ref index, data);
long b2 = (byte)ReadData(context, ref index, data);
long b3 = (byte)ReadData(context, ref index, data);
long b4 = (byte)ReadData(context, ref index, data);
long b5 = (byte)ReadData(context, ref index, data);
long b6 = (byte)ReadData(context, ref index, data);
long b7 = (byte)ReadData(context, ref index, data);
long b8 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (long)((b8 << 56) | (b7 << 48) | (b6 << 40) | (b5 << 32) |
(b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (long)((b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) |
(b5 << 24) | (b6 << 16) | (b7 << 8) | b8);
}
internal static ulong CreateULongValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
ulong b1 = (byte)ReadData(context, ref index, data);
ulong b2 = (byte)ReadData(context, ref index, data);
ulong b3 = (byte)ReadData(context, ref index, data);
ulong b4 = (byte)ReadData(context, ref index, data);
ulong b5 = (byte)ReadData(context, ref index, data);
ulong b6 = (byte)ReadData(context, ref index, data);
ulong b7 = (byte)ReadData(context, ref index, data);
ulong b8 = (byte)ReadData(context, ref index, data);
if (fLittleEndian)
return (ulong)((b8 << 56) | (b7 << 48) | (b6 << 40) | (b5 << 32) |
(b4 << 24) | (b3 << 16) | (b2 << 8) | b1);
else
return (ulong)((b1 << 56) | (b2 << 48) | (b3 << 40) | (b4 << 32) |
(b5 << 24) | (b6 << 16) | (b7 << 8) | b8);
}
internal static double CreateDoubleValue(CodeContext/*!*/ context, ref int index, bool fLittleEndian, IList<byte> data) {
byte[] bytes = new byte[8];
if (fLittleEndian) {
bytes[0] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[3] = (byte)ReadData(context, ref index, data);
bytes[4] = (byte)ReadData(context, ref index, data);
bytes[5] = (byte)ReadData(context, ref index, data);
bytes[6] = (byte)ReadData(context, ref index, data);
bytes[7] = (byte)ReadData(context, ref index, data);
} else {
bytes[7] = (byte)ReadData(context, ref index, data);
bytes[6] = (byte)ReadData(context, ref index, data);
bytes[5] = (byte)ReadData(context, ref index, data);
bytes[4] = (byte)ReadData(context, ref index, data);
bytes[3] = (byte)ReadData(context, ref index, data);
bytes[2] = (byte)ReadData(context, ref index, data);
bytes[1] = (byte)ReadData(context, ref index, data);
bytes[0] = (byte)ReadData(context, ref index, data);
}
double res = BitConverter.ToDouble(bytes, 0);
if (context.LanguageContext.DoubleFormat == FloatFormat.Unknown) {
if (double.IsNaN(res) || double.IsInfinity(res)) {
throw PythonOps.ValueError("can't unpack IEEE 754 special value on non-IEEE platform");
}
}
return res;
}
internal static Bytes CreateString(CodeContext/*!*/ context, ref int index, int count, IList<byte> data) {
using var res = new MemoryStream();
for (int i = 0; i < count; i++) {
res.WriteByte(ReadData(context, ref index, data));
}
return Bytes.Make(res.ToArray());
}
internal static Bytes CreatePascalString(CodeContext/*!*/ context, ref int index, int count, IList<byte> data) {
int realLen = (int)ReadData(context, ref index, data);
using var res = new MemoryStream();
for (int i = 0; i < realLen; i++) {
res.WriteByte(ReadData(context, ref index, data));
}
for (int i = realLen; i < count; i++) {
// throw away null bytes
ReadData(context, ref index, data);
}
return Bytes.Make(res.ToArray());
}
private static byte ReadData(CodeContext/*!*/ context, ref int index, IList<byte> data) {
if (index >= data.Count) throw Error(context, "not enough data while reading");
return data[index++];
}
#endregion
#region Misc. Private APIs
internal static int Align(int length, int size) {
return length + (size - 1) & ~(size - 1);
}
private static Exception Error(CodeContext/*!*/ context, string msg) {
return PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState("structerror"), msg);
}
#endregion
}
}
| 46.216994 | 523 | 0.487715 | [
"Apache-2.0"
] | AnandEmbold/ironpython3 | Src/IronPython.Modules/_struct.cs | 65,813 | C# |
using System;
using FarsiLibrary.UnitTest.Helpers;
using FarsiLibrary.Utils.Formatter;
using NUnit.Framework;
using System.Globalization;
using FarsiLibrary.Utils;
namespace FarsiLibrary.UnitTest
{
[TestFixture]
public class PrettyTimeTests
{
[TestCase(-5, "5 days ago", "en-US") ]
[TestCase(5, "5 days from now", "en-US")]
[TestCase(5, "پنج روز بعد", "fa-IR")]
[TestCase(-5, "پنج روز قبل", "fa-IR")]
public void Can_Format_Days(int days, string expected, string cultureName)
{
using (var context = new CultureSwitchContext(new CultureInfo(cultureName)))
{
var datetime = DateTime.Now;
var then = DateTime.Now.AddDays(days);
var pretty = new PrettyTime(datetime);
var result = pretty.Format(then);
Assert.NotNull(result);
Assert.AreEqual(expected, result);
}
}
[TestCase(-5, "moments ago", "en-US")]
[TestCase(5, "moments from now", "en-US")]
[TestCase(5, "چند لحظه بعد", "fa-IR")]
[TestCase(-5, "چند لحظه قبل", "fa-IR")]
public void Can_Format_Seconds(int seconds, string expected, string cultureName)
{
using (var context = new CultureSwitchContext(new CultureInfo(cultureName)))
{
var date = DateTime.Now.AddSeconds(seconds);
var pretty = new PrettyTime();
var result = pretty.Format(date);
Assert.NotNull(result);
Assert.AreEqual(expected, result);
}
}
[TestCase(-10, "10 minutes ago", "en-US")]
[TestCase(10, "10 minutes from now", "en-US")]
[TestCase(10, "ده دقیقه بعد", "fa-IR")]
[TestCase(-10, "ده دقیقه قبل", "fa-IR")]
public void Can_Format_Minutes(int minutes, string expected, string cultureName)
{
using (var context = new CultureSwitchContext(new CultureInfo(cultureName)))
{
var datetime = DateTime.Now;
var then = DateTime.Now.AddMinutes(minutes);
var pretty = new PrettyTime(datetime);
var result = pretty.Format(then);
Assert.NotNull(result);
Assert.AreEqual(expected, result);
}
}
[TestCase(-2, "2 hours ago", "en-US")]
[TestCase(2, "2 hours from now", "en-US")]
[TestCase(2, "دو ساعت بعد", "fa-IR")]
[TestCase(-2, "دو ساعت قبل", "fa-IR")]
public void Can_Format_Hours(int hours, string expected, string cultureName)
{
using (var context = new CultureSwitchContext(new CultureInfo(cultureName)))
{
var datetime = DateTime.Now;
var then = DateTime.Now.AddHours(hours);
var pretty = new PrettyTime(datetime);
var result = pretty.Format(then);
Assert.NotNull(result);
Assert.AreEqual(expected, result);
}
}
[TestCase(-2, "1 year ago", "en-US")]
[TestCase(2, "2 years from now", "en-US")]
[TestCase(50, "5 decades from now", "en-US")]
[TestCase(100, "10 decades from now", "en-US")]
[TestCase(101, "1 century from now", "en-US")]
[TestCase(-2, "يک سال قبل", "fa-IR")]
[TestCase(2, "دو سال بعد", "fa-IR")]
[TestCase(50, "پنج دهه بعد", "fa-IR")]
[TestCase(100, "ده دهه بعد", "fa-IR")]
[TestCase(101, "يک قرن بعد", "fa-IR")]
public void Can_Format_Years(int years, string expected, string cultureName)
{
using (var context = new CultureSwitchContext(new CultureInfo(cultureName)))
{
var datetime = DateTime.Now;
var then = DateTime.Now.AddYears(years);
var pretty = new PrettyTime(datetime);
var result = pretty.Format(then);
Assert.NotNull(result);
Assert.AreEqual(expected, result);
}
}
[Test]
public void Can_Compare_Two_Dates()
{
var from = new DateTime(2000, 1, 1);
var to = new DateTime(2001, 1, 1);
var duration = new PrettyTime(to).Format(from);
Assert.AreEqual("1 year ago", duration);
}
[Test]
public void Can_Compare_Two_Dates_Regardless_Of_Precedence()
{
var from = new DateTime(2000, 1, 1);
var to = new DateTime(2001, 1, 1);
var duration = new PrettyTime(from).Format(to);
Assert.AreEqual("1 year from now", duration);
}
[Test]
public void Default_Comparison_Compares_To_DateTimeNow()
{
var justNow = new PrettyTime().Format(DateTime.Now);
Assert.AreEqual("moments from now", justNow);
}
[Test]
public void Can_Convert_Dates_Using_ExtensionMethod()
{
var date = DateTime.Now;
var pretty = date.ToPrettyTime();
Assert.AreEqual("moments from now", pretty);
}
}
} | 34.105263 | 88 | 0.54321 | [
"MIT"
] | SKamalou/FarsiLibrary | FarsiLibrary.UnitTest/PrettyTimeTests.cs | 5,303 | C# |
// Copyright (c) Gurmit Teotia. Please see the LICENSE file in the project root for license information.
using System.Collections.Generic;
using Amazon.SimpleWorkflow.Model;
namespace Guflow.Decider
{
public class TimerFiredEvent :TimerEvent
{
internal TimerFiredEvent(HistoryEvent timerFiredEvent, IEnumerable<HistoryEvent> allHistoryEvents)
:base(timerFiredEvent)
{
var eventAttributes =timerFiredEvent.TimerFiredEventAttributes;
PopulateProperties(eventAttributes.StartedEventId, allHistoryEvents);
}
internal override WorkflowAction Interpret(IWorkflow workflow)
{
return workflow.WorkflowAction(this);
}
internal override WorkflowAction DefaultAction(IWorkflowDefaultActions defaultActions)
{
return defaultActions.Continue(this);
}
internal override bool CanTriggerSignalTimeout => SignalTriggerEventId != 0;
}
} | 36.074074 | 106 | 0.710472 | [
"Apache-2.0"
] | Seekatar/guflow | Guflow/Decider/Timer/TimerFiredEvent.cs | 976 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace CarRemote.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new CarRemote.App());
}
}
}
| 22.821429 | 52 | 0.729264 | [
"MIT"
] | iruel865/Netduino.Samples | RemoteCar/CarRemote/CarRemote/CarRemote.UWP/MainPage.xaml.cs | 641 | C# |
using System.Collections.Generic;
using System.Linq;
using StockportWebapp.Models;
using StockportWebapp.Utils;
namespace StockportWebapp.ViewModels
{
public class GroupResults
{
public List<Group> Groups = new List<Group>();
public Pagination Pagination { get; set; }
public QueryUrl CurrentUrl { get; private set; }
public IFilteredUrl FilteredUrl { get; private set; }
public List<GroupCategory> Categories = new List<GroupCategory>();
public List<GroupSubCategory> AvailableSubCategories = new List<GroupSubCategory>();
public List<string> SubCategories = new List<string>();
public string Tag { get; set; } = string.Empty;
public string KeepTag { get; set; } = string.Empty;
public PrimaryFilter PrimaryFilter { set; get; } = new PrimaryFilter();
public bool GetInvolved { get; set; }
public string OrganisationName { get; set; }
public GroupResults() { }
public void AddFilteredUrl(IFilteredUrl filteredUrl)
{
FilteredUrl = filteredUrl;
}
public void AddQueryUrl(QueryUrl queryUrl)
{
CurrentUrl = queryUrl;
}
public RefineByBar RefineByBar()
{
var bar = new RefineByBar
{
ShowLocation = false,
KeepLocationQueryValues = true,
MobileFilterText = "Filter",
Filters = new List<RefineByFilters>()
};
var subCategories = new RefineByFilters
{
Label = "Subcategories",
Mandatory = false,
Name = "subcategories",
Items = new List<RefineByFilterItems>()
};
if (AvailableSubCategories != null && AvailableSubCategories.Any())
{
var distinctSubcategories = AvailableSubCategories.GroupBy(c => c.Slug).Select(c => c.First());
foreach (var cat in distinctSubcategories.OrderBy(c => c.Name))
{
subCategories.Items.Add(new RefineByFilterItems { Label = cat.Name, Checked = SubCategories.Any(c => c.ToLower() == cat.Slug.ToLower()), Value = cat.Slug });
}
bar.Filters.Add(subCategories);
}
var getInvolved = new RefineByFilters
{
Label = "Get involved",
Mandatory = false,
Name = "getinvolved",
Items = new List<RefineByFilterItems>
{
new RefineByFilterItems { Label = "Volunteering opportunities", Checked = GetInvolved, Value = "yes" }
}
};
bar.Filters.Add(getInvolved);
if (!string.IsNullOrEmpty(KeepTag) || !string.IsNullOrEmpty(Tag))
{
var organisation = new RefineByFilters
{
Label = "Organisation",
Mandatory = false,
Name = "tag",
Items = new List<RefineByFilterItems>
{
new RefineByFilterItems { Label = OrganisationName, Checked = !string.IsNullOrEmpty(Tag), Value = KeepTag }
}
};
bar.Filters.Add(organisation);
}
return bar;
}
}
}
| 35.112245 | 177 | 0.533856 | [
"MIT"
] | smbc-digital/iag-webapp | src/StockportWebapp/ViewModels/GroupResults.cs | 3,443 | C# |
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Web.Mvc;
using WebMatrix.WebData;
using AzureMediaPortal.Models;
namespace AzureMediaPortal.Filters
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
}
| 39.45098 | 207 | 0.618787 | [
"Apache-2.0"
] | StephCourtney/Project | AzureMediaPortal/Filters/InitializeSimpleMembershipAttribute.cs | 2,014 | C# |
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace WebGL
{
// ReSharper disable InconsistentNaming
[SuppressUnmanagedCodeSecurity]
internal static class EGL
{
/* EGL Versioning */
public const UInt16 EGL_VERSION_1_0 = 1;
public const UInt16 EGL_VERSION_1_1 = 1;
public const UInt16 EGL_VERSION_1_2 = 1;
public const UInt16 EGL_VERSION_1_3 = 1;
public const UInt16 EGL_VERSION_1_4 = 1;
/* EGL Enumerants. Bitmasks and other exceptional cases aside, most
* enums are assigned unique values starting at 0x3000. */
/* EGL aliases */
public const UInt16 EGL_FALSE = 0;
public const UInt16 EGL_TRUE = 1;
/* Out-of-band handle values */
public const UInt16 EGL_DEFAULT_DISPLAY = 0;
public const UInt16 EGL_NO_CONTEXT = 0;
public const UInt16 EGL_NO_DISPLAY = 0;
public const UInt16 EGL_NO_SURFACE = 0;
/* Out-of-band attribute value */
public const UInt16 EGL_DONT_CARE = 0xFFFF;
/* Errors / GetError return values */
public const UInt16 EGL_SUCCESS = 0x3000;
public const UInt16 EGL_NOT_INITIALIZED = 0x3001;
public const UInt16 EGL_BAD_ACCESS = 0x3002;
public const UInt16 EGL_BAD_ALLOC = 0x3003;
public const UInt16 EGL_BAD_ATTRIBUTE = 0x3004;
public const UInt16 EGL_BAD_CONFIG = 0x3005;
public const UInt16 EGL_BAD_CONTEXT = 0x3006;
public const UInt16 EGL_BAD_CURRENT_SURFACE = 0x3007;
public const UInt16 EGL_BAD_DISPLAY = 0x3008;
public const UInt16 EGL_BAD_MATCH = 0x3009;
public const UInt16 EGL_BAD_NATIVE_PIXMAP = 0x300A;
public const UInt16 EGL_BAD_NATIVE_WINDOW = 0x300B;
public const UInt16 EGL_BAD_PARAMETER = 0x300C;
public const UInt16 EGL_BAD_SURFACE = 0x300D;
public const UInt16 EGL_CONTEXT_LOST = 0x300E; /* EGL 1.1 - IMG_power_management */
/* Reserved 0x300F-0x301F for additional errors */
/* Config attributes */
public const UInt16 EGL_BUFFER_SIZE = 0x3020;
public const UInt16 EGL_ALPHA_SIZE = 0x3021;
public const UInt16 EGL_BLUE_SIZE = 0x3022;
public const UInt16 EGL_GREEN_SIZE = 0x3023;
public const UInt16 EGL_RED_SIZE = 0x3024;
public const UInt16 EGL_DEPTH_SIZE = 0x3025;
public const UInt16 EGL_STENCIL_SIZE = 0x3026;
public const UInt16 EGL_CONFIG_CAVEAT = 0x3027;
public const UInt16 EGL_CONFIG_ID = 0x3028;
public const UInt16 EGL_LEVEL = 0x3029;
public const UInt16 EGL_MAX_PBUFFER_HEIGHT = 0x302A;
public const UInt16 EGL_MAX_PBUFFER_PIXELS = 0x302B;
public const UInt16 EGL_MAX_PBUFFER_WIDTH = 0x302C;
public const UInt16 EGL_NATIVE_RENDERABLE = 0x302D;
public const UInt16 EGL_NATIVE_VISUAL_ID = 0x302E;
public const UInt16 EGL_NATIVE_VISUAL_TYPE = 0x302F;
public const UInt16 EGL_SAMPLES = 0x3031;
public const UInt16 EGL_SAMPLE_BUFFERS = 0x3032;
public const UInt16 EGL_SURFACE_TYPE = 0x3033;
public const UInt16 EGL_TRANSPARENT_TYPE = 0x3034;
public const UInt16 EGL_TRANSPARENT_BLUE_VALUE = 0x3035;
public const UInt16 EGL_TRANSPARENT_GREEN_VALUE = 0x3036;
public const UInt16 EGL_TRANSPARENT_RED_VALUE = 0x3037;
public const UInt16 EGL_NONE = 0x3038; /* Attrib list terminator */
public const UInt16 EGL_BIND_TO_TEXTURE_RGB = 0x3039;
public const UInt16 EGL_BIND_TO_TEXTURE_RGBA = 0x303A;
public const UInt16 EGL_MIN_SWAP_INTERVAL = 0x303B;
public const UInt16 EGL_MAX_SWAP_INTERVAL = 0x303C;
public const UInt16 EGL_LUMINANCE_SIZE = 0x303D;
public const UInt16 EGL_ALPHA_MASK_SIZE = 0x303E;
public const UInt16 EGL_COLOR_BUFFER_TYPE = 0x303F;
public const UInt16 EGL_RENDERABLE_TYPE = 0x3040;
public const UInt16 EGL_MATCH_NATIVE_PIXMAP = 0x3041; /* Pseudo-attribute (not queryable) */
public const UInt16 EGL_CONFORMANT = 0x3042;
/* Reserved 0x3041-0x304F for additional config attributes */
/* Config attribute values */
public const UInt16 EGL_SLOW_CONFIG = 0x3050; /* EGL_CONFIG_CAVEAT value */
public const UInt16 EGL_NON_CONFORMANT_CONFIG = 0x3051; /* EGL_CONFIG_CAVEAT value */
public const UInt16 EGL_TRANSPARENT_RGB = 0x3052; /* EGL_TRANSPARENT_TYPE value */
public const UInt16 EGL_RGB_BUFFER = 0x308E; /* EGL_COLOR_BUFFER_TYPE value */
public const UInt16 EGL_LUMINANCE_BUFFER = 0x308F; /* EGL_COLOR_BUFFER_TYPE value */
/* More config attribute values, for EGL_TEXTURE_FORMAT */
public const UInt16 EGL_NO_TEXTURE = 0x305C;
public const UInt16 EGL_TEXTURE_RGB = 0x305D;
public const UInt16 EGL_TEXTURE_RGBA = 0x305E;
public const UInt16 EGL_TEXTURE_2D = 0x305F;
/* Config attribute mask bits */
public const UInt16 EGL_PBUFFER_BIT = 0x0001; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_PIXMAP_BIT = 0x0002; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_WINDOW_BIT = 0x0004; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_VG_COLORSPACE_LINEAR_BIT = 0x0020; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_VG_ALPHA_FORMAT_PRE_BIT = 0x0040; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_MULTISAMPLE_RESOLVE_BOX_BIT = 0x0200; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_SWAP_BEHAVIOR_PRESERVED_BIT = 0x0400; /* EGL_SURFACE_TYPE mask bits */
public const UInt16 EGL_OPENGL_ES_BIT = 0x0001; /* EGL_RENDERABLE_TYPE mask bits */
public const UInt16 EGL_OPENVG_BIT = 0x0002; /* EGL_RENDERABLE_TYPE mask bits */
public const UInt16 EGL_OPENGL_ES2_BIT = 0x0004; /* EGL_RENDERABLE_TYPE mask bits */
public const UInt16 EGL_OPENGL_BIT = 0x0008; /* EGL_RENDERABLE_TYPE mask bits */
/* QueryString targets */
public const UInt16 EGL_VENDOR = 0x3053;
public const UInt16 EGL_VERSION = 0x3054;
public const UInt16 EGL_EXTENSIONS = 0x3055;
public const UInt16 EGL_CLIENT_APIS = 0x308D;
/* QuerySurface / SurfaceAttrib / CreatePbufferSurface targets */
public const UInt16 EGL_HEIGHT = 0x3056;
public const UInt16 EGL_WIDTH = 0x3057;
public const UInt16 EGL_LARGEST_PBUFFER = 0x3058;
public const UInt16 EGL_TEXTURE_FORMAT = 0x3080;
public const UInt16 EGL_TEXTURE_TARGET = 0x3081;
public const UInt16 EGL_MIPMAP_TEXTURE = 0x3082;
public const UInt16 EGL_MIPMAP_LEVEL = 0x3083;
public const UInt16 EGL_RENDER_BUFFER = 0x3086;
public const UInt16 EGL_VG_COLORSPACE = 0x3087;
public const UInt16 EGL_VG_ALPHA_FORMAT = 0x3088;
public const UInt16 EGL_HORIZONTAL_RESOLUTION = 0x3090;
public const UInt16 EGL_VERTICAL_RESOLUTION = 0x3091;
public const UInt16 EGL_PIXEL_ASPECT_RATIO = 0x3092;
public const UInt16 EGL_SWAP_BEHAVIOR = 0x3093;
public const UInt16 EGL_MULTISAMPLE_RESOLVE = 0x3099;
/* EGL_RENDER_BUFFER values / BindTexImage / ReleaseTexImage buffer targets */
public const UInt16 EGL_BACK_BUFFER = 0x3084;
public const UInt16 EGL_SINGLE_BUFFER = 0x3085;
/* OpenVG color spaces */
public const UInt16 EGL_VG_COLORSPACE_sRGB = 0x3089; /* EGL_VG_COLORSPACE value */
public const UInt16 EGL_VG_COLORSPACE_LINEAR = 0x308A; /* EGL_VG_COLORSPACE value */
/* OpenVG alpha formats */
public const UInt16 EGL_VG_ALPHA_FORMAT_NONPRE = 0x308B; /* EGL_ALPHA_FORMAT value */
public const UInt16 EGL_VG_ALPHA_FORMAT_PRE = 0x308C; /* EGL_ALPHA_FORMAT value */
/* Constant scale factor by which fractional display resolutions &
* aspect ratio are scaled when queried as integer values.
*/
public const UInt16 EGL_DISPLAY_SCALING = 10000;
/* Unknown display resolution/aspect ratio */
public const UInt16 EGL_UNKNOWN = 0xFFFF;
/* Back buffer swap behaviors */
public const UInt16 EGL_BUFFER_PRESERVED = 0x3094; /* EGL_SWAP_BEHAVIOR value */
public const UInt16 EGL_BUFFER_DESTROYED = 0x3095; /* EGL_SWAP_BEHAVIOR value */
/* CreatePbufferFromClientBuffer buffer types */
public const UInt16 EGL_OPENVG_IMAGE = 0x3096;
/* QueryContext targets */
public const UInt16 EGL_CONTEXT_CLIENT_TYPE = 0x3097;
/* CreateContext attributes */
public const UInt16 EGL_CONTEXT_CLIENT_VERSION = 0x3098;
/* Multisample resolution behaviors */
public const UInt16 EGL_MULTISAMPLE_RESOLVE_DEFAULT = 0x309A; /* EGL_MULTISAMPLE_RESOLVE value */
public const UInt16 EGL_MULTISAMPLE_RESOLVE_BOX = 0x309B; /* EGL_MULTISAMPLE_RESOLVE value */
/* BindAPI/QueryAPI targets */
public const UInt16 EGL_OPENGL_ES_API = 0x30A0;
public const UInt16 EGL_OPENVG_API = 0x30A1;
public const UInt16 EGL_OPENGL_API = 0x30A2;
/* GetCurrentSurface targets */
public const UInt16 EGL_DRAW = 0x3059;
public const UInt16 EGL_READ = 0x305A;
/* WaitNative engines */
public const UInt16 EGL_CORE_NATIVE_ENGINE = 0x305B;
/* EGL 1.2 tokens renamed for consistency in EGL 1.3 */
public const UInt16 EGL_COLORSPACE = EGL_VG_COLORSPACE;
public const UInt16 EGL_ALPHA_FORMAT = EGL_VG_ALPHA_FORMAT;
public const UInt16 EGL_COLORSPACE_sRGB = EGL_VG_COLORSPACE_sRGB;
public const UInt16 EGL_COLORSPACE_LINEAR = EGL_VG_COLORSPACE_LINEAR;
public const UInt16 EGL_ALPHA_FORMAT_NONPRE = EGL_VG_ALPHA_FORMAT_NONPRE;
public const UInt16 EGL_ALPHA_FORMAT_PRE = EGL_VG_ALPHA_FORMAT_PRE;
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern Int32 eglGetError();
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern IntPtr eglGetDisplay(IntPtr display_id);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglInitialize(IntPtr dpy, out Int32 major, out Int32 minor);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglTerminate(IntPtr dpy);
[DllImport("libEGL.dll", EntryPoint = "eglQueryString", ExactSpelling = true)]
private static extern IntPtr _eglQueryString(IntPtr dpy, Int32 name);
public static String eglQueryString(IntPtr dpy, Int32 name)
{
return Marshal.PtrToStringAnsi(_eglQueryString(dpy, name));
}
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglGetConfigs(IntPtr dpy, IntPtr[] configs, Int32 config_size, out Int32 num_config);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglChooseConfig(IntPtr dpy, Int32[] attrib_list, IntPtr[] configs, Int32 config_size, out Int32 num_config);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern IntPtr eglCreateWindowSurface(IntPtr dpy, IntPtr config, IntPtr win, Int32[] attrib_list);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglDestroySurface(IntPtr dpy, IntPtr surface);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern IntPtr eglCreateContext(IntPtr dpy, IntPtr config, IntPtr share_context, Int32[] attrib_list);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglDestroyContext(IntPtr dpy, IntPtr ctx);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglMakeCurrent(IntPtr dpy, IntPtr draw, IntPtr read, IntPtr ctx);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglSwapBuffers(IntPtr dpy, IntPtr surface);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern UInt32 eglSwapInterval(IntPtr dpy, Int32 interval);
[DllImport("libEGL.dll", ExactSpelling = true)]
public static extern IntPtr eglGetProcAddress(String procname);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglGetConfigAttrib(IntPtr dpy, IntPtr config, Int32 attribute, out Int32 value);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern IntPtr eglCreatePbufferSurface(IntPtr dpy, IntPtr config, Int32[] attrib_list);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern IntPtr eglCreatePixmapSurface(IntPtr dpy, IntPtr config, IntPtr pixmap, Int32[] attrib_list);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglQuerySurface(IntPtr dpy, IntPtr surface, Int32 attribute, out Int32 value);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglBindAPI(UInt32 api);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglQueryAPI();
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglWaitClient();
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglReleaseThread();
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern IntPtr eglCreatePbufferFromClientBuffer(IntPtr dpy, UInt32 buftype, IntPtr buffer, IntPtr config, Int32[] attrib_list);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglSurfaceAttrib(IntPtr dpy, IntPtr surface, Int32 attribute, Int32 value);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglBindTexImage(IntPtr dpy, IntPtr surface, Int32 buffer);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglReleaseTexImage(IntPtr dpy, IntPtr surface, Int32 buffer);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern IntPtr eglGetCurrentContext();
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern IntPtr eglGetCurrentSurface(Int32 readdraw);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern IntPtr eglGetCurrentDisplay();
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglQueryContext(IntPtr dpy, IntPtr ctx, Int32 attribute, out Int32 value);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglWaitGL();
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglWaitNative(Int32 engine);
[DllImport("libEGL.dll", ExactSpelling = true)]
private static extern UInt32 eglCopyBuffers(IntPtr dpy, IntPtr surface, IntPtr target);
}
// ReSharper restore InconsistentNaming
}
| 48.754045 | 149 | 0.702489 | [
"Apache-2.0"
] | jdarc/webgl.net | WebGL/native/EGL.cs | 15,067 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using MasteringEFCore.QueryObjectPattern.Final.Data;
using MasteringEFCore.QueryObjectPattern.Final.Models;
using Microsoft.AspNetCore.Authorization;
namespace MasteringEFCore.QueryObjectPattern.Final.Controllers
{
//[Authorize(Roles = "Administrators")]
public class PeopleController : Controller
{
private readonly BlogContext _context;
public PeopleController(BlogContext context)
{
_context = context;
}
// GET: People
public async Task<IActionResult> Index()
{
return View(await _context.People.ToListAsync());
}
// GET: People/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var person = await _context.People
.SingleOrDefaultAsync(m => m.Id == id);
if (person == null)
{
return NotFound();
}
return View(person);
}
// GET: People/Create
public IActionResult Create()
{
return View();
}
// POST: People/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,NickName,Url,Biography,ImageUrl")] Person person)
{
if (ModelState.IsValid)
{
_context.Add(person);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(person);
}
// GET: People/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var person = await _context.People.SingleOrDefaultAsync(m => m.Id == id);
if (person == null)
{
return NotFound();
}
return View(person);
}
// POST: People/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,FirstName,LastName,NickName,Url,Biography,ImageUrl")] Person person)
{
if (id != person.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(person);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PersonExists(person.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(person);
}
// GET: People/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var person = await _context.People
.SingleOrDefaultAsync(m => m.Id == id);
if (person == null)
{
return NotFound();
}
return View(person);
}
// POST: People/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var person = await _context.People.SingleOrDefaultAsync(m => m.Id == id);
_context.People.Remove(person);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
private bool PersonExists(int id)
{
return _context.People.Any(e => e.Id == id);
}
}
}
| 29.391026 | 132 | 0.514286 | [
"MIT"
] | PacktPublishing/Mastering-Entity-Framework-Core | Chapter 8/Final/MasteringEFCore.QueryObjectPattern.Final/Controllers/PeopleController.cs | 4,585 | C# |
using System;
//using System.Collections.Generic;
using System.Linq;
namespace Tutorial_Null.Lesson1_2
{
class Main
{
public void Run()
{
Console.WriteLine($"{new Person().name}");
}
}
class Person
{
public string name = String.Empty;
}
}
| 17.210526 | 55 | 0.535168 | [
"CC0-1.0"
] | ytyaru/CSharp.Tutorial.Null.20191028092251 | src/Tutorial_Null/Lesson1_2/Main.cs | 329 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.10
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
namespace Noesis
{
public class StatusBar : ItemsControl {
internal new static StatusBar CreateProxy(IntPtr cPtr, bool cMemoryOwn) {
return new StatusBar(cPtr, cMemoryOwn);
}
internal StatusBar(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) {
}
internal static HandleRef getCPtr(StatusBar obj) {
return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
}
public StatusBar() {
}
protected override IntPtr CreateCPtr(Type type, out bool registerExtend) {
if ((object)type.TypeHandle == typeof(StatusBar).TypeHandle) {
registerExtend = false;
return NoesisGUI_PINVOKE.new_StatusBar();
}
else {
return base.CreateExtendCPtr(type, out registerExtend);
}
}
public static DependencyProperty SeparatorStyleKey {
get {
IntPtr cPtr = NoesisGUI_PINVOKE.StatusBar_SeparatorStyleKey_get();
if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
}
}
new internal static IntPtr GetStaticType() {
IntPtr ret = NoesisGUI_PINVOKE.StatusBar_GetStaticType();
if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
return ret;
}
internal new static IntPtr Extend(string typeName) {
IntPtr nativeType = NoesisGUI_PINVOKE.Extend_StatusBar(Marshal.StringToHGlobalAnsi(typeName));
if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
return nativeType;
}
}
}
| 30.895522 | 114 | 0.683092 | [
"MIT"
] | WaveEngine/Extensions | WaveEngine.NoesisGUI/Shared/Proxies/StatusBar.cs | 2,070 | C# |
namespace JudoPayDotNet.Errors
{
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable UnusedMember.Global
/// <summary>
/// This model represents one issue encountered with a supplied field
/// </summary>
public class JudoModelError
{
public string FieldName { get; set; }
public string ErrorMessage { get; set; }
public string DetailErrorMessage { get; set; }
}
// ReSharper restore UnusedMember.Global
// ReSharper restore UnusedAutoPropertyAccessor.Global
}
| 31.764706 | 70 | 0.703704 | [
"MIT"
] | Judopay/DotNetSDK | JudoPayDotNet/Errors/JudoModelError.cs | 542 | C# |
using System.ComponentModel.DataAnnotations;
using DayTripper.Data.Common.Models;
namespace DayTripper.Data.Models
{
public class Sector : BaseDeletableModel<int>
{
[Required]
[MaxLength(100)]
public string Name { get; set; }
public int CragId { get; set; }
[Required]
public Crag Crag { get; set; }
}
}
| 19.421053 | 49 | 0.620596 | [
"MIT"
] | todor-tsankov/day-tripper | Server/Data/DayTripper.Data.Models/Sector.cs | 371 | C# |
/* ========================================================================
*
* This file is part of the DM Jukebox project.
* Copyright (c) 2016 Joe Clapis. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ====================================================================== */
using System;
using System.Runtime.InteropServices;
namespace DMJukebox.Interop
{
/// <summary>
/// This is a utility class that holds the P/Invoke wrappers for libavcodec.
/// </summary>
/// <remarks>
/// For more information, please see the documentation at
/// https://www.ffmpeg.org/doxygen/trunk/index.html
/// or the source code at https://github.com/FFmpeg/FFmpeg.
/// </remarks>
internal static class AVCodecInterop
{
/// <summary>
/// The DLL for Windows
/// </summary>
private const string WindowsAVCodecLibrary = "avcodec-57.dll";
/// <summary>
/// The SO for Linux
/// </summary>
private const string LinuxAVCodecLibrary = "avcodec-57.so";
/// <summary>
/// The Dylib for OSX
/// </summary>
private const string MacAVCodecLibrary = "avcodec-57.dylib";
// These regions contain the DllImport function definitions for each OS. Since we can't really set
// the path of DllImport dynamically (and loading them dynamically using LoadLibrary / dlopen is complicated
// to manage cross-platform), we have to pre-define them based on the names of the libraries above.
#region Windows Functions
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(avcodec_find_decoder), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr avcodec_find_decoder_windows(AVCodecID id);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(avcodec_open2), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_open2_windows(IntPtr avctx, IntPtr codec, ref IntPtr options);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(avcodec_send_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_send_packet_windows(IntPtr avctx, IntPtr avpkt);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(avcodec_receive_frame), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_receive_frame_windows(IntPtr avctx, IntPtr frame);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(av_packet_alloc), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr av_packet_alloc_windows();
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(av_packet_free), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_packet_free_windows(ref IntPtr pkt);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(av_new_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR av_new_packet_windows(IntPtr pkt, int size);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(av_init_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_init_packet_windows(IntPtr pkt);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(av_packet_unref), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_packet_unref_windows(IntPtr pkt);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(avcodec_flush_buffers), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void avcodec_flush_buffers_windows(IntPtr avctx);
[DllImport(WindowsAVCodecLibrary, EntryPoint = nameof(av_get_exact_bits_per_sample), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int av_get_exact_bits_per_sample_windows(AVCodecID codec_id);
#endregion
#region Linux Functions
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(avcodec_find_decoder), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr avcodec_find_decoder_linux(AVCodecID id);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(avcodec_open2), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_open2_linux(IntPtr avctx, IntPtr codec, ref IntPtr options);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(avcodec_send_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_send_packet_linux(IntPtr avctx, IntPtr avpkt);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(avcodec_receive_frame), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_receive_frame_linux(IntPtr avctx, IntPtr frame);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(av_packet_alloc), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr av_packet_alloc_linux();
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(av_packet_free), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_packet_free_linux(ref IntPtr pkt);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(av_new_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR av_new_packet_linux(IntPtr pkt, int size);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(av_init_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_init_packet_linux(IntPtr pkt);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(av_packet_unref), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_packet_unref_linux(IntPtr pkt);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(avcodec_flush_buffers), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void avcodec_flush_buffers_linux(IntPtr avctx);
[DllImport(LinuxAVCodecLibrary, EntryPoint = nameof(av_get_exact_bits_per_sample), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int av_get_exact_bits_per_sample_linux(AVCodecID codec_id);
#endregion
#region OSX Functions
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(avcodec_find_decoder), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr avcodec_find_decoder_osx(AVCodecID id);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(avcodec_open2), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_open2_osx(IntPtr avctx, IntPtr codec, ref IntPtr options);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(avcodec_send_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_send_packet_osx(IntPtr avctx, IntPtr avpkt);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(avcodec_receive_frame), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR avcodec_receive_frame_osx(IntPtr avctx, IntPtr frame);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(av_packet_alloc), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern IntPtr av_packet_alloc_osx();
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(av_packet_free), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_packet_free_osx(ref IntPtr pkt);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(av_new_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern AVERROR av_new_packet_osx(IntPtr pkt, int size);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(av_init_packet), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_init_packet_osx(IntPtr pkt);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(av_packet_unref), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void av_packet_unref_osx(IntPtr pkt);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(avcodec_flush_buffers), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern void avcodec_flush_buffers_osx(IntPtr avctx);
[DllImport(MacAVCodecLibrary, EntryPoint = nameof(av_get_exact_bits_per_sample), CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
private static extern int av_get_exact_bits_per_sample_osx(AVCodecID codec_id);
#endregion
#region Delegates and Platform-Dependent Loading
// These delegates all represent the function signatures for the libavcodec methods I need to call.
private delegate IntPtr avcodec_find_decoder_delegate(AVCodecID id);
private delegate AVERROR avcodec_open2_delegate(IntPtr avctx, IntPtr codec, ref IntPtr options);
private delegate AVERROR avcodec_send_packet_delegate(IntPtr avctx, IntPtr avpkt);
private delegate AVERROR avcodec_receive_frame_delegate(IntPtr avctx, IntPtr frame);
private delegate IntPtr av_packet_alloc_delegate();
private delegate void av_packet_free_delegate(ref IntPtr pkt);
private delegate AVERROR av_new_packet_delegate(IntPtr pkt, int size);
private delegate void av_init_packet_delegate(IntPtr pkt);
private delegate void av_packet_unref_delegate(IntPtr pkt);
private delegate void avcodec_flush_buffers_delegate(IntPtr avctx);
private delegate int av_get_exact_bits_per_sample_delegate(AVCodecID codec_id);
// These fields represent function pointers towards each of the extern functions. They get set
// to the proper platform-specific functions by the static constructor. For example, if this is
// running on a Windows machine, each of these pointers will point to the various XXX_windows
// extern functions listed above.
private static avcodec_find_decoder_delegate avcodec_find_decoder_impl;
private static avcodec_open2_delegate avcodec_open2_impl;
private static avcodec_send_packet_delegate avcodec_send_packet_impl;
private static avcodec_receive_frame_delegate avcodec_receive_frame_impl;
private static av_packet_alloc_delegate av_packet_alloc_impl;
private static av_packet_free_delegate av_packet_free_impl;
private static av_new_packet_delegate av_new_packet_func;
private static av_init_packet_delegate av_init_packet_impl;
private static av_packet_unref_delegate av_packet_unref_impl;
private static avcodec_flush_buffers_delegate avcodec_flush_buffers_impl;
private static av_get_exact_bits_per_sample_delegate av_get_exact_bits_per_sample_impl;
/// <summary>
/// The static constructor figures out which library to use for P/Invoke based
/// on the current OS platform.
/// </summary>
static AVCodecInterop()
{
NativePathFinder.AddNativeLibraryPathToEnvironmentVariable();
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
avcodec_find_decoder_impl = avcodec_find_decoder_windows;
avcodec_open2_impl = avcodec_open2_windows;
avcodec_send_packet_impl = avcodec_send_packet_windows;
avcodec_receive_frame_impl = avcodec_receive_frame_windows;
av_packet_alloc_impl = av_packet_alloc_windows;
av_packet_free_impl = av_packet_free_windows;
av_new_packet_func = av_new_packet_windows;
av_init_packet_impl = av_init_packet_windows;
av_packet_unref_impl = av_packet_unref_windows;
avcodec_flush_buffers_impl = avcodec_flush_buffers_windows;
av_get_exact_bits_per_sample_impl = av_get_exact_bits_per_sample_windows;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
avcodec_find_decoder_impl = avcodec_find_decoder_linux;
avcodec_open2_impl = avcodec_open2_linux;
avcodec_send_packet_impl = avcodec_send_packet_linux;
avcodec_receive_frame_impl = avcodec_receive_frame_linux;
av_packet_alloc_impl = av_packet_alloc_linux;
av_packet_free_impl = av_packet_free_linux;
av_new_packet_func = av_new_packet_linux;
av_init_packet_impl = av_init_packet_linux;
av_packet_unref_impl = av_packet_unref_linux;
avcodec_flush_buffers_impl = avcodec_flush_buffers_linux;
av_get_exact_bits_per_sample_impl = av_get_exact_bits_per_sample_linux;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
avcodec_find_decoder_impl = avcodec_find_decoder_osx;
avcodec_open2_impl = avcodec_open2_osx;
avcodec_send_packet_impl = avcodec_send_packet_osx;
avcodec_receive_frame_impl = avcodec_receive_frame_osx;
av_packet_alloc_impl = av_packet_alloc_osx;
av_packet_free_impl = av_packet_free_osx;
av_new_packet_func = av_new_packet_osx;
av_init_packet_impl = av_init_packet_osx;
av_packet_unref_impl = av_packet_unref_osx;
avcodec_flush_buffers_impl = avcodec_flush_buffers_osx;
av_get_exact_bits_per_sample_impl = av_get_exact_bits_per_sample_osx;
}
else
{
throw new NotSupportedException();
}
}
#endregion
#region Public API
/// <summary>
/// Returns information about the decoder for the given codec type.
/// </summary>
/// <param name="id">The codec to get the decoder for</param>
/// <returns>(<see cref="AVCodec"/>*) The decoder for the codec type</returns>
public static IntPtr avcodec_find_decoder(AVCodecID id)
{
return avcodec_find_decoder_impl(id);
}
/// <summary>
/// Sets up an <see cref="AVCodecContext"/> with support for the given <see cref="AVCodec"/>.
/// </summary>
/// <param name="avctx">(<see cref="AVCodecContext"/>*) The context to prepare</param>
/// <param name="codec">(<see cref="AVCodec"/>*) The codec to prepare the context with</param>
/// <param name="options">(<see cref="AVDictionary"/>*) Options for the assignment, or
/// <see cref="IntPtr.Zero"/> for the default options.</param>
/// <returns><see cref="AVERROR.AVERROR_SUCCESS"/> on a success, or an error code on a failure.</returns>
public static AVERROR avcodec_open2(IntPtr avctx, IntPtr codec, ref IntPtr options)
{
return avcodec_open2_impl(avctx, codec, ref options);
}
/// <summary>
/// Sends a packet full of encoded audio data from an audio stream to the decoder for decoding.
/// </summary>
/// <param name="avctx">(<see cref="AVCodecContext"/>*) The decoder to decode the packet with</param>
/// <param name="avpkt">(<see cref="AVPacket"/>*) The input packet with the encoded audio data</param>
/// <returns><see cref="AVERROR.AVERROR_SUCCESS"/> on a success, or an error code on a failure.</returns>
public static AVERROR avcodec_send_packet(IntPtr avctx, IntPtr avpkt)
{
return avcodec_send_packet_impl(avctx, avpkt);
}
/// <summary>
/// Retrieves raw, decoded audio from the decoder. Call this after <see cref="avcodec_send_packet(IntPtr, IntPtr)"/>
/// to get the decoded input data.
/// </summary>
/// <param name="avctx">(<see cref="AVCodecContext"/>*) The decoder holding the decoded data</param>
/// <param name="frame">(<see cref="AVFrame"/>*) The output frame to hold the decoded data</param>
/// <returns><see cref="AVERROR.AVERROR_SUCCESS"/> on a success, or an error code on a failure.</returns>
public static AVERROR avcodec_receive_frame(IntPtr avctx, IntPtr frame)
{
return avcodec_receive_frame_impl(avctx, frame);
}
/// <summary>
/// Allocates an <see cref="AVPacket"/> and sets all of its fields to the default values.
/// This doesn't allocate any data buffers though, those have to be done with
/// <see cref="av_new_packet(IntPtr, int)"/>.
/// </summary>
/// <returns>(<see cref="AVPacket"/>*) The new packet</returns>
public static IntPtr av_packet_alloc()
{
return av_packet_alloc_impl();
}
/// <summary>
/// Deletes and frees an <see cref="AVPacket"/>. The pointer to it in <paramref name="pkt"/>
/// will be set to <see cref="IntPtr.Zero"/>.
/// </summary>
/// <param name="pkt">(<see cref="AVPacket"/>*) The packet to free</param>
public static void av_packet_free(ref IntPtr pkt)
{
av_packet_free_impl(ref pkt);
}
/// <summary>
/// Reinitializes an <see cref="AVPacket"/>, setting its fields to the default values
/// and allocating its data buffer with the given size.
/// </summary>
/// <param name="pkt">(<see cref="AVPacket"/>*) The packet to reset</param>
/// <param name="size">The size of the buffer to allocate, in bytes</param>
/// <returns><see cref="AVERROR.AVERROR_SUCCESS"/> on a success, or an error code on a failure.</returns>
public static AVERROR av_new_packet(IntPtr pkt, int size)
{
return av_new_packet_func(pkt, size);
}
/// <summary>
/// Reinitializes an <see cref="AVPacket"/>, setting its fields to the default values
/// but leaving the data buffer alone.
/// </summary>
/// <param name="pkt">(<see cref="AVPacket"/>*) The packet to reset</param>
public static void av_init_packet(IntPtr pkt)
{
av_init_packet_impl(pkt);
}
/// <summary>
/// Wipes an <see cref="AVPacket"/>, resetting the fields to their default values
/// and decrementing the reference counter on the data buffer.
/// </summary>
/// <param name="pkt">(<see cref="AVPacket"/>*) The packet to wipe</param>
public static void av_packet_unref(IntPtr pkt)
{
av_packet_unref_impl(pkt);
}
/// <summary>
/// Wipes and resets the internal state of an <see cref="AVCodecContext"/> and clears
/// out its internal buffers. This should be used after seeking around in a stream,
/// such as restarting it from the beginning.
/// </summary>
/// <param name="avctx">(<see cref="AVCodecContext"/>*) The context to reset</param>
public static void avcodec_flush_buffers(IntPtr avctx)
{
avcodec_flush_buffers_impl(avctx);
}
/// <summary>
/// Returns the precise number of bits that an audio sample will contain, based on the
/// codec it was encoded with. If the number is unknown, this will return zero.
/// </summary>
/// <param name="codec_id">The codec that the sample was encoded with</param>
/// <returns>The number of bits that a frame of audio encoded with the given codec
/// contains, or zero if the amount isn't known.</returns>
public static int av_get_exact_bits_per_sample(AVCodecID codec_id)
{
return av_get_exact_bits_per_sample_impl(codec_id);
}
#endregion
}
}
| 55.292428 | 162 | 0.691174 | [
"Apache-2.0"
] | jclapis/dm-jukebox | DMJukebox.Core/Interop/AVCodecInterop.cs | 21,179 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LootGun : MonoBehaviour
{
private ShootingController shootctrl;
public GameObject bullet;
public AudioSource src;
private bool isPickedUp = false;
// Start is called before the first frame update
void Start()
{
if (src == null)
src = GetComponent<AudioSource>();
isPickedUp = false;
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "Player" && !isPickedUp)
{
AudioManager.Instance.PlayReloadSFX(src,0);
shootctrl = col.GetComponent<ShootingController>();
shootctrl.bulletPrefab = bullet;
isPickedUp = true;
GameManager.MethodDelegate method = DestroyObj;
GameManager.Instance.ExecMethodAfterWaitForSeconds(1,DestroyObj);
}
}
private void DestroyObj()
{
Destroy(gameObject);
}
}
| 22.404255 | 77 | 0.615385 | [
"MIT"
] | WinterPu/CSYE-7270-Game-Repo | CSYE 7270 Final Project/CSYE 7270 Midterm Game/Assets/Scripts/Loot/LootGun.cs | 1,055 | C# |
//
// ImapReplayStream.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2017 Xamarin Inc. (www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
using MimeKit.IO;
using MimeKit.IO.Filters;
namespace UnitTests.Net.Imap {
enum ImapReplayCommandResponse {
OK,
NO,
BAD,
Plus
}
class ImapReplayCommand
{
public string Command { get; private set; }
public byte[] Response { get; private set; }
public ImapReplayCommand (string command, byte[] response)
{
Command = command;
Response = response;
}
public ImapReplayCommand (string command, string resource)
{
Command = command;
using (var stream = GetType ().Assembly.GetManifestResourceStream ("UnitTests.Net.Imap.Resources." + resource)) {
var memory = new MemoryBlockStream ();
using (var filtered = new FilteredStream (memory)) {
filtered.Add (new Unix2DosFilter ());
stream.CopyTo (filtered, 4096);
}
Response = memory.ToArray ();
}
}
public ImapReplayCommand (string command, ImapReplayCommandResponse response)
{
if (response == ImapReplayCommandResponse.Plus) {
Response = Encoding.ASCII.GetBytes ("+\r\n");
Command = command;
return;
}
var tokens = command.Split (' ');
var cmd = (tokens[1] == "UID" ? tokens[2] : tokens[1]).TrimEnd ();
var tag = tokens[0];
var text = string.Format ("{0} {1} {2} completed\r\n", tag, response, cmd);
Response = Encoding.ASCII.GetBytes (text);
Command = command;
}
}
enum ImapReplayState {
SendResponse,
WaitForCommand,
}
class ImapReplayStream : Stream
{
static readonly Encoding Latin1 = Encoding.GetEncoding (28591);
readonly MemoryStream sent = new MemoryStream ();
readonly IList<ImapReplayCommand> commands;
readonly bool testUnixFormat;
ImapReplayState state;
int timeout = 100000;
Stream stream;
bool disposed;
bool asyncIO;
bool isAsync;
int index;
public ImapReplayStream (IList<ImapReplayCommand> commands, bool asyncIO, bool testUnixFormat)
{
stream = GetResponseStream (commands[0]);
state = ImapReplayState.SendResponse;
this.testUnixFormat = testUnixFormat;
this.commands = commands;
this.asyncIO = asyncIO;
}
void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException ("ImapReplayStream");
}
#region implemented abstract members of Stream
public override bool CanRead {
get { return true; }
}
public override bool CanSeek {
get { return true; }
}
public override bool CanWrite {
get { return true; }
}
public override bool CanTimeout {
get { return true; }
}
public override long Length {
get { return stream.Length; }
}
public override long Position {
get { return stream.Position; }
set { throw new NotSupportedException (); }
}
public override int ReadTimeout {
get { return timeout; }
set { timeout = value; }
}
public override int WriteTimeout {
get { return timeout; }
set { timeout = value; }
}
public override int Read (byte[] buffer, int offset, int count)
{
CheckDisposed ();
if (asyncIO) {
Assert.IsTrue (isAsync, "Trying to Read in an async unit test.");
} else {
Assert.IsFalse (isAsync, "Trying to ReadAsync in a non-async unit test.");
}
if (state != ImapReplayState.SendResponse) {
var command = Latin1.GetString (sent.GetBuffer (), 0, (int) sent.Length);
Assert.AreEqual (ImapReplayState.SendResponse, state, "Trying to read before command received. Sent so far: {0}", command);
}
Assert.IsNotNull (stream, "Trying to read when no data available.");
int nread = stream.Read (buffer, offset, count);
if (stream.Position == stream.Length) {
state = ImapReplayState.WaitForCommand;
index++;
}
return nread;
}
public override Task<int> ReadAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
isAsync = true;
try {
return Task.FromResult (Read (buffer, offset, count));
} finally {
isAsync = false;
}
}
Stream GetResponseStream (ImapReplayCommand command)
{
MemoryStream memory;
if (testUnixFormat) {
memory = new MemoryStream ();
using (var filtered = new FilteredStream (memory)) {
filtered.Add (new Dos2UnixFilter ());
filtered.Write (command.Response, 0, command.Response.Length);
filtered.Flush ();
}
memory.Position = 0;
} else {
memory = new MemoryStream (command.Response, false);
}
return memory;
}
public override void Write (byte[] buffer, int offset, int count)
{
CheckDisposed ();
if (asyncIO) {
Assert.IsTrue (isAsync, "Trying to Write in an async unit test.");
} else {
Assert.IsFalse (isAsync, "Trying to WriteAsync in a non-async unit test.");
}
Assert.AreEqual (ImapReplayState.WaitForCommand, state, "Trying to write when a command has already been given.");
sent.Write (buffer, offset, count);
if (sent.Length >= commands[index].Command.Length) {
var command = Latin1.GetString (sent.GetBuffer (), 0, (int) sent.Length);
Assert.AreEqual (commands[index].Command, command, "Commands did not match.");
if (stream != null)
stream.Dispose ();
stream = GetResponseStream (commands[index]);
state = ImapReplayState.SendResponse;
sent.SetLength (0);
}
}
public override Task WriteAsync (byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
isAsync = true;
try {
Write (buffer, offset, count);
return Task.FromResult (true);
} finally {
isAsync = false;
}
}
public override void Flush ()
{
CheckDisposed ();
Assert.IsFalse (asyncIO, "Trying to Flush in an async unit test.");
}
public override Task FlushAsync (CancellationToken cancellationToken)
{
CheckDisposed ();
Assert.IsTrue (asyncIO, "Trying to FlushAsync in a non-async unit test.");
return Task.FromResult (true);
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
#endregion
protected override void Dispose (bool disposing)
{
if (stream != null)
stream.Dispose ();
base.Dispose (disposing);
disposed = true;
}
}
}
| 25.173333 | 127 | 0.687632 | [
"MIT"
] | AntonyZhuc/Emailnig | UnitTests/Net/Imap/ImapReplayStream.cs | 7,552 | C# |
using System;
namespace SocialMediaLogin
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 18.5625 | 69 | 0.609428 | [
"MIT"
] | giovanellij/SocialMediaLogin | WeatherForecast.cs | 297 | 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 GM8_MIUI.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.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;
}
}
}
}
| 35.4 | 151 | 0.580979 | [
"MIT"
] | halitsever/general-mobile-gm8-miui | src/GM8 MIUI/Properties/Settings.Designer.cs | 1,064 | C# |
using System;
using FluentAssertions.Common;
namespace FluentAssertions.Equivalency;
/// <summary>
/// Provides contextual information to an <see cref="IMemberSelectionRule"/>.
/// </summary>
public class MemberSelectionContext
{
private readonly Type compileTimeType;
private readonly Type runtimeType;
private readonly IEquivalencyAssertionOptions options;
public MemberSelectionContext(Type compileTimeType, Type runtimeType, IEquivalencyAssertionOptions options)
{
this.runtimeType = runtimeType;
this.compileTimeType = compileTimeType;
this.options = options;
}
/// <summary>
/// Gets a value indicating whether and which properties should be considered.
/// </summary>
public MemberVisibility IncludedProperties => options.IncludedProperties;
/// <summary>
/// Gets a value indicating whether and which fields should be considered.
/// </summary>
public MemberVisibility IncludedFields => options.IncludedFields;
/// <summary>
/// Gets either the compile-time or run-time type depending on the options provided by the caller.
/// </summary>
public Type Type
{
get
{
Type type = options.UseRuntimeTyping ? runtimeType : compileTimeType;
return type.NullableOrActualType();
}
}
}
| 29.844444 | 111 | 0.697692 | [
"Apache-2.0"
] | IT-VBFK/fluentassertions | Src/FluentAssertions/Equivalency/MemberSelectionContext.cs | 1,343 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.